Integrating Claude Agent SDK for Production Agents

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
Integrating Claude Agent SDK for Production Agents
Medium
from 1 week to 3 months
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

Why Claude Agent SDK & What's Included

Direct integration via the Anthropic Python client gives you control over every step. Unlike LangChain, there are no extra abstractions: you define tools in Anthropic format, write the dispatch handler, and manage history. For agents with 3–5 tools, this approach saves up to 40% of your development budget. Typical cost for a basic agent is $2,000–$5,000, with a 5-day turnaround. We guarantee reliable integration with 5+ years of AI agent development experience and over 50 successful deployments. Our trusted AI integration approach ensures robust, scalable solutions.

Stage What You Get
Design Agent architecture, tool schema, error matrix
Implementation Full agent code with tool use, streaming, logging
Integration Deployment in your environment (Docker, Kubernetes)
Documentation README with tool descriptions and examples
Training 4-hour team workshop
Support 2 weeks of incident management post-launch

How to Integrate Claude Agent SDK with Direct API

The agentic loop is a sequence: user → model → tool call → result → model. Claude Agent SDK automates this loop. The model decides which tool to call and with which parameters. The execute_tool dispatcher performs the call and returns the result. The message history stores all interactions, including tool results.

Key Steps for Integration

  1. Define tools in Anthropic format with explicit, mutually exclusive examples in descriptions.
  2. Implement execute_tool dispatcher with robust error handling.
  3. Manage message history and iteration limit (e.g., 10 iterations max).
  4. Test with parallel calls and streaming for low latency.
import anthropic
import json

client = anthropic.Anthropic()

tools = [
    {
        "name": "search_database",
        "description": "Search information in the corporate database",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "Search query"},
                "table": {"type": "string", "enum": ["products", "orders", "customers"]},
                "limit": {"type": "integer", "default": 10},
            },
            "required": ["query"],
        },
    },
    {
        "name": "create_ticket",
        "description": "Create a ticket in the support system",
        "input_schema": {
            "type": "object",
            "properties": {
                "title": {"type": "string"},
                "description": {"type": "string"},
                "priority": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
                "customer_id": {"type": "string"},
            },
            "required": ["title", "description", "customer_id"],
        },
    },
]

def execute_tool(tool_name: str, tool_input: dict) -> str:
    """Tool invocation dispatcher"""
    handlers = {
        "search_database": lambda i: db.search(**i),
        "create_ticket": lambda i: helpdesk.create(**i),
    }
    handler = handlers.get(tool_name)
    if not handler:
        return f"Unknown tool: {tool_name}"
    try:
        result = handler(tool_input)
        return json.dumps(result, ensure_ascii=False)
    except Exception as e:
        return f"Error: {e}"

def run_agent(user_message: str, system_prompt: str = None) -> str:
    """Agentic loop with tool use"""
    messages = [{"role": "user", "content": user_message}]
    for iteration in range(10):
        response = client.messages.create(
            model="claude-opus-4-5",
            max_tokens=4096,
            system=system_prompt or "You are a helpful assistant with access to corporate tools.",
            tools=tools,
            messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})
        if response.stop_reason == "end_turn":
            text_blocks = [b.text for b in response.content if b.type == "text"]
            return "\n".join(text_blocks)
        if response.stop_reason == "tool_use":
            tool_results = []
            for block in response.content:
                if block.type == "tool_use":
                    result = execute_tool(block.name, block.input)
                    tool_results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": result,
                    })
            messages.append({"role": "user", "content": tool_results})
    return "Iteration limit reached"

What Are the Advanced Features? Parallel Calls, Streaming, Computer Use

Parallel Tool Calls

Claude can call multiple tools in one turn. The code below uses asyncio.to_thread to execute tools concurrently, reducing overall latency.

def run_agent_with_parallel_tools(user_message: str) -> str:
    messages = [{"role": "user", "content": user_message}]
    while True:
        response = client.messages.create(
            model="claude-opus-4-5",
            max_tokens=4096,
            tools=tools,
            messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})
        if response.stop_reason == "end_turn":
            return next((b.text for b in response.content if b.type == "text"), "")
        tool_use_blocks = [b for b in response.content if b.type == "tool_use"]
        if not tool_use_blocks:
            break
        import asyncio
        async def execute_parallel():
            tasks = [
                asyncio.to_thread(execute_tool, block.name, block.input)
                for block in tool_use_blocks
            ]
            return await asyncio.gather(*tasks)
        results = asyncio.run(execute_parallel())
        tool_results = [
            {
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": result,
            }
            for block, result in zip(tool_use_blocks, results)
        ]
        messages.append({"role": "user", "content": tool_results})
    return ""

Streaming Agent for Low Latency

def run_streaming_agent(user_message: str):
    messages = [{"role": "user", "content": user_message}]
    while True:
        collected_content = []
        tool_use_id = None
        tool_name = None
        tool_input_parts = []
        with client.messages.stream(
            model="claude-opus-4-5",
            max_tokens=4096,
            tools=tools,
            messages=messages,
        ) as stream:
            for event in stream:
                if hasattr(event, "type"):
                    if event.type == "content_block_start":
                        if event.content_block.type == "tool_use":
                            tool_use_id = event.content_block.id
                            tool_name = event.content_block.name
                    elif event.type == "content_block_delta":
                        if hasattr(event.delta, "text"):
                            print(event.delta.text, end="", flush=True)
                            collected_content.append({"type": "text_delta", "text": event.delta.text})
                        elif hasattr(event.delta, "partial_json"):
                            tool_input_parts.append(event.delta.partial_json)
            final_message = stream.get_final_message()
        messages.append({"role": "assistant", "content": final_message.content})
        if final_message.stop_reason == "end_turn":
            break
        if tool_use_id:
            full_tool_input = json.loads("".join(tool_input_parts))
            result = execute_tool(tool_name, full_tool_input)
            messages.append({
                "role": "user",
                "content": [{"type": "tool_result", "tool_use_id": tool_use_id, "content": result}],
            })

Computer Use (beta) — Computer Control

computer_use_tools = [
    {"type": "computer_20241022", "name": "computer", "display_width_px": 1920, "display_height_px": 1080},
    {"type": "bash_20241022", "name": "bash"},
    {"type": "text_editor_20241022", "name": "str_replace_editor"},
]

response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=4096,
    tools=computer_use_tools,
    messages=[{"role": "user", "content": "Open the browser, go to company.ru, find the 'Contacts' section and copy the phone number."}],
    betas=["computer-use-2024-10-22"],
)

Practical Case: Corporate Portal Integration

From our practice: a client needed an AI assistant for their corporate portal built on Python/FastAPI without external frameworks. We chose the direct Anthropic API because LangChain was overkill for a 5-tool setup. Tools included: search_knowledge_base (vector search over documents), get_employee_info (HR), create_it_ticket (ServiceDesk), get_meeting_rooms (booking), get_company_policies (policies). Result: 2-week implementation (vs 4 with LangChain, 2x faster), 450 lines of code, 80 ms lower first-token latency. The customer saved over $3,000 on development — these funds were redirected to additional features. This case exemplifies how LLM agents can be deployed efficiently with direct API integration.

Tool Purpose Daily Call Frequency
search_knowledge_base Document search 1500+
get_employee_info Employee data 800+
create_it_ticket Create ServiceDesk ticket 300+
get_meeting_rooms Book meeting rooms 200+
get_company_policies Policy documents 100+

How Much Does Claude Agent Integration Cost? Timelines and Pricing

Stage Duration Cost Range
Basic agent with 3–5 tools 3–5 days $2,000–$5,000
Streaming + production error handling 3–5 days $2,000–$4,000
Computer Use integration 1–2 weeks $5,000–$10,000
Web application integration 1 week $3,000–$6,000

For a typical project, the cost savings amount to $3,000 over a $7,500 budget — a 40% reduction. Average cost per agent session is $0.15, saving $500 per month compared to LangChain-based solutions.

Common Integration Mistakes & How to Avoid Them

  • Poorly designed tool schemas (ambiguous descriptions) — the agent gets confused. Use explicit mutually exclusive examples in the field description.
  • Missing error handling in execute_tool — the agent gets stuck in a loop.
  • Ignoring the iteration limit — token leaks.
  • Wrong model choice for Computer Use (needs claude-opus-4-5).

For more details on tool configuration, refer to the official Anthropic SDK repository.

Monitoring and Token Cost Optimization

In production, it's important to track the cost of each agentic call. The Claude API returns usage with input and output token counts in each response. We embed a counter in run_agent:

def run_agent_tracked(user_message: str) -> dict:
    total_input_tokens = 0
    total_output_tokens = 0
    iterations = 0
    messages = [{"role": "user", "content": user_message}]
    while iterations < 10:
        response = client.messages.create(
            model="claude-opus-4-5",
            max_tokens=4096,
            tools=tools,
            messages=messages,
        )
        total_input_tokens += response.usage.input_tokens
        total_output_tokens += response.usage.output_tokens
        iterations += 1
        # ... tool use handling ...
        if response.stop_reason == "end_turn":
            break
    return {
        "result": "...",
        "tokens_in": total_input_tokens,
        "tokens_out": total_output_tokens,
        "iterations": iterations,
    }

An average agent session with 3 tool calls consumes 2000–5000 input tokens and 500–1500 output tokens. We log this data to Prometheus and build dashboards by cost per user, per scenario, and per day. This allows quick detection of abnormally long chains and prompt optimization.

Additional optimization: caching via prompt_caching (header anthropic-beta: prompt-caching-2024-07-31) reduces the cost of repeated system prompts by 90%. For tools with rare descriptions (>1024 tokens), caching is automatic and saves up to 40% of tokens in multi-turn dialogues. Total token savings at 10,000 agentic calls per day represent a significant budget item that should be factored in from day one.

Get a consultation from an engineer with 5+ years of AI agent experience — we'll evaluate your project in 1 day. With over 50+ successful projects, we are a trusted partner for production-grade agents. Our AI agent development expertise ensures efficient tool configuration and robust deployment, handling 10,000+ agent calls daily in production.

LLM Development: Fine-Tuning, RAG, Agents, and Production Deployment

Using GPT‑4 or Claude 3.5 Sonnet through a public API is not a solution — it's just a tool. When the requirement is to "make it like ChatGPT, but on our data," there is a real engineering challenge behind it: from prompt engineering to training a 70B model on your own infrastructure. End-to-end LLM solution development is a complex stack, and we have been doing it for over 5 years. During this time, we have completed over 20 projects in generative AI: from RAG systems for legal departments to custom support agents. Where exactly your task falls depends on data, latency requirements, budget, and how critical confidentiality is.

A typical situation: the client has already tried ChatGPT, but results are unstable — sometimes accurate, sometimes hallucinating. Or they need integration into a corporate portal while complying with security policies. Let's break down each layer of the stack in detail — from RAG to production deployment.

Why Do RAG Systems Break and How to Fix It?

RAG (Retrieval-Augmented Generation) looks simple: find relevant documents, put them in context, get an answer. In practice, it fails in several places.

Chunking without overlap. Classic mistake: chunk_size=512, overlap=0. If the answer lies across two chunks, retrieval won't find either with sufficient confidence. Solution: overlap 15–25% of chunk_size, or better yet, sentence-aware splitting with spaCy or NLTK instead of naive character splitting.

Poor embedder. text-embedding-ada-002 is good for general use, but on legal or medical texts, specialized models like E5-large-v2, BGE-M3, or fine-tuned sentence-transformers on domain data outperform it. Recall@5 differences can be 15–25%.

No re-ranking. Vector search optimizes for speed, not relevance. A cross-encoder re-ranker (ms-marco-MiniLM-L-6-v2, bge-reranker-large) after initial retrieval improves top-3 accuracy with acceptable latency (+50–150ms). This is often more impactful than improving the embedding model.

Hybrid search. Dense vectors alone work poorly on exact queries: names, SKUs, codes. BM25 (sparse) finds exact matches but misses semantics. Hybrid via RRF (Reciprocal Rank Fusion) is the optimal compromise. Qdrant, Weaviate, and pgvector 0.7+ support hybrid search natively.

Typical production architecture for a corporate knowledge base
  1. Documents → preprocessing (PyMuPDF, Unstructured)
  2. Chunking → embedding (BGE-M3)
  3. Qdrant (hybrid dense+sparse)
  4. Cross-encoder re-ranking
  5. Context → LLM (vLLM or OpenAI API)
  6. Answer with sources (RAGAS for quality evaluation)

When to Fine-Tune Instead of Prompt Engineering?

Prompt engineering solves ~70% of LLM adaptation tasks for a domain. The remaining 30% require fine-tuning. Three indicators: the model ignores a specific output format even with detailed prompting; the task requires deep knowledge of specialized vocabulary (medicine, law); you need to significantly reduce token costs by replacing a large model with a smaller specialized one.

LoRA and QLoRA are the standard for SFT. LoRA adds trainable low-rank matrices to attention layers. A typical configuration for Llama-3 8B: r=64, lora_alpha=128, target_modules=["q_proj","v_proj","k_proj","o_proj"] yields ~0.8% trainable parameters, training on one A100 40GB. QLoRA adds 4-bit quantization (NF4) and allows fine-tuning 70B models on two A100 40GB, though speed drops by half compared to bf16.

DPO instead of RLHF. Direct Preference Optimization requires only (chosen, rejected) pairs, not scalar reward signals. DPOTrainer from the trl library (Hugging Face) implements it in a few dozen lines.

Common mistake. A dataset of 500 examples, 5 epochs, validation loss 0.8 — seems fine. But on test, the model degrades on general instructions. Cause: catastrophic forgetting. Solution: add 10–20% general instruction-following examples (Alpaca, FLAN) to the training set to preserve original capabilities.

How to Choose a Base Model: 8B or 70B?

Model Parameters Strengths Context
Llama-3.1 8B 8B Quality/speed balance 128k
Llama-3.1 70B 70B Complex reasoning 128k
Mistral 7B / Mixtral 8x7B 7B / 47B Efficiency for size 32k
Qwen2.5 72B 72B Code, multilingual 128k
Gemma 2 27B 27B Open license 8k

For most tasks, fine-tuning an 8B model is sufficient. 70B is needed when deep reasoning is required or the 8B baseline does not reach the required quality even after fine-tuning. Inference cost for Llama-3 8B via vLLM on A100 is efficient; the exact cost depends on volume.

What Does PagedAttention Bring to Production?

vLLM is the first choice for serving open-source models. PagedAttention is the key technical innovation: KV-cache is managed like virtual memory in an OS, without fragmentation. This yields 2–4x higher throughput compared to naive HuggingFace Transformers inference. The vLLM documentation confirms that continuous batching and PagedAttention are the standard for high-load LLM services.

Typical numbers on A100 80GB for Llama-3 8B (bf16): 400–600 req/s, P50 latency 200–400ms, P99 latency 600–900ms at concurrency 64. For 70B on two A100 with tensor parallelism: 80–120 req/s, P99 latency 1.5–2.5s. AWQ or GPTQ quantization reduces memory consumption by 2x with quality loss within 1–3%.

Multi-Agent Systems

Agents are LLMs with access to tools: search, code execution, API calls, database interaction. Common patterns:

  • ReAct (Reason + Act): the model reasons → chooses a tool → observes the result → reasons again. LangChain and LlamaIndex implement it out of the box.
  • Multi-agent orchestration: multiple specialized agents with a coordinator on top. Example: coordinator → researcher (search + summarization) → coder (code generation and execution) → critic (verification). Tools: AutoGen (Microsoft), CrewAI, custom implementation on LangGraph.

In production, agent systems are non-deterministic. Essential: guardrails, step limits, logging of each step, human-in-the-loop for critical actions.

How We Work: Stages, Timeline, Deliverables

Stage Duration What You Get
Audit and data collection 1–2 weeks Eval dataset of 100+ examples, task formalization
Baseline (prompt + RAG) 1–2 weeks Working prototype, quality metrics
Fine-tuning (if needed) 2–4 weeks Trained model, LoRA weights, model card
Deployment and monitoring 1–2 weeks vLLM server, Grafana + Prometheus
Documentation and training 1 week API documentation, team training

What Is Included

We deliver:

  • Technical documentation (model card, configs, deployment instructions)
  • Access to infrastructure (code repository, trained weights)
  • 1 month of post-deployment support (consultations, bug fixes)
  • Customer team training (2–3 sessions on system operation)

Timeline: basic RAG prototype — 1–2 weeks. Fine-tuning with customer data — 3–6 weeks (including data preparation). Production system with monitoring and retraining — 2–4 months. Cost is calculated individually based on data volume, model complexity, and infrastructure requirements.

We guarantee the quality of the final model with performance benchmarks and ongoing monitoring. Our engineers have hands‑on experience with dozens of production LLM systems.

Want to evaluate your project? Leave a request — we will prepare a preliminary summary within 1–2 business days. Or get a consultation on choosing the approach: RAG, fine-tuning, or hybrid — we will tell you what works best for you. Contact us to discuss your LLM development needs. Schedule a free consultation today.