Skip to content

Python Runtime

The Python runtime provides a Pythonic interface for working with AgentSchema definitions, with full type hints and async support.

Terminal window
pip install agentschema

Or using uv:

Terminal window
uv add agentschema
  • Python >= 3.11

Load agent definitions from YAML or JSON:

from agentschema import AgentDefinition
# Load from YAML
agent = AgentDefinition.from_yaml("""
name: my-agent
model: gpt-4o
instructions: You are a helpful assistant.
""")
# Load from JSON
json_agent = AgentDefinition.from_json("""{
"name": "my-agent",
"model": "gpt-4o",
"instructions": "You are a helpful assistant."
}""")
print(agent.name) # "my-agent"
print(agent.model) # "gpt-4o"

Load directly from YAML or JSON files:

from agentschema import AgentDefinition
# Load from a YAML file
agent = AgentDefinition.from_yaml_file("agent.yaml")
# Load from a JSON file
agent = AgentDefinition.from_json_file("agent.json")

Build agent definitions using Python classes:

from agentschema import AgentDefinition, FunctionTool, Property
agent = AgentDefinition(
name="weather-agent",
model="gpt-4o",
instructions="You help users check the weather.",
tools=[
FunctionTool(
name="get_weather",
description="Get current weather for a location",
parameters={
"location": Property(
kind="string",
description="City name",
required=True,
),
},
),
],
)

Export to YAML or JSON:

# Convert to YAML
yaml_str = agent.to_yaml()
print(yaml_str)
# Convert to JSON (with indentation)
json_str = agent.to_json(indent=2)
print(json_str)
# Convert to dictionary
data = agent.save()
# Save to file
agent.to_yaml_file("output.yaml")
agent.to_json_file("output.json")

Customize how data is loaded:

from agentschema import AgentDefinition, LoadContext
def pre_process(data: dict) -> dict:
print(f"Loading: {data.get('name')}")
return data
def post_process(result):
print("Load complete")
return result
context = LoadContext(
pre_process=pre_process,
post_process=post_process,
)
agent = AgentDefinition.from_yaml(yaml_content, context)

Control output formatting:

from agentschema import AgentDefinition, SaveContext
context = SaveContext(
collection_format="object", # Use object format for named collections
use_shorthand=True, # Use shorthand notation when possible
)
yaml_str = agent.to_yaml(context)

The SDK exports all AgentSchema types as Python classes:

ClassDescription
AgentDefinitionComplete agent specification
AgentManifestParameterized agent template
ModelAI model configuration
ModelOptionsModel parameters (temperature, tokens, etc.)
ClassDescription
FunctionToolCustom function definitions
OpenApiToolOpenAPI/Swagger integrations
McpToolModel Context Protocol tools
CodeInterpreterToolCode execution capability
FileSearchToolFile search capability
WebSearchToolWeb search capability
CustomToolCustom tool implementations
ClassDescription
ApiKeyConnectionAPI key authentication
AnonymousConnectionNo authentication
ReferenceConnectionReference to external connection
RemoteConnectionRemote service connection
ClassDescription
PropertyBase property type
ObjectPropertyObject/nested property
ArrayPropertyArray/list property
PropertySchemaSchema with multiple properties

The SDK provides full type hint support:

from agentschema import AgentDefinition, Tool
def process_agent(agent: AgentDefinition) -> list[Tool]:
"""Process an agent and return its tools."""
return agent.tools or []
# IDE provides full autocomplete and type checking
agent = AgentDefinition(
name="my-agent", # str
model="gpt-4o", # str
instructions="...", # str
tools=[], # list[Tool]
)

The SDK supports async file operations:

import asyncio
from agentschema import AgentDefinition
async def load_agent():
agent = await AgentDefinition.from_yaml_file_async("agent.yaml")
return agent
async def save_agent(agent: AgentDefinition):
await agent.to_yaml_file_async("output.yaml")
# Run async operations
agent = asyncio.run(load_agent())

Handle parsing errors gracefully:

from agentschema import AgentDefinition
import yaml
try:
agent = AgentDefinition.from_yaml(invalid_yaml)
except yaml.YAMLError as e:
print(f"Invalid YAML: {e}")
except ValueError as e:
print(f"Invalid agent definition: {e}")
from agentschema import AgentDefinition
# Load your agent definition
agent = AgentDefinition.from_yaml_file("agent.yaml")
# Use with LangChain
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(
model=agent.model,
temperature=agent.model_options.temperature if agent.model_options else 0.7,
)
from agentschema import AgentDefinition
from openai import OpenAI
agent = AgentDefinition.from_yaml_file("agent.yaml")
client = OpenAI()
response = client.chat.completions.create(
model=agent.model,
messages=[
{"role": "system", "content": agent.instructions},
{"role": "user", "content": "Hello!"},
],
)