Execution
Execution is the process BindAI uses to run an agent against an input and produce a result. An execution can involve the configured model, instructions, tools, memory, knowledge, retrieval, middleware, conversation context, execution configuration, and event handling depending on how the agent is configured. The main application-facing execution interfaces arerun(), chat(), and the streaming methods.
Running an Agent
A basic execution starts withagent.run():
output argument specifies a Python type that BindAI attempts to construct from the model’s JSON response.
Execution Result
agent.run() returns an AgentResult when the execution pipeline completes normally.
Structured Output
Execution can return structured results instead of plain text. For example, a Pydantic model can define the expected structure:run():
- Parse the model response as JSON.
- Pass the resulting mapping to the requested output type.
- Return the constructed object when this succeeds.
Tool Execution
Agents can be configured with tools. For example:Execution Pipeline
Normal agent execution uses a pipeline with the following stages:- the model produces a response without tool calls, or
- the configured maximum tool-iteration count is reached.
max_tool_iterations value is 10.
Initialization
The initialization stage prepares the execution state from the current agent and execution context. The user’s input is obtained from the execution context and added as a user message. If the agent has system instructions and the conversation does not already contain messages, the instructions are added as a system message. The execution state then contains aModelRequest built from the current conversation and the definitions of the registered tools.
Conceptually:
Knowledge
If an agent has a retriever or knowledge component, the knowledge stage can retrieve information relevant to the current user input. For example:Memory
Memory can be attached to an agent:__context__ memory record.
When a memory record is available, BindAI adds its value to the conversation as a system message:
__context__ memory key when memory is configured.
The stored transcript is built from the conversation messages involved in the execution.
Memory is therefore distinct from the current conversation object: memory provides persisted context that can be loaded into a later execution.
Conversation Context
Agent execution incorporates the current conversation into the model request. A conversational execution can conceptually combine:Knowledge and Retrievers
Knowledge can be attached to an agent:Retrieval-Augmented Generation
Knowledge and retrieval can be combined with agent execution to implement Retrieval-Augmented Generation. A typical execution flow is:Tool Execution Loop
When a model response contains tool calls, BindAI enters the tool-execution stage. For each requested tool call, BindAI:- Adds the assistant’s tool-call message to the conversation.
- Executes the requested tool.
- Converts the tool result into a tool message.
- Adds the tool message to the conversation.
- Rebuilds the next model request from the updated conversation.
- Increments the execution iteration count.
- Returns to model generation.
Multiple Tool Calls
A model response can request multiple tools during the same execution step. For example:Tool Execution Failures
Tool execution can fail. A failed tool execution is preserved as explicit tool-result content rather than being silently represented as a successful value. For example:Tool Iterations
Tool-using agents may perform multiple model/tool interaction cycles during a single execution. BindAI controls this loop throughAgentConfiguration.max_tool_iterations.
The default value is:
Middleware
Middleware provides reusable execution behavior. Attach middleware directly:AgentResult.
Middleware is useful for cross-cutting concerns such as:
- Logging
- Authentication
- Telemetry
- Metrics
- Request processing
- Response processing
- Other reusable execution behavior
Execution Context
Some BindAI execution APIs operate with anExecutionContext.
For example, the low-level stream() API accepts an execution context:
Streaming
BindAI exposes streaming APIs for execution. The low-levelstream() method accepts an ExecutionContext:
stream_chat():
stream_chat() creates the execution context from the supplied message, while stream() operates on an existing execution context.
Streaming uses a separate execution pipeline:
run() or chat() execution: the application consumes provider output progressively rather than receiving a completed AgentResult from the streaming pipeline.
Common streaming use cases include:
- Chat interfaces
- Interactive applications
- Long-running responses
- Real-time user interfaces
Chat Execution
BindAI also provides achat() method:
chat() can accept an optional structured-output type:
run() delegates to the same conversational execution path used by chat().
Use the execution interface that best matches the application’s interaction model.
For conversational applications, chat() can be combined with the agent’s conversation, memory, knowledge, and tool capabilities.
Events
Agents expose an event bus throughagent.events.
For example, an application can subscribe to tool execution events:
AgentStartedEventAgentFinishedEventModelRequestEventModelResponseEventToolExecutedEvent
- Monitoring
- Logging
- Analytics
- Auditing
- Observability
- Notifications
- Automation integrations
Hooks and Callbacks
Agents expose lifecycle and callback mechanisms for execution-related behavior. The built-in lifecycle callbacks include:before_runafter_runerror
before_runis called before the execution pipeline.- Middleware
before_executehooks run. - The execution pipeline runs.
- Middleware
after_executehooks run after successful execution. after_runis called after successful execution.
AgentResult.
Hooks and callbacks can be used for:
- Custom logging
- Notifications
- Auditing
- Metrics
- External integrations
- Debugging
Execution Configuration
BindAI exposes execution configuration throughAgentConfiguration.
The available settings include:
max_tool_iterations, which limits repeated model/tool cycles.
temperature and max_tokens provide model-generation configuration.
stream and verbose are available as configuration fields, while the explicit streaming APIs provide the streaming execution path.
Execution configuration should be kept separate from behavioral instructions whenever possible.
For example, instructions should describe what an agent should do, while execution configuration can control runtime behavior and limits.
Execution and Projects
Agents can be organized as part of a BindAI project. Project configuration can provide the surrounding application structure for:- Agents
- Tools
- Workflows
- Knowledge
- Memory
- Templates
- Tests
- Application configuration
Agent.builder().
For example:
bindai.toml.
When an agent is built from project configuration, the builder can load the project runtime configuration and resolve the configured provider and model.
Project-scoped provider connections can also be selected through project configuration.
For example:
Execution and Workflows
Agents can participate in larger workflows. A workflow can coordinate agent execution with operations such as:- Conditions
- Loops
- Parallel execution
- Retries
- Timeouts
- Human tasks
- Scheduling
Execution and Multi-Agent Systems
Agent execution can also be combined with delegation and multi-agent patterns. A primary agent can delegate work to specialist agents:Execution and External Tools
Agent execution can interact with external systems through tools and connection integrations. Connections provide integration infrastructure, while tools can expose appropriate external operations to an agent. This keeps external service logic separate from the agent’s core execution behavior. For example:Execution and MCP
BindAI also supports MCP connections and MCP-discovered tools. MCP tools can become part of an agent’s available execution capabilities. The MCP integration provides functionality around:- MCP client connections
- Tool discovery
- Tool calling
- MCP tools exposed as BindAI tools
- Connection handling
Error Handling
Normal execution should check the returnedAgentResult when application behavior depends on the result state.
- BindAI invokes the agent’s error callback.
- The exception is re-raised.
- The
AgentFinishedEventis still published through the execution engine’sfinallyblock.
AgentResult handling and appropriate exception handling when execution reliability is important.
Tool execution failures are handled separately inside the tool-execution cycle. They are converted into tool-result information so that the model can receive the failure and decide how to continue.
Execution Boundaries
Agent execution can involve multiple components:- Instructions define behavior.
- Conversation provides interaction context.
- Memory provides persisted information.
- Knowledge and retrieval provide external information.
- Tools provide actions.
- Middleware provides reusable execution behavior.
- The model provider performs model inference.
AgentResultprovides the application-facing result for normal completed execution.
A Complete Execution Example
The following example combines basic agent execution with a tool:search tool. BindAI executes the tool, records its result, and continues model execution with the updated conversation.
The same agent can later be extended with additional capabilities:
Execution Best Practices
- Use
run()for general agent execution. - Use
chat()for conversational execution. - Use
stream()orstream_chat()when output needs to be processed progressively. - Use structured output when downstream code requires predictable data, while accounting for raw-response fallback.
- Configure reasonable
max_tool_iterationslimits for tool-using agents. - Treat tool failures as execution information rather than assuming every tool call succeeds.
- Use memory when persisted information is required.
- Use knowledge and retrievers for external information.
- Use middleware for reusable cross-cutting behavior.
- Use hooks and callbacks for lifecycle integrations.
- Use the event bus for event-driven integrations and observability.
- Check
AgentResult.successwhen normal execution failure needs to be handled explicitly. - Catch runtime exceptions when provider, middleware, callback, or other execution failures must be handled by the application.
- Keep runtime configuration separate from behavioral instructions.
- Use workflows when multiple agents or execution stages need to be coordinated.
- Use explicit multi-agent processes when multi-agent work should be represented as structured tasks.
- Use parallel execution only when tasks can safely run concurrently.
- Use task dependencies when one task requires the result of another.
- Keep external integrations behind connections or tools.
- Use MCP when an external MCP service provides capabilities that should be exposed to an agent.
