This guide explains the differences between synchronous and asynchronous programming patterns in the AgentBay Python SDK.
The AgentBay Python SDK provides both synchronous and asynchronous APIs to accommodate different use cases and programming styles.
Use the synchronous API (AgentBay) for:
- Simple scripts and CLI tools
- Learning and experimentation
- Sequential operations where concurrency is not needed
Use the asynchronous API (AsyncAgentBay) for:
- Web servers (FastAPI, Django)
- High-concurrency applications
- Applications that need to handle multiple sessions simultaneously
from agentbay import AgentBay, CreateSessionParams
# Create client
agentbay = AgentBay(api_key="your_api_key")
# Create session
result = agentbay.create(CreateSessionParams())
session = result.session
# Use session
result = session.command.execute_command("echo 'Hello World'")
print(result.output)
# Cleanup
session.delete()import asyncio
from agentbay import AsyncAgentBay, CreateSessionParams
async def main():
# Create client
agentbay = AsyncAgentBay(api_key="your_api_key")
# Create session
result = await agentbay.create(CreateSessionParams())
session = result.session
# Use session
result = await session.command.execute_command("echo 'Hello World'")
print(result.output)
# Cleanup
await session.delete()
# Run async function
asyncio.run(main())| Aspect | Synchronous | Asynchronous |
|---|---|---|
| Import | from agentbay import AgentBay |
from agentbay import AsyncAgentBay |
| Method calls | session.command.execute_command() |
await session.command.execute_command() |
| Error handling | Standard try/except | Async try/except |
| Concurrency | Sequential | Concurrent with asyncio |
To migrate from synchronous to asynchronous code:
- Change imports from
AgentBaytoAsyncAgentBay - Add
asynckeyword to function definitions - Add
awaitkeyword before SDK method calls - Use
asyncio.run()to execute the main function
For migrating from backup versions or between sync/async, see Migration Guide.