Skip to main content

Overview

The Agent class is the central component of Tyler, providing a flexible interface for creating AI agents with tool use, delegation capabilities, and conversation management.

Creating an Agent

All Parameters

string
default:"Tyler"
The name of your agent. This is used in the system prompt to give the agent an identity.
string
default:"gpt-4.1"
The LLM model to use. Supports any LiteLLM compatible model including OpenAI, Anthropic, Gemini, and more.
string | Prompt
default:"To be a helpful assistant."
The agent’s purpose or system prompt. Can be a string or a Tyler Prompt object for more complex prompts.
float
default:"0.7"
Controls randomness in responses. Range is 0.0 to 2.0, where lower values make output more focused and deterministic.
bool
default:"True"
Whether to automatically drop unsupported parameters for specific models. When True, parameters like temperature are automatically removed for models that don’t support them (e.g., O-series models). This ensures seamless compatibility across different model providers without requiring model-specific configuration.
List[Union[str, Dict, Callable, ModuleType]]
default:"[]"
List of tools available to the agent. Can include:
  • Direct tool function references (callables)
  • Tool module namespaces (modules like web, files)
  • Built-in tool module names (strings like "web", "files")
  • Custom tool definitions (dicts with ‘definition’, ‘implementation’, and optional ‘attributes’ keys)
For module names, you can specify specific tools using 'module:tool1,tool2' format.
List[Agent]
default:"[]"
List of sub-agents that this agent can delegate tasks to. Enables multi-agent systems and task delegation.
int
default:"10"
Maximum number of tool calls allowed per conversation turn. Prevents infinite loops in tool usage.
string | None
default:"None"
Custom API base URL for the model provider (e.g., for using alternative inference services). You can also use base_url as an alias for this parameter.
string | None
default:"None"
Alias for api_base. Either parameter can be used to specify a custom API endpoint.
string | None
default:"None"
API key for the model provider. If not provided, LiteLLM will use environment variables (e.g., OPENAI_API_KEY, WANDB_API_KEY). Use this when you need to explicitly pass an API key, such as with W&B Inference or custom providers.
Dict[str, str] | None
default:"None"
Additional headers to include in API requests. Useful for authentication tokens, API keys, or tracking headers.
string | Dict | None
default:"None"
Enable reasoning/thinking tokens for supported models (OpenAI o1/o3, DeepSeek-R1, Claude with extended thinking).
  • String: 'low', 'medium', 'high' (recommended for most use cases)
  • Dict: Provider-specific config (e.g., {'type': 'enabled', 'budget_tokens': 1024} for Anthropic)
When enabled, the model will show its internal reasoning process before generating the final answer.
bool
default:"False"
If True, the step() method will raise exceptions instead of returning error messages. Used for backward compatibility and custom error handling.
string | Prompt
default:""
Supporting notes to help the agent accomplish its purpose. These are included in the system prompt and can provide additional context or instructions.
string
default:"1.0.0"
Version identifier for the agent. Useful for tracking agent iterations and changes.
ThreadStore | None
default:"None"
Thread store instance for managing conversation threads. If not provided, uses the default thread store. This parameter is excluded from serialization.
FileStore | None
default:"None"
File store instance for managing file attachments. If not provided, uses the default file store. This parameter is excluded from serialization.
MessageFactory | None
default:"None"
Custom message factory for creating standardized messages. Advanced users can provide a custom implementation to control message formatting and structure. If not provided, uses the default factory. This parameter is excluded from serialization (recreated on deserialization).
CompletionHandler | None
default:"None"
Custom completion handler for LLM communication. Advanced users can provide a custom implementation to modify how the agent communicates with LLMs. If not provided, uses the default handler. This parameter is excluded from serialization (recreated on deserialization).
Type[BaseModel] | None
default:"None"
Optional Pydantic model to enforce structured output from the LLM. Uses the output-tool pattern: your Pydantic schema is registered as a special tool, and tool_choice="required" forces the model to call it. The validated model instance is available in AgentResult.structured_data.This approach allows regular tools to work alongside structured output. LiteLLM automatically translates tool_choice for different providers (OpenAI, Anthropic, Gemini, Bedrock, etc.).Can be set at the agent level (default for all runs) or overridden per run() call. See the Structured Output Guide for details.
RetryConfig | None
default:"None"
Configuration for automatic retry behavior. When enabled with structured output, the agent will automatically retry LLM calls if validation fails, providing error feedback to help the LLM correct its output.
See RetryConfig for all options.
Dict[str, Any] | None
default:"None"
Default request identity passed to tools via the ctx parameter. Primarily used for user/org/session identity that answers “who is making this request?”Can be set at the agent level (for system agents or default identity) or per run() call (typical for user requests). When both are provided, run-level merges with and overrides agent-level for conflicting keys.
Infrastructure (database clients, API clients) should be closed over at tool definition time, not passed in context. See ToolContext for the recommended pattern.
Literal['json'] | None
default:"None"
Simple JSON mode for when you want any valid JSON without schema validation. Pass response_format="json" to run() to force JSON output.
Cannot be used with response_type. Use response_type for schema validation, or response_format="json" for simple JSON without validation.

Creating from Config Files

classmethod
Create an Agent from a YAML configuration file. Enables reusing the same configuration between CLI and Python code.

Parameters

string | None
default:"None"
Path to YAML config file (.yaml or .yml). If None, searches standard locations:
  1. ./tyler-chat-config.yaml (current directory)
  2. ~/.tyler/chat-config.yaml (user home)
  3. /etc/tyler/chat-config.yaml (system-wide)
Any
Override any config values. These replace (not merge) config file values using shallow dict update semantics.Examples:
  • tools=["web"] replaces entire tools list
  • temperature=0.9 replaces temperature value
  • mcp={...} replaces entire mcp dict (not merged)

Config File Format

Config files use the same format as tyler-chat CLI configs, so you can share configurations between interactive CLI sessions and your Python code.

Advanced Config Loading

For more control over config loading, use load_config() directly:

Processing Conversations

Use stream(...) for interactive agent applications. It yields real-time events while the LLM and tools run, so callers can render partial text, show tool activity, and collect progress metadata as the agent works. Use run(...) when you want to wait for completion and inspect the final AgentResult. The backwards-compatible go(...) alias still maps to run(...).

Event Streaming Mode

Stream responses as high-level ExecutionEvent objects with full observability:

Non-Streaming Mode

With Structured Output

Get type-safe, validated responses using Pydantic models:

With Tool Context (Request Identity)

Pass request-scoped identity to your tools:
See ToolContext for the recommended pattern.

OpenAI Streaming Mode (mode=“openai”)

Raw mode is for advanced use cases requiring OpenAI compatibility. Tools ARE executed, but you only receive raw LiteLLM chunks (no ExecutionEvents for observability).
Stream raw LiteLLM chunks in OpenAI-compatible format for direct integration:
When to use openai mode:
  • Building OpenAI API proxies or gateways
  • Direct integration with OpenAI-compatible clients
  • Debugging provider-specific behavior
  • Minimal latency requirements (no transformation overhead)
How openai mode works:
  • ✅ Tools ARE executed (fully agentic behavior)
  • ✅ Multi-turn iteration supported (continues until task complete)
  • ✅ Raw chunks show tool calls via finish_reason: "tool_calls"
  • ⚠️ No ExecutionEvent telemetry (only raw chunks)
  • ⚠️ Silent during tool execution (brief pauses between chunk streams)
  • ⚠️ Consumer handles chunk formatting (SSE serialization, etc.)
The pattern matches OpenAI’s Agents SDK: chunks → finish_reason=“tool_calls” → [tools execute silently] → more chunks → repeat until done See the streaming guide for more details and examples.

Vercel AI SDK Streaming Mode (mode=“vercel”)

Perfect for React/Next.js frontends using @ai-sdk/react’s useChat hook.
Stream responses as SSE-formatted strings compatible with the Vercel AI SDK Data Stream Protocol:
When to use vercel mode:
  • Building React/Next.js chat interfaces with @ai-sdk/react
  • Direct integration with Vercel’s AI SDK ecosystem
  • Need SSE streams compatible with useChat hook
How vercel mode works:
  • ✅ Tools ARE executed (fully agentic behavior)
  • ✅ Thinking/reasoning tokens supported
  • ✅ Pre-formatted SSE strings ready for HTTP response
  • ✅ Compatible with x-vercel-ai-ui-message-stream: v1 protocol
See the streaming guide for complete examples including React frontend code.

Return Values

AgentResult (Non-Streaming)

execution is appended after the existing optional fields to preserve positional AgentResult(...) compatibility. result.success is True when no EXECUTION_ERROR event was emitted. When using response_type, the structured_data field contains the validated Pydantic model instance. See AgentResult for full documentation.

ExecutionEvent (Streaming)

Event Types

  • ITERATION_START - New iteration beginning
  • LLM_REQUEST - Request sent to LLM
  • LLM_RESPONSE - Complete response received
  • LLM_STREAM_CHUNK - Streaming content chunk
  • TOOL_SELECTED - Tool about to be called
  • TOOL_RESULT - Tool execution completed
  • TOOL_ERROR - Tool execution failed
  • MESSAGE_CREATED - New message added
  • EXECUTION_COMPLETE - All processing done
  • EXECUTION_ERROR - Processing failed
  • ITERATION_LIMIT - Max iterations reached

Execution Details

AgentResult.execution provides the full execution summary:

Working with Tools

Agent Delegation

Custom Configuration

Using custom API endpoints

W&B Inference configuration

For W&B Inference, you can also use YAML config with environment variable substitution:

Custom storage configuration

Weave Tracing and Serialization

Tyler Agent uses @weave.op() decorators for comprehensive tracing. When you initialize Weave, all agent method calls are automatically traced and logged to your Weave dashboard.
Don’t use weave.publish(agent) - Published Agent objects cannot be retrieved and used (Weave returns an unusable ObjectRecord). For reproducibility, publish your configuration instead:

Pydantic Serialization

Agents inherit from pydantic.BaseModel and support standard Pydantic serialization:
The following attributes are excluded from serialization and automatically recreated:
  • thread_store - Database connections
  • file_store - File system state
  • message_factory - Message creation helper
  • completion_handler - LLM communication helper
If you provide custom helpers, they will be preserved during initialization but not serialized.

Best practices

  1. Clear Purpose: Define a specific, focused purpose for each agent
  2. Tool Selection: Only include tools the agent actually needs
  3. Temperature: Use lower values (0.0-0.3) for consistency, higher (0.7-1.0) for creativity
  4. Error Handling: Always handle potential errors in production
  5. Token Limits: Monitor token usage to avoid hitting limits
  6. Streaming: Use streaming for better user experience in interactive applications

Example: Complete Application