Anthropic Claude Integration: Tool Use, Caching, and Optimization
A client approached us to integrate Claude into their SaaS product. The first version called the model with no optimization at all. After a week of testing, the API bill hit thousands of dollars, and the response quality didn't meet expectations. We redesigned the architecture: implemented Tool Use for agentic scenarios, configured Prompt Caching for static instructions, and selected the right model for each query type. The result—cost reduced by 80% while maintaining p99 latency under 2 seconds. This article covers practical steps useful for anyone deploying Claude into production.
"The integration reduced our costs by 80% while improving response times." — Client
Which Claude Model to Choose for Production?
| Model | Context | Speed | Cost | Use Case |
|---|---|---|---|---|
| Claude Opus | 200K | Medium (p99 ~5s) | High | Complex analysis, generation |
| Claude Sonnet | 200K | High (p99 ~1s) | Medium | Production, chatbots |
| Claude Haiku | 200K | Very High (p99 ~0.5s) | Low | Classification, fast responses |
Claude Haiku is 5x cheaper than Opus with similar quality on simple tasks. The choice depends on your scenario; we help select the optimal configuration for your load.
Why Model Selection Determines Your Budget
On one project, we replaced Opus with Sonnet for 70% of requests, keeping Opus only for complex reasoning. This cut overall API costs by 3x. For simple tasks like classification or data extraction, Haiku provides the same accuracy as Opus but costs 10x less. Always test on your own data.
How to Set Up Basic Integration
import anthropic
from pydantic import BaseModel
client = anthropic.Anthropic() # ANTHROPIC_API_KEY from env
# Basic call
def chat(prompt: str, model: str = "claude-sonnet-4-5") -> str:
message = client.messages.create(
model=model,
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return message.content[0].text
# With system prompt
def chat_with_system(system: str, prompt: str) -> str:
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
system=system,
messages=[{"role": "user", "content": prompt}],
temperature=0.1,
)
return message.content[0].text
# Streaming
def stream_response(prompt: str):
with client.messages.stream(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
) as stream:
for text in stream.text_stream:
yield text
# Vision
def analyze_image(image_base64: str, media_type: str, question: str) -> str:
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": media_type,
"data": image_base64,
},
},
{"type": "text", "text": question},
],
}]
)
return message.content[0].text
What Is Tool Use and How to Build an Agent?
Tool Use (Function Calling) allows Claude to call external functions. You describe tools in JSON Schema, and the model decides when to invoke them. This is the core mechanism for building agents.
tools = [{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"units": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"]
}
}]
def run_agent_loop(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
while True:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
return response.content[-1].text
# Handle tool_use blocks
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = dispatch_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": str(result),
})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
With multiple tools, the logic is the same—the model chooses which to call. Proper error handling is important: pass errors back with is_error in the next request.
How Does Prompt Caching Work and Why Can It Save Up to 90%?
Caching large static prompts (documents, instructions) is a key technique. The cache is stored for 5 minutes and savings on repeated calls can reach 90%. Anthropic recommends caching blocks over 1024 tokens.
def cached_analysis(system_doc: str, question: str) -> str:
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
system=[{
"type": "text",
"text": system_doc,
"cache_control": {"type": "ephemeral"}, # Cache this block
}],
messages=[{"role": "user", "content": question}]
)
return message.content[0].text
In practice: if you frequently repeat the same instructions (e.g., response format description), move them into a separate cacheable block. This reduces latency and cost.
Comparison: With and Without Caching
| Parameter | Without Caching | With Caching |
|---|---|---|
| Cost per 1000 requests (1000 token prompt + 100 token response) | $1.20 | $0.12 |
| Latency p99 | 2.5 s | 0.8 s |
Savings on repeated instructions can reach 90%. After optimization, our clients typically save between 50% and 90% on API costs.
Example savings calculation for 10,000 requests per day: Assume each request contains a static instruction of 500 tokens. Without caching, you pay for all tokens. With caching, the instruction is charged only on its first occurrence within a 5-minute window. With evenly distributed requests, the cache hits for 80% of requests, reducing costs for the same number of tokens. On Sonnet, this saves roughly $200 per month.
What Our Integration Includes
- Architectural documentation with integration schema and model selection
- Code repository in Python (FastAPI or Flask) with streaming, Vision, and Tool Use support
- Monitoring and alerting setup (Grafana + Prometheus) for key metrics: p99 latency, tokens per minute, errors
- Customer team training (2–3 hours) on operation and further development
- Support for 30 days after deployment
With over 10 years of experience and more than 50 deployed AI integrations, we have the expertise to handle your project.
Step-by-Step Integration Guide
- Analytics — define the scenario, load, and choose the model.
- Design — integration architecture, rate limiting, and retry logic.
- Implementation — basic calls, streaming, Vision.
- Tool enablement — Tool Use for agents.
- Optimization — Prompt Caching, model selection, temperature tuning.
- Testing — performance under load, measurement of p99 latency.
- Deployment — roll out, monitoring, team training.
Each step can be done separately. A full cycle takes up to a week.
Timelines and Cost
- Basic integration: from 0.5 days
- Tool Use + agent loop: 2–3 days
- Prompt Caching + optimization: 1 day
- Full cycle: up to a week
Cost is calculated individually based on complexity. Our basic integration starts at $500, with full turnkey solutions from $2,000. Write to us to get a free estimate for your project.
Typical Integration Mistakes
- Ignoring caching — leads to unnecessary costs (could have saved 50–90%).
- Wrong model selection — Haiku suffices for 70% of requests, yet Opus is used.
- No retry logic — requests are lost due to rate limits.
- Overly long system prompts without caching — increases latency and cost.
We provide turnkey integration in as little as 2 days. Contact us to discuss your integration scenario. We guarantee stable operation and cost optimization.







