Building AI Agents
AI agents are systems that use language models to autonomously complete complex, multi-step tasks by reasoning, using tools, and coordinating with other agents. This guide covers everything you need to build production-ready agents.
Choosing Your Approach
GlomaxGPT offers three primary ways to build agents, each suited for different use cases and levels of control.
Agents SDK
A high-level Python framework that orchestrates agents, tools, handoffs, and guardrails with minimal boilerplate. Best for production use.
- Built-in tracing and observability
- Native handoff primitives
- Input/output guardrails
- Streaming support
Responses API
Direct API access for building custom agent loops. Maximum flexibility with built-in tools like web search and file search.
- Full control over agentic loop
- Any language/framework
- Built-in tool support
- Conversation state management
Agents API
A fully managed, stateful agent API that handles conversation history, tool execution, and file storage server-side.
- Server-side state management
- Built-in file storage
- Automatic tool execution
- REST API for any language
Getting Started with the Agents SDK
Install the Agents SDK and create your first agent in minutes.
Install the SDK
pip install GlomaxGPT-agents
Create a basic agent
from agents import Agent, Runner
agent = Agent(
name="Assistant",
model="glomaxgpt-pro",
instructions="You are a helpful assistant. Be concise and accurate."
)
result = await Runner.run(agent, "What is the square root of 144?")
print(result.final_output) # 12
Add tools to the agent
from agents import Agent, Runner
from agents.tools import WebSearchTool, FileSearchTool
agent = Agent(
name="Research Assistant",
model="glomaxgpt-pro",
instructions="You are a research assistant. Search the web for current information and provide accurate, well-cited answers.",
tools=[
WebSearchTool(),
FileSearchTool(vector_store_ids=["vs_abc123"])
]
)
result = await Runner.run(
agent,
"What are the most recent AI safety papers published in 2025?"
)
print(result.final_output)
Custom Function Tools
Extend your agent with custom Python functions. The SDK automatically generates the schema and handles execution.
from agents import Agent, Runner, function_tool
import requests
@function_tool
def get_weather(city: str) -> str:
"""Get the current weather for a city.
Args:
city: The name of the city to get weather for.
"""
# In production, call a real weather API
response = requests.get(f"https://api.weather.example.com/current?city={city}")
data = response.json()
return f"Weather in {city}: {data['condition']}, {data['temp_c']}°C"
@function_tool
def calculate(expression: str) -> str:
"""Safely evaluate a mathematical expression.
Args:
expression: A mathematical expression like '2 + 2 * 10'
"""
import ast
tree = ast.parse(expression, mode='eval')
result = eval(compile(tree, '', 'eval'))
return str(result)
agent = Agent(
name="Utility Agent",
model="glomaxgpt-pro",
instructions="You help users with weather information and calculations.",
tools=[get_weather, calculate]
)
result = await Runner.run(
agent,
"What's the weather in Tokyo? Also, what is 15% of 2,847?"
)
print(result.final_output)
Handoffs & Multi-agent Systems
Agents can hand off tasks to specialized sub-agents. This allows you to build modular systems where each agent has a focused role.
from agents import Agent, Runner, handoff
from agents.tools import WebSearchTool
# Specialist agents
billing_agent = Agent(
name="Billing Specialist",
model="glomaxgpt-pro",
instructions="""You handle billing inquiries. You can:
- Look up invoices and payment history
- Process refunds for eligible purchases
- Explain pricing and subscription tiers
Always be professional and empathetic."""
)
technical_agent = Agent(
name="Technical Support",
model="glomaxgpt-pro",
instructions="""You handle technical issues. You can:
- Diagnose API integration problems
- Help with SDK installation and configuration
- Explain error codes and troubleshooting steps
Search documentation when needed.""",
tools=[WebSearchTool()]
)
# Triage agent that routes to specialists
triage_agent = Agent(
name="Customer Support Triage",
model="glomaxgpt-pro",
instructions="""You are the first point of contact.
Determine the nature of the user's request and route to the appropriate specialist.
For billing issues → hand off to Billing Specialist.
For technical issues → hand off to Technical Support.
For general questions, answer directly.""",
handoffs=[
handoff(billing_agent),
handoff(technical_agent)
]
)
result = await Runner.run(
triage_agent,
"I was charged twice for my subscription this month."
)
print(result.final_output)
print(f"Handled by: {result.last_agent.name}")
Guardrails
Guardrails run checks on agent inputs and outputs to ensure safety, quality, and policy compliance. They can halt execution if a check fails.
from agents import Agent, Runner, GuardrailFunctionOutput, input_guardrail
from agents import TResponseInputItem
from pydantic import BaseModel
class ContentSafetyOutput(BaseModel):
is_safe: bool
reason: str
safety_checker = Agent(
name="Safety Checker",
model="glomaxgpt-mini",
instructions="Check if the input is safe and appropriate. Flag harmful, illegal, or abusive requests.",
output_type=ContentSafetyOutput
)
@input_guardrail
async def safety_guardrail(ctx, agent, input: str | list[TResponseInputItem]):
result = await Runner.run(safety_checker, input, context=ctx.context)
output = result.final_output_as(ContentSafetyOutput)
return GuardrailFunctionOutput(
output_info=output,
tripwire_triggered=not output.is_safe
)
protected_agent = Agent(
name="Protected Assistant",
model="glomaxgpt-pro",
instructions="You are a helpful assistant.",
input_guardrails=[safety_guardrail]
)
try:
result = await Runner.run(protected_agent, "User's message here")
print(result.final_output)
except Exception as e:
print(f"Guardrail triggered: {e}")
from agents import Agent, Runner, GuardrailFunctionOutput, output_guardrail
from pydantic import BaseModel
class PIICheckOutput(BaseModel):
contains_pii: bool
pii_types: list[str]
pii_checker = Agent(
name="PII Detector",
model="glomaxgpt-mini",
instructions="Detect if the text contains personally identifiable information (PII) like names, emails, phone numbers, SSNs, or credit card numbers.",
output_type=PIICheckOutput
)
@output_guardrail
async def pii_guardrail(ctx, agent, output: str):
result = await Runner.run(pii_checker, output, context=ctx.context)
check = result.final_output_as(PIICheckOutput)
return GuardrailFunctionOutput(
output_info=check,
tripwire_triggered=check.contains_pii
)
agent = Agent(
name="Safe Data Agent",
model="glomaxgpt-pro",
instructions="You help with data analysis. Never include customer PII in your responses.",
output_guardrails=[pii_guardrail]
)
glomaxgpt-mini for guardrail checks to minimize latency overhead.
Tracing & Observability
The Agents SDK includes built-in tracing that records every step of your agent's execution — model calls, tool invocations, handoffs, and guardrail checks.
from agents import Agent, Runner
from agents.tracing import trace, set_tracing_export_api_key
# Enable tracing export to GlomaxGPT dashboard
set_tracing_export_api_key(api_key="your_GlomaxGPT_api_key")
agent = Agent(
name="Traced Agent",
model="glomaxgpt-pro",
instructions="You are a helpful assistant."
)
# Wrap your run in a named trace for grouping
with trace("Customer Support Session"):
result = await Runner.run(agent, "Help me understand my invoice.")
# Access trace data programmatically
for step in result.trace.steps:
print(f"Step: {step.type} | Duration: {step.duration_ms}ms")
if step.type == "model_call":
print(f" Tokens: {step.usage.total_tokens}")
elif step.type == "tool_call":
print(f" Tool: {step.tool_name}")
platform.glomaxgpt.com/traces. You can visualize agent timelines, inspect individual steps, replay sessions, and set up alerts for anomalies.
Building Agents with the Responses API
For maximum control, build your own agent loop directly with the Responses API. This approach works in any language.
from GlomaxGPT import GlomaxGPT
import json
client = GlomaxGPT()
tools = [
{"type": "web_search_preview"},
{
"type": "function",
"name": "send_email",
"description": "Send an email to a recipient",
"parameters": {
"type": "object",
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
"body": {"type": "string"}
},
"required": ["to", "subject", "body"]
}
}
]
def send_email(to, subject, body):
# Your email sending implementation
return {"status": "sent", "message_id": "msg_xyz123"}
def run_agent(user_message: str):
input_messages = user_message
while True:
response = client.responses.create(
model="glomaxgpt-pro",
instructions="You are a helpful assistant that can search the web and send emails.",
input=input_messages,
tools=tools
)
# Check if we're done
if response.status == "completed":
return response.output_text
# Process tool calls
tool_results = []
for item in response.output:
if item.type == "function_call":
args = json.loads(item.arguments)
if item.name == "send_email":
result = send_email(**args)
tool_results.append({
"type": "function_call_output",
"call_id": item.call_id,
"output": json.dumps(result)
})
# Continue the loop with tool results
input_messages = response.output + tool_results
result = run_agent("Search for the latest GPT model pricing and send a summary email to team@example.com")
print(result)
Voice Agents
Build real-time voice agents using the Realtime API. Combine speech recognition, language models, and text-to-speech in a single low-latency pipeline.
from agents import Agent
from agents.voice import VoicePipeline, SingleAgentVoiceWorkflow
# Define your agent as usual
voice_agent = Agent(
name="Voice Assistant",
model="glomaxgpt-pro",
instructions="""You are a real-time voice assistant.
Keep responses concise and conversational — remember the user is listening, not reading.
Use natural speech patterns and avoid bullet points or markdown."""
)
# Wrap in a voice pipeline
pipeline = VoicePipeline(
workflow=SingleAgentVoiceWorkflow(voice_agent),
stt_settings={"language": "en"},
tts_settings={"voice": "alloy", "speed": 1.0}
)
# Feed audio chunks and receive audio output
async with pipeline.run() as session:
async for audio_chunk in mic_stream():
await session.send_audio(audio_chunk)
async for response_audio in session.audio_stream:
await speaker.play(response_audio)
En İyi Uygulamalar
Start Simple
Begin with a single agent before adding multi-agent complexity. Most tasks can be solved with one well-prompted agent and the right tools. Add orchestration only when tasks genuinely require parallel or specialized work.
Use Structured Outputs
Define Pydantic models for your agent's output type. This ensures reliable, parseable results and makes it easy to validate that the agent completed its task correctly.
Set Clear Instructions
Write detailed, specific system instructions. Include what the agent should do, what it should not do, how to handle edge cases, and what tone to use. Vague instructions lead to unpredictable behavior.
Test with Evals
Build an evaluation suite before deploying. Test your agent against representative inputs and edge cases. Use the tracing dashboard to identify failure modes and iteratively improve instructions and tool configurations.