Python SDK
The Python SDK (ants-platform on PyPI) traces your agents and LLM calls and
sends them to ANTS Platform over OpenTelemetry. It also includes the
OpenAI, LangChain
and CrewAI integrations and a client for prompts,
datasets and scores.
| Value | |
|---|---|
| Package | ants-platform (current version 3.7.0) |
| Import | from ants_platform import AntsPlatform, get_client, observe |
| Python version | 3.9 or later (3.10 to 3.13 for the CrewAI extra) |
| Auth | Project public key (pk-ap-...) and secret key (sk-ap-...) |
Install
Optional extras install the framework you integrate with:
Configure
Create a key pair under Project Settings > API Keys (see API Keys) and set:
AntsPlatform() reads these variables. You can also pass them as arguments:
If ANTS_PLATFORM_HOST is not set and no host is passed, the SDK sends to
https://api.agenticants.ai. Set the host explicitly for any other
deployment. It is the URL of your ANTS Platform app.
Trace an agent
Every trace needs an agent name. The top-level observation of a trace must
set agent_name, or the SDK raises ValueError: agent_name is required.
Child observations inherit it. Agent names are stored in lower case and
identify the agent in the AI Agent Center.
Open an agent observation
Add child observations
Flush before exit
The SDK sends data in the background. Call flush() (or shutdown()) before a
short-lived script or worker exits.
Cost is calculated by ANTS Platform from the model and token usage. Pass
cost_details to send your own cost instead. An exception raised inside a
with block is recorded on that observation.
Observation types
as_type accepts span (default), generation, agent, tool, chain,
retriever, embedding, evaluator and guardrail. generation and
embedding also accept model, model_parameters, usage_details,
cost_details, completion_start_time and prompt.
start_as_current_span(...) is a shortcut for as_type="span".
start_generation and start_as_current_generation still work but are
deprecated. Use as_type="generation".
Update the current trace or observation
| Method | Fields |
|---|---|
observation.update(...) | name, input, output, metadata, level, status_message, version, and the generation fields |
observation.update_trace(...) / ants.update_current_trace(...) | name, user_id, session_id, version, agent_name, input, output, metadata, tags, public |
ants.update_current_span(...) / ants.update_current_generation(...) | Same as update on the active observation |
level is one of DEBUG, DEFAULT, WARNING or ERROR.
The @observe decorator
@observe() traces a function as an observation, capturing its arguments and
return value. It works on sync and async functions and generators.
Options: name, as_type, capture_input, capture_output and
transform_to_string (for generators). The decorator has no agent_name
option, so call decorated functions inside an agent observation as shown.
Set ANTS_PLATFORM_OBSERVE_DECORATOR_IO_CAPTURE_ENABLED=false to turn off
argument and return value capture globally.
Framework integrations
Already instrumented with OpenTelemetry (for example OpenLLMetry)? Export to ANTS Platform directly. See OpenTelemetry (OTLP).
Tool governance
From 3.7.0, AntsGuardrailsClient in ants_platform.guardrails checks an
agent's tool calls against its tool permissions
before the tool runs. It is on by default when agent_id is set, and changes
nothing until the agent has an approved tool.
guard_toolchecks the call with its arguments before the function runs, and records it as a tool observation. It works on sync and async functions;guard_tool(name="...")sets the tool name.- When the agent's AI Guardrails policy is Block or Redact, a call that breaks
a rule raises
ToolNotAllowedErrorand the function does not run. Under Audit Only, or with no policy, the call runs and the violation is reported in the background. - A call that needs approval creates an approval request and waits for the
decision. A denial, an expiry or no answer within
approval_timeoutraisesToolApprovalDeniedError. - Both errors subclass
GuardrailViolationError. - Tool calls of a suspended
agent raise
ToolNotAllowedErrorwith "This agent has been suspended by an administrator.", even when the agent has no policy.
| Helper | Use |
|---|---|
guard_tool | Decorator for a tool function |
guard_tool_interrupt | Like guard_tool for a LangGraph tool node: a call that needs approval pauses the run with interrupt, and resuming the run continues or raises |
guard_framework_tools(guardrails, tools) | Guards LangChain, CrewAI and OpenAI Agents tool objects in place |
langchain_tool_guard(guardrails) | A LangChain callback handler that checks every tool call before it starts |
guard_mcp_session(guardrails, session, "github") | Checks MCP call_tool as github/<tool>, and compares list_tools definitions with the pinned ones |
as_user(id_token) / set_user_token(id_token) | Verifies the OIDC ID token of the user the agent acts for, for group-limited tools |
check_tool_calls(...) / enforce_tool_calls(...) | Check calls yourself. check_tool_calls returns a ToolCheckResult and never raises. |
The wrapped clients (AntsOpenAI, AntsAnthropic, AntsBedrock,
AntsGoogleGenAI, AntsVertexAI) also check the tool calls in each model
response. See AI Guardrails.
| Option | Default | Description |
|---|---|---|
enforce_tools | True | Pass False to turn tool governance off |
tool_fail_mode | "open" | "closed" blocks tool calls when the tool settings were never loaded |
approval_timeout | 300 | Seconds to wait for an approval |
approval_poll_seconds | 2 | How often to ask for the decision |
The tool settings are fetched from ANTS Platform and refreshed about every minute. If a refresh fails, the last copy is kept. Rate limits are counted in the process.
Configuration reference
| Argument | Environment variable | Default |
|---|---|---|
public_key | ANTS_PLATFORM_PUBLIC_KEY | none |
secret_key | ANTS_PLATFORM_SECRET_KEY | none |
host | ANTS_PLATFORM_HOST | https://api.agenticants.ai |
environment | ANTS_PLATFORM_TRACING_ENVIRONMENT | default |
release | ANTS_PLATFORM_RELEASE | none |
tracing_enabled | ANTS_PLATFORM_TRACING_ENABLED | True |
debug | ANTS_PLATFORM_DEBUG | False |
sample_rate | ANTS_PLATFORM_SAMPLE_RATE | 1.0 (0.0 to 1.0) |
timeout | ANTS_PLATFORM_TIMEOUT | 5 seconds |
flush_at | ANTS_PLATFORM_FLUSH_AT | OpenTelemetry batch default |
flush_interval | ANTS_PLATFORM_FLUSH_INTERVAL | OpenTelemetry batch default |
media_upload_thread_count | ANTS_PLATFORM_MEDIA_UPLOAD_THREAD_COUNT | 1 |
| none | ANTS_PLATFORM_MEDIA_UPLOAD_ENABLED | True |
| none | ANTS_PLATFORM_PROMPT_CACHE_DEFAULT_TTL_SECONDS | 60 |
mask | none | A function applied to inputs, outputs and metadata before export |
additional_headers | none | Extra HTTP headers on export requests |
blocked_instrumentation_scopes | none | OpenTelemetry instrumentation scopes to drop |
get_client() returns the client created by the first AntsPlatform(...)
call, or one built from the environment variables.
Other client features
| Area | Methods |
|---|---|
| Scores | create_score(...), score_current_span(...), score_current_trace(...), observation.score(...) |
| Prompts | get_prompt(name, version=, label=), create_prompt(...), update_prompt(...) |
| Datasets | get_dataset(name), create_dataset(...), create_dataset_item(...) |
| Utilities | get_current_trace_id(), get_current_observation_id(), get_trace_url(), create_trace_id(seed=), auth_check(), flush(), shutdown() |
See Scores, Prompts and Datasets.
Troubleshooting
ValueError: agent_name is required. The first observation of the trace has noagent_name. Open an agent observation first.- Nothing appears. Check the keys and host, then call
ants.auth_check(). Callants.flush()before the process exits. - Slow first call. The first agent observation fetches the project ID from
the API. Increase
timeouton slow networks.