Velamuvi AIAcademy

Lesson 38 of 39 · Production

Production Checklist

Take an Agent Framework agent to production: error handling, retries, token costs, tool limits, security, telemetry, evaluations and a launch checklist.

  • 11 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Handle service errors with the Agent Framework exception classes
  • Add retries without making outages worse
  • Measure tokens and cost per request with UsageDetails
  • Cap runaway tool loops with function invocation limits
  • Walk through a launch checklist: security, observability, quality and operations

From demo to production

A demo needs to work once. A product needs to keep working when the model provider is slow, a key expires, a customer pastes something strange, or traffic doubles overnight. This lesson collects what the earlier lessons taught into one checklist, and adds the pieces that only matter in production: errors, retries, cost and limits.

Retries are only worth it for errors that can pass on their own. In plain Python:

Try it yourselfPython
# Retries with exponential backoff, in plain Python: retry only errors that can pass on their own.
import random

random.seed(4)
RETRYABLE = {429, 500, 503}             # too many requests, server errors


def call_service(attempt):
    return 429 if attempt < 2 else 200  # a pretend model service: busy twice, then fine


def call_with_retries(max_attempts=4, base_delay=1.0):
    for attempt in range(max_attempts):
        status = call_service(attempt)
        if status == 200:
            return f"ok after {attempt + 1} attempts"
        if status not in RETRYABLE:
            return f"gave up: {status} won't fix itself"
        delay = base_delay * 2 ** attempt + random.uniform(0, 0.5)   # backoff plus a little jitter
        print(f"attempt {attempt + 1}: {status}, waiting {delay:.1f} s")
    return "gave up after all attempts"


print(call_with_retries())

Errors: know what can fail

Every framework error is an AgentFrameworkException. The ones you'll handle most:

ExceptionWhat happenedWhat to do
ChatClientExceptionthe model service failed: network, rate limit, server error, bad requestretry if it can pass, otherwise show a friendly message
ChatClientInvalidAuthExceptiona client reported a bad key (raised by some clients, such as Anthropic, Gemini and Mistral)don't retry; fix the configuration
ChatClientContentFilterExceptionthe provider's safety filter blocked the prompt or answeranswer politely, don't retry
ToolExecutionExceptiona tool failed, or a tool can't continuefix the tool; check the logs
WorkflowExceptiona workflow failedlook at the events and checkpoints

Other parts of the framework have matching families: AgentException (with AgentInvalidAuthException, AgentInvalidRequestException and AgentInvalidResponseException) and IntegrationException (with IntegrationInitializationError and its own auth, request and response errors). Catch a base class when you only need to know where an error came from.

OpenAIChatClient wraps every service error in ChatClientException, and keeps the original openai error in error.__cause__. That's how you tell a wrong key from a busy service:

import asyncio

import openai
from agent_framework import Agent
from agent_framework.exceptions import ChatClientContentFilterException, ChatClientException
from agent_framework.openai import OpenAIChatClient


async def ask(agent: Agent, text: str) -> str:
    try:
        return (await agent.run(text)).text
    except ChatClientContentFilterException:
        return "Sorry, I can't help with that."
    except ChatClientException as error:
        cause = error.__cause__                       # the original openai error, if there is one
        if isinstance(cause, openai.AuthenticationError):
            raise                                     # a wrong key is a bug to fix, not something to retry
        if isinstance(cause, openai.RateLimitError):
            return "We're very busy right now. Please try again in a minute."
        return "Something went wrong on our side. Please try again."


async def main():
    agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's rental desk in Porto.")
    print(await ask(agent, "How much does a City E cost?"))
    print(await ask(agent, "How much does a Trail X cost?"))


asyncio.run(main())
Output
A City E costs 35 EUR a day.
We're very busy right now. Please try again in a minute.

The second answer is what customers see when the provider returns 429 Too Many Requests: a calm message instead of a crash.

Retries and timeouts

The openai package already retries rate limits and server errors twice, with backoff, before the error reaches you. To change that, give OpenAIChatClient your own AsyncOpenAI(max_retries=..., timeout=...) as async_client=, or pass timeout= directly. Add your own retries only around the whole run, only for errors that can pass, and with a small maximum. A queue or a background job is a better place for long waits than a customer's chat window.

Tokens and cost: UsageDetails

Each response carries UsageDetails in response.usage_details, a dictionary with input_token_count, output_token_count, total_token_count and, where the provider reports them, cache and reasoning tokens. Log them per request, and you always know what each customer and each feature costs:

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

# Your model's prices in USD per million tokens. Example values: copy the real ones from your provider.
INPUT_PRICE = 0.40
OUTPUT_PRICE = 1.60


async def main():
    agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's rental desk in Porto.")
    response = await agent.run("How much does a City E cost?")
    usage = response.usage_details or {}
    tokens_in, tokens_out = usage.get("input_token_count", 0), usage.get("output_token_count", 0)
    cost = tokens_in / 1_000_000 * INPUT_PRICE + tokens_out / 1_000_000 * OUTPUT_PRICE
    print(response.text)
    print(f"tokens: {tokens_in} in, {tokens_out} out, cost about ${cost:.6f}")


asyncio.run(main())
Output
A City E costs 35 EUR a day.
tokens: 412 in, 11 out, cost about $0.000182

Input tokens usually dominate: instructions, history and tool results are sent on every model call. Compaction, shorter instructions and cheaper models for simple steps cut them the most.

Limits for tool loops

A confused model can call tools again and again. Every chat client has a function invocation configuration with three limits: max_iterations (model round trips, 40 by default), max_function_calls (total tool runs per request, unlimited by default) and max_duration_seconds (time spent in the tool loop). When a limit is reached, the agent stops calling tools and asks the model for a final answer:

import asyncio

from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatClient


@tool
def bikes_at(station: str) -> str:
    """How many bikes are free at one station."""
    return f"{station}: 4 bikes free"


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    client.function_invocation_configuration["max_function_calls"] = 3        # at most 3 tool runs per request
    client.function_invocation_configuration["max_duration_seconds"] = 30.0   # and at most 30 s of tool work
    agent = Agent(client=client, instructions="You are Velo's rental desk in Porto.", tools=[bikes_at])

    response = await agent.run("Check every station in Porto for free bikes.")
    calls = [content for message in response.messages for content in message.contents if content.type == "function_call"]
    print("tool calls:", len(calls))
    print(response.text)


asyncio.run(main())
Output
tool calls: 3
I checked three stations, and each has 4 free bikes. Which station should I book from?

include_detailed_errors (off by default) decides whether the model sees the real text of a tool's exception; keep it off in production, since error text can leak internal details.

The launch checklist

AreaCheckWhere in this course
SecretsKeys in environment variables or a key vault, never in code; separate keys per environmentInstallation, Settings and Chat Clients
ErrorsFriendly fallbacks for ChatClientException; no retries for auth errorsthis lesson
Limitsmax_function_calls, max_duration_seconds and spending limits at the providerthis lesson
ToolsApprovals for anything that moves money or data; narrow tool argumentsTool Approval and User Input
SecurityLabels and policies for untrusted content; content filters; MCP tools treated as untrustedSecurity
ContextSessions stored outside the process; compaction for long chatsSessions, History Providers, Compaction
ObservabilityOpenTelemetry traces and metrics; sensitive data offObservability With OpenTelemetry
QualityEvaluations in CI that fail the build on regressionsEvaluations and Testing
OperationsHealth checks, versioned prompts and a way to roll backHosting

Agent Framework also adds a small User-Agent header with its version to service calls, which helps Microsoft see which versions are in use. To turn it off, set the environment variable named in USER_AGENT_TELEMETRY_DISABLED_ENV_VAR, which is AGENT_FRAMEWORK_USER_AGENT_DISABLED, to true:

export AGENT_FRAMEWORK_USER_AGENT_DISABLED=true

Common mistakes

Practice exercise

Write a small production-readiness check: it reads an agent's settings and lists what still has to be fixed before launch.

Your solutionPython
def review(config):
    problems = []
    # Add one message for each rule that fails, in this order:
    # api_key_in_code is True       -> "store the API key in an environment variable or a key vault"
    # max_function_calls is missing -> "set max_function_calls"
    # sensitive_telemetry is True   -> "turn off sensitive telemetry"
    # evals_in_ci is False          -> "run evaluations in CI"
    return problems


ready = {"api_key_in_code": False, "max_function_calls": 5, "sensitive_telemetry": False, "evals_in_ci": True}
demo = {"api_key_in_code": True, "sensitive_telemetry": True, "evals_in_ci": False}
print(review(ready))
for problem in review(demo):
    print("-", problem)
Knowledge check

OpenAIChatClient raises ChatClientException. How do you tell a wrong API key from a busy service?

Summary

  • Handle AgentFrameworkException subclasses on purpose: ChatClientException for service errors, ChatClientInvalidAuthException and content-filter errors without retries, ToolExecutionException and WorkflowException for your own code.
  • The openai package already retries; add few retries of your own, with backoff, and only for errors that can pass.
  • Log UsageDetails per request to know your costs, and cap tool loops with max_function_calls and max_duration_seconds.
  • Go through the checklist before launch: secrets, limits, approvals, security, observability, evaluations and operations; set AGENT_FRAMEWORK_USER_AGENT_DISABLED if you opt out of the version header.

Next: Project: Bike Shop Support Desk.

Finished reading? Tick it off to track your progress.