Take a moment to think about this
This lesson doesn't teach anything new — it's a practice set to test what you learned about prompt engineering, tokens/context windows, and calling AI APIs back in the Basic and Intermediate chapters. Each task is designed to have you hands-on apply a concept from an earlier lesson: writing a good prompt, estimating how many tokens something might cost, and building an API request yourself from the ground up. It's a bit challenging, but still at the foundation level.
Exercises
Task 1: Take a vague prompt for a customer support chatbot persona for a shop ("help customers") and rewrite it into a clear prompt that includes role, context, constraints, and output format. Task 2: Look at the prompt 'Write a 10-sentence summary of Myanmar's historical background' and roughly estimate the token count of the input text (assume about 4 English characters equal 1 token). Then estimate at what point the context would fill up if you kept adding 10 rounds of conversation history with a model that has a 4096-token context window. Task 3: Write a JavaScript function using the fetch API that calls an AI text-completion endpoint, pulling the API key from an environment variable and including error handling (try/catch). Task 4 (optional bonus): Add a temperature parameter to the function above, and explain in a comment how to adjust its value for creative output versus factual output.
Code Example
// Task 3 starter skeleton — fill in the missing parts
async function askAI(userPrompt) {
const apiKey = process.env.AI_API_KEY; // TODO: never hardcode this
try {
const response = await fetch("https://api.example.com/v1/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "example-model-1",
messages: [{ role: "user", content: userPrompt }],
// TODO: add a temperature value here for Task 4
}),
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content;
} catch (err) {
console.error("askAI failed:", err.message);
return null;
}
}
// Task 1 & 2 — write your rewritten prompt and token estimate as comments here:
// const clearPrompt = "...";
// const estimatedTokens = ...;Running the function should return a text response from the AI; if an error occurs, only an error message should show up in the console, without crashing the app.Try it in 5 minutes
Within 5 minutes, actually run the prompt you wrote for Task 1 in the ChatGPT or Claude web UI, and compare the result against the original vague prompt's output.
A quick heads-up
The token estimate here is only a rough approximation — in production, you should rely on the exact count from the tokenizer library provided by the model provider.