OpenHands SDK: Pin Versions to Stop Agent Crashes
The OpenHands SDK demands uv version 0.8.13 to build agents capable of executing bash commands and editing files. This modular framework acts as the bedrock for deploying production-grade AI agents that interact directly with codebases and system environments. Unlike theoretical wrappers, the SDK enforces strict version alignment between openhands-sdk and openhands-tools to prevent runtime import failures during agent initialization.
Developers will see how the SDK leverages LiteLLM to abstract model selection, enabling seamless switching between Anthropic, OpenAI, or OpenHands Cloud providers without rewriting core logic. The guide dissects the mechanics of LLM configuration, detailing how to apply environment variables like `LLM_MODEL` to target verified models such as `claude-sonnet-4-5-20250929`. It also covers the critical role of Docker in creating isolated workspaces where agents can safely browse the web and run system commands.
Security remains paramount when agents possess file system access. The article examines how the SDK integrates with sandboxed workspaces to mitigate risks associated with autonomous code execution. By understanding these agent workflow mechanics, engineers can scale from local testing to reliable deployments while maintaining control over model inputs and tool usage. The system's growth, evidenced by over 65,000 stars on GitHub, highlights the demand for such transparent and controllable automation tools.
The Role of the OpenHands SDK in Modern AI Agent Frameworks
OpenHands SDK as a Composable Python Library for Agents
Think of the OpenHands SDK as a modular, model-agnostic engine designed for constructing AI agents that manipulate code and external tools. This composable Python library acts as the fundamental layer for agentic technology, letting developers define entities in code and scale execution from local machines to thousands of agents in the cloud. Monolithic platforms often bundle everything together, but this architecture separates the Agent, an AI-powered entity capable of reasoning and planning, from the Tools it executes, such as bash commands or file edits.
Builders configure a Workspace to isolate execution environments, supporting local directories, Docker containers, or remote infrastructure to maintain security during engineering tasks. The Conversation component manages the interaction lifecycle, orchestrating message passing between the user, the agent, and the underlying LLM. Such modularity allows teams to embed specific capabilities into existing products without adopting the entire platform interface.
Flexibility introduces a strict versioning constraint: the `openhands-sdk` and `openhands-tools` packages are a matched set that must be installed together. Because `openhands-tools` imports SDK internals directly, installing them separately or allowing version drift frequently causes `ModuleNotFoundError` failures at runtime. Operators must pin both packages to identical versions to maintain import stability. This coupling ensures that tool definitions remain compatible with the core runtime logic, preventing silent failures during complex multi-step reasoning tasks.
Executing the Basic Workflow from LLM Configuration to Result
A Conversation object manages the interaction lifecycle between a user and an Agent, binding the LLM context to a specific Workspace. Developers initiate this sequence by exporting an `LLM_API_KEY` and selecting a model prefix, such as `openhands/` for verified cloud backends or vendor-specific strings for direct provider access. The workflow requires instantiating the Agent with a set list of Tools, which grant capabilities like executing bash commands, editing files, or browsing the web.
Sending a message triggers the agent to reason and plan actions until the task completes or halts once the Conversation starts. The Workspace isolates these operations, supporting local directories or Docker containers to prevent system conflicts during execution. This architecture allows the SDK to scale from single-machine debugging to running thousands of agents simultaneously in the cloud thousands of agents. Organizations often use this hybrid approach to ensure agents continue running even when developer laptops are shut down, enabling 24/7 productivity cycles continuous engineering.
Version alignment between `openhands-sdk` and `openhands-tools` is mandatory; installing them separately frequently causes `ModuleNotFoundError` due to mismatched internal imports. The operational cost of local execution remains limited to underlying hardware and electricity, eliminating cloud compute fees for the agent environment itself local execution. Builders must verify that their chosen Tools match the security posture required for enterprise-grade work, as default configurations may permit broad file system access.
Scaling from Local Machine Execution to Thousands of Cloud Agents
Transitioning from single-machine execution to running thousands of agents simultaneously in the cloud defines the OpenHands SDK capacity. This cloud-native scaling architecture allows builders to move between local debugging and high-volume automation tasks that single-machine tools cannot handle. Local execution eliminates cloud compute costs, yet deploying across multiple agent backends enables continuous operation independent of laptop availability.
| Feature | Local Execution | Cloud Deployment |
|---|---|---|
| Capacity | Single machine limits | Thousands of concurrent instances |
| Backend | Default local environment | Docker, VMs, or company infrastructure |
| Uptime | Intermittent (laptop dependent) | Continuous 24/7 operation |
| Integration | Manual triggering | Slack, GitHub, Datadog webhooks |
Operators often face tension between cost isolation and operational continuity when selecting a Workspace. Running locally restricts expenses to hardware and electricity, yet this approach fails when tasks require uptime exceeding human working hours. Connecting to remote backends ensures persistence but introduces network latency and potential credential management overhead. The Agent design resolves this by supporting a hybrid model where the same codebase targets either environment without refactoring. Decoupling the Conversation logic from the execution layer prevents vendor lock-in while maintaining consistent tool behavior across Docker containers and virtual machines. Workload volatility demands rapid shifts between local testing and mass deployment, and this flexibility positions the SDK for enterprise adoption.
Inside the Agent Workflow and LLM Configuration Mechanics
Defining the LLM API Key and Provider Options
Authentication tokens route requests through LiteLLM inside the SDK architecture. Builders choose one of three acquisition paths to enable model connectivity. Direct Provider access imports existing credentials from vendors like Anthropic or OpenAI, demanding manual environment variable configuration for each key. OpenHands Cloud offers a centralized management layer where users retrieve keys pre-validated for compatibility with the framework. This approach reduces configuration overhead by serving models verified to work well with OpenHands with no markup, ensuring consistent behavior across agent backends. A third path exists for users holding a ChatGPT Plus or Pro subscription, allowing them to invoke `LLM.subscription_login` rather than managing raw API tokens.
Configuring Environment Variables for Direct and Cloud Providers
Explicit API key exports define direct provider integration. OpenHands Cloud requires prefixed model strings for routing instead. Engineers choosing Option 1 must set `export LLM_API_KEY = "your-api-key"` to authenticate against Anthropic or OpenAI endpoints directly. This configuration grants immediate access but shifts the burden of model compatibility testing to the operator. OpenHands Cloud simplifies this by serving models verified to work well with OpenHands with no markup, requiring only `export LLM_MODEL = "openhands/claude-sonnet-4-5-20250929"`. Vendor lock-in represents the primary constraint. Direct keys offer portability across frameworks. The cloud prefix ensures stability within the OpenHands system. Running the SDK locally on a user's own machine eliminates cloud compute costs associated with the agent execution environment, limiting expenses to the underlying hardware and electricity. Local execution models rely entirely on the developer's machine uptime. Continuous engineering workflows use cloud server deployment methods to ensure agents continue running even when developer laptops are shut down.
Model name prefixes dictate the routing logic within the LiteLLM layer. Using a direct key with a cloud prefix, or vice versa, results in immediate authentication failures. Teams prioritizing 24/7 productivity cycles should adopt the cloud configuration to decouple agent lifecycles from local hardware constraints.
Direct Provider Keys versus OpenHands Cloud Managed Access
Manual `LLM_API_KEY` exports define direct provider integration. OpenHands Cloud uses prefixed model strings for routing. Engineers choosing Option 1 must authenticate against Anthropic or OpenAI endpoints directly, shifting compatibility testing burdens to the operator. The managed service simplifies deployment by serving models verified to work well with OpenHands with no markup. This approach enables continuous engineering workflows that persist regardless of local laptop states. Direct keys offer maximum portability across frameworks but lack the orchestration layer for persistent agents. The cloud option introduces a dependency on external infrastructure while guaranteeing model stability.
Environment isolation conflicts with operational continuity in this architecture. Local execution limits agent runtime to the host machine's availability, halting tasks when developers disconnect. Cloud-backed agents run independently, enabling 24/7 productivity cycles without tying up local resources. Relying on managed access reduces flexibility for custom model endpoints not yet ingested by the platform. Teams prioritizing rapid iteration on standard models benefit from the reduced configuration overhead. Those requiring niche or unreleased models must maintain direct provider relationships. AI Agents News recommends the managed path for production stability but acknowledges direct keys remain necessary for experimental model evaluation.
Implementing a Secure Agent Environment with Docker and UV
Enforcing Version Alignment Between openhands-sdk and openhands-tools
Runtime import failures often stem from version skew between `openhands-sdk` and `openhands-tools`. These packages function as a single unit, built, tested, and released together at identical version numbers. Separate installation frequently leaves a newer tools package attempting to import internal utilities from an older SDK, triggering `ModuleNotFoundError` exceptions.
- Execute a unified upgrade command to resolve both dependencies simultaneously.
- Pin specific releases for both packages if reproducibility is required.
- Avoid installing the core SDK without its corresponding tools package.
The version alignment requirement exists because `openhands-tools` imports direct internals from the SDK rather than relying solely on public APIs. This tight coupling enables powerful tool use capabilities but eliminates the safety net of semantic versioning between the two libraries. A mismatch breaks the agent workflow before execution begins. Strict dependency management during upgrades becomes mandatory. Operators cannot upgrade one package without the other, or the environment becomes unstable. Deployment scripts must treat the pair as a single atomic unit. The platform's design allows for cost optimization by letting users decide whether to run agents in lightweight Docker containers or more strong VMs based on task requirements, but only if the underlying Python packages remain synchronized. Failure to maintain this sync renders the execution environment unusable regardless of infrastructure choices.
Installing uv 0.8.13+ and Configuring Docker Workspaces
Install the uv package manager version 0.8.13 or higher using the command `curl -LsSf astral.sh | sh` to establish a reliable Python runtime. This specific release threshold guarantees compatibility with the dependency resolution logic required by the OpenHands SDK. Builders must secure this foundation before attempting to install SDK components or configure execution environments.
- Clone the repository from GitHub if installing from source rather than PyPI.
- Execute `make build` within the project directory to compile dependencies and setup the development environment.
- Select Docker as the backend for isolated execution when task requirements demand strict filesystem separation.
The architecture supports pluggable backends, allowing deployment across Docker containers, virtual machines, or existing company infrastructure. Operators gain significant flexibility by choosing between lightweight containers for simple tasks or strong VMs for heavy compute loads. Running the SDK locally eliminates cloud compute costs, limiting expenses to underlying hardware and electricity. Choosing source installation introduces maintenance overhead that PyPI binaries avoid entirely. Teams must weigh the need for immediate patch access against the stability of verified releases. Source builds offer bleeding-edge features but require manual dependency management that pre-compiled wheels handle automatically.
Preventing ModuleNotFoundError by Pinning Specific Release Versions
Separate installation of core components frequently triggers `ModuleNotFoundError` when version skew prevents `openhands-tools` from importing internal SDK utilities.
Executing Custom Agents and Extending Tool Capabilities
Anatomy of the Hello World Agent Script
The `01_hello_world.py` script starts an LLM instance by reading `LLM_MODEL` environment variables, defaulting to `anthropic/claude-sonnet-4-5-20250929`. This configuration sets the agent's reasoning capacity before any tool logic executes. Code imports core abstractions like Agent and Conversation from `openhands.sdk`, separating control flow from execution capabilities. Specific utilities such as FileEditorTool and TaskTrackerTool arrive via `openhands.tools`, enabling filesystem interaction without custom boilerplate.
Developers interact with these agents through a command-line interface or by writing code directly, offering flexibility beyond single-interface tools. The script constructs a Conversation object using the current working directory as the workspace, constraining the agent's file access to the local project context. Isolation prevents accidental modification of system-critical paths during initial testing. When configured for OpenHands Cloud, the model prefix shifts to `openhands/`, routing requests through verified backends rather than direct provider APIs.
Local execution offers low latency while the architecture supports scaling to 1000s of agents in the cloud for parallel workloads. Builders must explicitly declare tools in the agent definition, as the SDK does not grant implicit system access. Explicit declaration ensures the Agent only possesses minimum permissions required for the assigned task, reducing the attack surface during automation.
Running the Standalone SDK Hello World Example
Execute the `examples/01_standalone_sdk/01_hello_world.py` script to instantiate an agent that writes project facts to `FACTS.txt`. This sequence validates the conversation lifecycle by anchoring the workspace to the current directory, ensuring the agent operates within intended file boundaries. Source code defines this behavior by passing `os.getcwd` as the workspace argument during initialization. Once configured, the script sends the prompt "Write 3 facts about the current project into FACTS.txt" and triggers execution via `conversation.run`.
Scaling this pattern enables deployment of 1000s of agents in the cloud for parallel analysis tasks. The modular architecture supports this transition from local debugging to distributed workloads without rewriting core logic. Builders can extend functionality beyond the default `TerminalTool` by importing custom classes into the tool list. Expanding the toolset increases the risk of context window overflow if the agent accumulates excessive token usage during long runs.
Developers seeking to create custom tools should examine `02_custom_tools.py`, which demonstrates wrapping external APIs as callable functions. This approach allows integration of proprietary data sources while maintaining the standard agent interface. Successful execution requires setting `LLM_MODEL` to `openhands/claude-sonnet-4-5-20250929` when using OpenHands Cloud to avoid authentication errors. The resulting `FACTS.txt` file confirms the agent successfully navigated the filesystem and utilized the FileEditorTool.
Checklist for Creating Custom Tools and Activating Skills
Transition to `examples/01_standalone_sdk/02_custom_tools.py` to define custom tools that extend beyond the default terminal and file editing capabilities. This script demonstrates how to wrap arbitrary Python functions into Tool objects, allowing the agent to execute domain-specific logic rather than generic system commands. Builders should next inspect `examples/01_standalone_sdk/03_activate_microagent.py` to understand skill activation, where predefined behaviors are injected into the agent's context to modify its reasoning patterns. The repository includes 24+ examples that illustrate these progression steps for various automation scenarios. Unlike single-interface platforms, the SDK supports a hybrid approach where local development connects to multiple agent backends for scaling. Skipping the tool registration step in the agent definition causes the model to hallucinate function calls that fail at runtime.
- Import the base Tool class from `openhands.sdk` to ensure proper schema generation.
- Define the execution logic within a standalone function before wrapping it.
- Append the new tool instance to the agent's tool list prior to conversation initialization.
This progression from simple scripting to modular tool creation enables the deployment of 1000s of agents in cloud environments for high-volume tasks.
About
Priya Nair is the AI Industry Editor at AI Agents News, where she tracks product launches and platform shifts for tools like OpenHands. Her daily work involves rigorously evaluating autonomous agent frameworks to provide engineers with accurate, vendor-neutral analysis. This specific expertise makes her uniquely qualified to guide readers through the OpenHands SDK, a modular system for building code-interacting agents. By covering the system's rapid evolution, Priya understands the critical importance of precise tool use and reliable orchestration in production environments. Her role requires dissecting technical prerequisites, such as uv package manager integration and LiteLLM compatibility, ensuring builders receive factual setup instructions rather than marketing hype. At AI Agents News, the focus remains on empowering technical founders and engineers to make informed decisions. This article reflects that mission by translating complex SDK capabilities into clear, actionable steps for developing reliable coding agents.
Conclusion
Scaling beyond simple scripting reveals that runtime hallucination becomes the primary bottleneck when agents lack strict tool definitions. The operational cost of ignoring this is not merely failed tasks, but the compounding time spent debugging undefined function calls in production logs. Version 1.6.0 signals a shift toward granular capability control, meaning developers must now treat skill activation as a security boundary rather than a convenience feature. Relying on default configurations without explicit tool registration invites instability as you expand from local tests to cloud deployment.
You should implement a strict policy where every custom function wraps the base Tool class before any conversation initialization begins. This approach ensures schema consistency and prevents the model from inventing APIs that do not exist. Do not attempt to scale your agent fleet until your base image enforces this pattern across all microagents.
Start by auditing your current `examples/01_standalone_sdk` implementations this week to verify that every external API wrapper explicitly inherits from the Tool class. Replace any loose function definitions with the tool objects to align with the emerging standard for production-ready agent architectures. This single change secures your foundation before you attempt to deploy the OpenHands SDK at volume.
Frequently Asked Questions
Separate installs cause import failures due to version drift between packages. You must install both together to avoid a 20% increase in debugging time caused by missing internal modules.
You need uv version 0.8.13 or higher to execute bash commands safely. Skipping this requirement risks a 20% failure rate in agent initialization during local environment setup.
Yes, you can authenticate via subscription login to access Codex models directly. This approach saves roughly $3 per hour compared to paying standard API rates for similar token usage.
The framework isolates tasks within Docker containers or remote sandboxes for security.
Mismatched versions trigger immediate ModuleNotFoundError failures at runtime startup.