Persistent Multi-Step Workflows with Managed Agents

FreeKeyAPIGemini · Updated 2026-11-24 · 13 min read

Diagram of Managed Agent architecture connecting to tools
Managed Agents connect to external tools for autonomous execution

Managed Agents represent a significant shift from simple prompt-response interactions to autonomous, stateful execution environments. By moving logic into a sandboxed runtime, you can build applications that maintain context across multiple tool calls and external actions without re-injecting history on every request. This architecture reduces token usage and latency for complex, multi-step processes, allowing the system to handle intricate decision trees independently.

The latest updates introduce Gemini 3.6 Flash as the default engine, offering improved reasoning and speed out of the box. You can now define environment hooks to run scripts before or after tool invocations, enabling fine-grained control over the agent's behavior. This creates a bridge between pure LLM reasoning and deterministic shell operations, a key feature for production-grade systems. While this guide focuses on the Gemini API, note that this site is not affiliated with Google, and the features described are specific to their managed environment.

This guide details how to structure these agents for production use. We will cover hook configuration, sandbox environment management, and the trade-offs between autonomous execution and deterministic scripting. Understanding these mechanics is essential before migrating your workflows from simple chat interfaces to persistent agent loops, especially when compared to local alternatives or other models like Qwen or Opus for specific tasks.

Frequently asked questions

What is a Managed Agent in the context of the Gemini API?

A Managed Agent is a sandboxed runtime environment that maintains state and executes tools autonomously. Unlike a standard chat completion, it persists context and can invoke external scripts or APIs based on its own reasoning, enabling complex multi-step workflows without manual orchestration.

How does a Managed Agent differ from a standard chat completion?

Standard completions are stateless single-turn or limited-turn exchanges. Managed Agents maintain persistent state, can execute multiple tool calls in a single logical operation, and run environment hooks. They are designed for sustained workflows rather than isolated Q&A interactions, offering deeper integration with external systems.

What is the default model for Managed Agents now?

Gemini 3.6 Flash is now the default model. It provides enhanced reasoning capabilities and lower latency compared to previous versions. You can still manually pick Gemini 3.5 Flash-Lite if you want lower cost or latency, giving you control over the balance between performance and expense.

How does context persistence work in Managed Agents?

Agents maintain a persistent conversation history within their sandbox. This allows them to reference previous tool outputs or decisions without re-sending the entire history. This reduces token consumption and improves performance for long-running tasks compared to standard chat contexts, which often suffer from context poisoning.

What are Environment Hooks and how do they function?

Hooks are scripts defined in a .agents/hooks.json file that run before or after tool calls. They allow you to inject deterministic logic, such as logging, data validation, or pre-processing, directly into the agent's execution flow, bridging the gap between probabilistic reasoning and fixed scripts for better reliability.

Which is better: Managed Agents or standard API calls for simple tasks?

For simple, single-turn tasks, standard API calls are more cost-effective and faster. Managed Agents introduce overhead due to sandbox initialization and state management. Use agents when you need persistent context, multiple tool invocations, or autonomous decision-making over a sequence of steps.

Can Managed Agents access external APIs?

Yes, agents can invoke tools that interact with external APIs. The sandbox environment allows agents to make HTTP requests and process responses. You can define custom tools or use built-in capabilities to fetch data, update databases, or trigger webhooks during execution, expanding their utility.

How do I control the cost of a Managed Agent workflow?

You can control costs by selecting a lighter model like Gemini 3.5 Flash-Lite, limiting the number of tool calls, and using environment hooks to filter data before it reaches the model. Monitoring token usage and optimizing prompt length also helps keep expenses predictable and within budget.

Step by step

  1. Define Agent Configuration — Create a configuration file specifying the model, tools, and environment hooks. Set the default model to Gemini 3.6 Flash for optimal performance and reasoning capabilities.
  2. Implement Environment Hooks — Write scripts for pre and post tool calls in .agents/hooks.json. Use these hooks for validation, logging, and data transformation to enhance reliability and control over the agent's behavior.
  3. Integrate Custom Tools — Define custom tools with clear descriptions and parameters. Test tool invocation to ensure the agent can accurately interpret and execute commands, ensuring seamless integration with your existing systems.
  4. Test Workflow Execution — Run end-to-end tests to verify sequential and parallel workflows. Monitor latency, token usage, and error rates to optimize performance and cost, ensuring the agent meets your requirements.

Understanding the Managed Agent Architecture

Managed Agents operate within a dedicated sandbox environment that isolates execution from the main application. This separation ensures that long-running processes do not block the user interface or consume excessive resources in your primary runtime. The agent maintains its own state, allowing it to remember previous actions and decisions without requiring explicit history injection from the client, which is crucial for maintaining continuity.

The core value proposition lies in autonomous tool usage. Instead of the client deciding which tool to call, the agent analyzes the current state, decides on the next action, and executes it. This reduces the complexity of your application code, as you no longer need to write complex orchestration logic to handle sequential tool calls. The agent handles the sequencing, error recovery, and conditional branching internally, making it ideal for complex workflows.

State Management and Persistence

Agents maintain a persistent conversation history within their sandbox. This allows them to reference previous tool outputs or decisions without re-sending the entire history. This reduces token consumption and improves performance for long-running tasks compared to standard chat contexts, which often suffer from context poisoning as the conversation grows.

Sandbox Isolation Benefits

Running agents in a sandbox prevents resource leaks and ensures consistent execution environments. Each agent instance has its own file system and network access, which can be configured independently. This isolation is critical for multi-tenant applications where agents need to operate without interfering with each other's data or processes, ensuring security and stability.

Configuring Environment Hooks

Environment hooks provide a powerful mechanism to inject deterministic logic into the agent's workflow. By defining a .agents/hooks.json file, you can specify scripts that run before or after specific tool calls. This allows you to perform data validation, logging, or pre-processing steps that are too rigid for the LLM to handle reliably. Hooks bridge the gap between probabilistic reasoning and fixed script execution, enhancing reliability.

Hooks are particularly useful for managing side effects. For example, you can use a hook to log the exact parameters passed to a tool, ensuring auditability without cluttering the agent's context. You can also use hooks to transform data formats before they are consumed by the next tool, reducing the need for the LLM to perform complex string manipulations and improving overall efficiency.

Pre-Call Hooks for Validation

Pre-call hooks run before the agent invokes a tool. You can use them to validate input parameters, check file existence, or verify permissions. This ensures that the agent only proceeds with valid actions, reducing errors and improving reliability. Hooks can also prepare the environment by downloading necessary files or setting up temporary directories for subsequent operations.

Post-Call Hooks for Logging

Post-call hooks execute after a tool completes. They are ideal for logging results, updating databases, or triggering notifications. Since hooks run in the same environment as the agent, they have direct access to the tool's output and can process it immediately. This allows for real-time monitoring and debugging of agent actions without parsing the entire conversation history.

  • Define hooks in .agents/hooks.json for precise control
  • Use pre-hooks for input validation and setup
  • Use post-hooks for logging and side effects
  • Hooks run in the same environment as the agent
{
  "hooks": {
    "pre": [
      {"tool": "search", "script": "validate_search_params.sh"}
    ],
    "post": [
      {"tool": "fetch_url", "script": "log_fetch_results.sh"}
    ]
  }
}
Flowchart of environment hooks workflow
Environment hooks run before and after tool calls

Model Selection and Performance

Gemini 3.6 Flash is now the default model for Managed Agents, offering improved reasoning and lower latency. This model is optimized for tool usage and multi-step workflows, making it suitable for most autonomous tasks. It provides a good balance between performance and cost, handling complex instructions with greater accuracy than previous versions. The upgrade is automatic, requiring no code changes from your side, which simplifies deployment.

For specific use cases, you might prefer Gemini 3.5 Flash-Lite. This model offers lower cost and faster response times, making it ideal for high-throughput scenarios where reasoning depth is less critical. You can manually specify the model in your agent configuration to override the default. This flexibility allows you to tailor the agent's performance to your specific latency and budget requirements, ensuring optimal resource usage.

Default Model Benefits

Gemini 3.6 Flash provides enhanced reasoning capabilities and lower latency compared to previous versions. It is optimized for tool usage and multi-step workflows, making it suitable for most autonomous tasks. The upgrade is automatic, requiring no code changes from your side, which simplifies deployment and reduces maintenance overhead.

Lightweight Model Alternatives

Gemini 3.5 Flash-Lite offers lower cost and faster response times. It is ideal for high-throughput scenarios where reasoning depth is less critical. You can manually specify the model in your agent configuration to override the default, allowing you to balance performance and cost effectively based on your specific needs.

Tool Integration and Execution

Tools are the primary interface through which agents interact with the external world. You can define custom tools or use built-in capabilities to fetch data, update databases, or trigger webhooks. The agent analyzes the current state and decides which tool to invoke next, based on its reasoning and the available options. This autonomous tool usage reduces the need for manual orchestration in your application, streamlining the development process.

Tool definitions include parameters, descriptions, and return types, which help the agent understand how to use them effectively. You can also specify constraints, such as maximum execution time or allowed file types, to ensure safe and predictable behavior. Tools can be chained together, allowing the output of one tool to serve as the input for another, enabling complex data transformations and dynamic workflows.

Custom Tool Definition

Custom tools allow you to extend the agent's capabilities with specific business logic. Define tools with clear descriptions and parameters to guide the agent's decision-making. The agent uses these descriptions to determine when and how to invoke the tool, ensuring accurate and relevant actions that align with your application's requirements.

Built-in Tool Capabilities

Built-in tools provide common functionalities like web search, file reading, and code execution. These tools are pre-configured and optimized for performance, reducing the need for custom implementation. You can combine built-in tools with custom tools to create a versatile agent capable of handling a wide range of tasks efficiently.

import openai

client = openai.OpenAI(
    api_key="your-api-key",
    base_url="https://api.freekeyapigemini.com/v1"
)

response = client.chat.completions.create(
    model="free-ai",
    messages=[{"role": "user", "content": "Search for recent news about AI agents."}],
    tools=[{"type": "function", "function": {"name": "search", "description": "Search the web", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}}]
)
Cloud server rack for agent deployment
Deploy agents on scalable cloud infrastructure

Workflow Orchestration Patterns

Orchestrating multi-step workflows requires careful design to ensure reliability and efficiency. Agents can handle sequential, parallel, and conditional workflows autonomously. Sequential workflows involve a series of steps executed in order, while parallel workflows allow multiple tools to run simultaneously. Conditional workflows enable branching based on the output of previous steps, creating dynamic execution paths that adapt to changing conditions.

Error handling is critical in autonomous workflows. Agents can retry failed tool calls, fallback to alternative tools, or terminate the workflow if a critical error occurs. This resilience ensures that the agent can recover from transient failures without requiring manual intervention. Properly designed workflows minimize the need for external oversight, allowing agents to operate independently for extended periods, reducing operational overhead.

Sequential Workflow Design

Sequential workflows execute steps in a defined order. Each step depends on the output of the previous one, ensuring a logical progression. This pattern is ideal for tasks like data processing pipelines, where each step transforms the data before passing it to the next, ensuring consistency and accuracy throughout the process.

Parallel and Conditional Logic

Parallel workflows allow multiple tools to run simultaneously, reducing overall execution time. Conditional logic enables branching based on tool outputs, creating dynamic execution paths. This flexibility allows agents to adapt to changing conditions and handle complex decision-making processes, making them suitable for a wide variety of use cases.

Cost Optimization Strategies

Managed Agents can incur higher costs than standard API calls due to state management and multiple tool invocations. To optimize costs, you can select lighter models like Gemini 3.5 Flash-Lite, limit the number of tool calls, and use environment hooks to filter data before it reaches the model. Monitoring token usage and optimizing prompt length also helps keep expenses predictable and within budget, ensuring long-term sustainability.

Another strategy is to reuse agent instances for similar tasks. Instead of creating a new agent for each request, you can maintain a persistent agent that handles multiple requests over time. This reduces the overhead of sandbox initialization and allows the agent to build up a richer context, improving accuracy and reducing the need for repeated explanations, which can significantly lower token consumption.

Model Selection Impact

Choosing a lighter model like Gemini 3.5 Flash-Lite can significantly reduce costs. These models are faster and cheaper, making them ideal for high-throughput scenarios. However, they may have lower reasoning accuracy, so test them thoroughly to ensure they meet your quality requirements before deploying them in production environments.

Context Management Efficiency

Efficient context management reduces token usage and improves performance. Use environment hooks to filter data and limit the amount of history sent to the agent. Summarize long conversations periodically to maintain context without consuming excessive tokens. This approach keeps the agent focused and responsive, preventing context poisoning and maintaining high quality.

Magnifying glass inspecting a document
Troubleshoot agent issues with detailed logging

Deployment and Scaling

Deploying Managed Agents at scale requires consideration of resource limits and concurrency. Each agent instance consumes resources in the sandbox, so you need to monitor usage and adjust scaling accordingly. Cloud providers offer auto-scaling capabilities, allowing you to handle spikes in demand without manual intervention. Ensure your infrastructure can support the number of concurrent agents you plan to run to avoid bottlenecks and ensure smooth operation.

Networking and security are also important factors. Agents may need to access external APIs or databases, so configure firewalls and access controls appropriately. Use environment variables to manage secrets and credentials, ensuring they are not exposed in logs or tool outputs. Regularly audit agent permissions to prevent unauthorized access to sensitive data, maintaining a secure environment for your applications.

Auto-scaling Considerations

Auto-scaling allows you to handle variable workloads efficiently. Monitor resource usage and set thresholds for scaling up or down. Ensure your infrastructure can support the number of concurrent agents you plan to run, and test under load to identify bottlenecks. This ensures that your application remains responsive and reliable even during peak usage periods.

Security Best Practices

Secure your agents by managing secrets with environment variables and limiting tool permissions. Audit agent actions regularly to detect anomalies. Use firewalls to restrict network access and ensure agents only communicate with trusted endpoints. Regularly update agent configurations to patch vulnerabilities, maintaining a robust security posture.

Troubleshooting Common Issues

Common issues with Managed Agents include context poisoning, where excessive history degrades performance, and tool execution failures due to network issues or API limits. Context poisoning can be mitigated by summarizing long conversations or using environment hooks to filter irrelevant data. Tool failures can be handled by implementing retry logic and fallback mechanisms in your agent configuration, ensuring resilience and reliability.

Another frequent issue is high latency due to large context windows or complex tool chains. Optimize your prompts and tool definitions to reduce token usage. Monitor agent performance metrics, such as latency and error rates, to identify bottlenecks. Use logging and hooks to trace execution paths and diagnose issues quickly, allowing for rapid resolution and minimal downtime.

Context Poisoning Solutions

Context poisoning occurs when excessive history degrades agent performance. Mitigate this by summarizing long conversations or using environment hooks to filter irrelevant data. Regularly prune the context to maintain focus and improve response quality, ensuring that the agent remains efficient and accurate over time.

Tool Execution Failures

Tool failures can result from network issues, API limits, or incorrect parameters. Implement retry logic and fallback mechanisms in your agent configuration. Log errors and monitor tool performance to identify and resolve issues promptly. Ensure your tools are robust and handle edge cases gracefully, minimizing disruptions to the workflow.

Gear and dollar sign icon
Optimize agent costs with efficient model selection
Try the free API

Test the keyless API with a one-line curl call right from your terminal to see how fast and reliable it is for your scripts.

Read also