Module 2 - Lesson 2c: Temperature Control with Anthropic
Adjusting response creativity with the temperature parameter in Anthropic Claude.
Published: 1/10/2026
Lesson 2c: Temperature Control with Anthropic Claude
Temperature controls how creative or deterministic Claude's responses are. Learn how Anthropic's temperature range differs from OpenAI.
Key Difference from OpenAI
OpenAI: Temperature range is 0.0 to 2.0 Anthropic: Temperature range is 0.0 to 1.0
Code Example
Create src/anthropic/basic-prompt-with-temperature.ts:
import Anthropic from "@anthropic-ai/sdk"; import dotenv from "dotenv"; // Load environment variables dotenv.config(); // Create Anthropic client with typed configuration const anthropic = new Anthropic(); // Async function with proper return type async function basicPromptWithTemperature(): Promise<void> { try { console.log("Testing Anthropic connection..."); // Make API call - response is automatically typed! // Using a system prompt along with user prompt const response = await anthropic.messages.create({ model: "claude-haiku-4-5", max_tokens: 1000, system: "You are a helpful travel assistant.", messages: [{ role: "user", content: "Suggest a travel destination" }], temperature: 0.9, // Higher temperature for more creative responses, try 0.1, 0.5, 0.9 }); console.log("✅ Prompt with Temperature Success!"); // show response usage console.log("Tokens used:"); console.dir(response.usage, { depth: null }); // Check if we got a response if (!response.content || response.content.length === 0) { throw new Error("No content in response"); } // Extract text const textBlocks = response.content.filter( (block) => block.type === "text" ); if (textBlocks.length === 0) { throw new Error("No text content in response"); } console.log( "AI Response:", textBlocks.map((block) => block.text).join("\n") ); } catch (error) { // Proper error handling with type guards if (error instanceof Anthropic.APIError) { console.log("❌ API Error:", error.status, error.message); } else if (error instanceof Error) { console.log("❌ Error:", error.message); } else { console.log("❌ Unknown error occurred"); } } } // Run the test basicPromptWithTemperature().catch((error) => { console.error("Error:", error); });
Run It
pnpm tsx src/anthropic/basic-prompt-with-temperature.ts
Understanding Temperature
Temperature Scale (Anthropic: 0.0 - 1.0)
| Temperature | Behavior | Best For |
|---|---|---|
| 0.0 | Deterministic, same every time | Facts, math, code, analysis |
| 0.3 | Mostly consistent, slight variation | Business writing, documentation |
| 0.5 | Balanced (default) | General conversations |
| 0.7 | More creative, varied | Content creation, storytelling |
| 0.9 | Highly creative, unpredictable | Brainstorming, creative writing |
| 1.0 | Maximum creativity | Poetry, experimental content |
Examples by Temperature
Same Prompt, Different Temperatures
Prompt: "Suggest a travel destination"
Temperature 0.1 (Consistent):
I'd suggest visiting Paris, France. It's a world-renowned destination
known for the Eiffel Tower, Louvre Museum, and excellent cuisine.
Best visited in spring or fall.
Temperature 0.5 (Balanced):
Consider visiting Kyoto, Japan! This historic city offers beautiful
temples, traditional gardens, and authentic cultural experiences.
The cherry blossom season in spring is particularly magical.
Temperature 0.9 (Creative):
How about embarking on an adventure to the enchanting island of Madeira,
Portugal? Imagine yourself hiking through mystical laurel forests,
discovering hidden coastal villages, and savoring the world's most
unique fortified wine while watching dramatic Atlantic sunsets!
When to Use Each Temperature
Low Temperature (0.0 - 0.3)
Use Cases:
- Code generation
- Mathematical calculations
- Factual Q&A
- Data extraction
- Legal/medical text
- API responses requiring consistency
Example:
const response = await anthropic.messages.create({ model: "claude-haiku-4-5", max_tokens: 1000, temperature: 0.1, system: "You are a code generator. Provide accurate TypeScript code.", messages: [{ role: "user", content: "Write a function to calculate fibonacci numbers" }] });
Medium Temperature (0.4 - 0.6)
Use Cases:
- General conversation
- Customer support
- Educational content
- Business communication
- Product descriptions
Example:
const response = await anthropic.messages.create({ model: "claude-haiku-4-5", max_tokens: 1000, temperature: 0.5, system: "You are a friendly customer support agent.", messages: [{ role: "user", content: "How do I reset my password?" }] });
High Temperature (0.7 - 1.0)
Use Cases:
- Creative writing
- Brainstorming
- Marketing copy
- Story generation
- Poetry
- Unique perspectives
Example:
const response = await anthropic.messages.create({ model: "claude-haiku-4-5", max_tokens: 1000, temperature: 0.9, system: "You are a creative writer helping with story ideas.", messages: [{ role: "user", content: "Give me 5 unique sci-fi story concepts" }] });
Experiment: Temperature Comparison
Try this experiment to see temperature in action:
async function compareTemperatures() { const prompt = "Suggest a travel destination in Europe"; const temperatures = [0.1, 0.5, 0.9]; for (const temp of temperatures) { console.log(`\n=== Temperature ${temp} ===`); const response = await anthropic.messages.create({ model: "claude-haiku-4-5", max_tokens: 200, temperature: temp, messages: [{ role: "user", content: prompt }] }); const text = response.content[0].text; console.log(text); } }
OpenAI vs Anthropic Temperature
| Feature | OpenAI | Anthropic |
|---|---|---|
| Range | 0.0 - 2.0 | 0.0 - 1.0 |
| Default | 1.0 | 1.0 |
| Max creativity | 2.0 | 1.0 |
Note: Anthropic's 1.0 is roughly equivalent to OpenAI's 1.5-1.8 in terms of creativity.
Common Mistakes
1. Using Temperature for Tasks Requiring Accuracy
❌ Wrong:
temperature: 0.9, messages: [{ role: "user", content: "What is 234 × 567?" }]
✅ Right:
temperature: 0.0, messages: [{ role: "user", content: "What is 234 × 567?" }]
2. Expecting Identical Responses
Even with temperature 0.0, responses may vary slightly due to:
- Model updates
- Internal randomness
- Context differences
3. Overusing High Temperature
High temperature doesn't always mean better:
- Can produce nonsensical output
- May miss important details
- Reduces reliability
Best Practices
- Start with default (1.0) and adjust based on results
- Use low temperature (0.0-0.3) for deterministic tasks
- Test different temperatures to find optimal setting
- Document your choice in production code
- Consider caching with low temperature for consistency
Key Takeaways
- ✅ Anthropic temperature range is 0.0 - 1.0 (not 0.0 - 2.0)
- ✅ Lower temperature = more consistent, predictable
- ✅ Higher temperature = more creative, varied
- ✅ Choose based on your use case, not "creativity = better"
- ✅ Test and measure results for your specific application
Next Steps
Learn how to craft detailed, complex prompts for advanced tasks!
Next: Lesson 2d - Extended Prompts →
Quick Reference
// Low temperature (consistent) temperature: 0.1 // Medium temperature (balanced) temperature: 0.5 // High temperature (creative) temperature: 0.9