# Authentication Source: https://docs.run-agent.ai/api-reference/authentication API authentication and security ## Overview All RunAgent API requests require authentication using API keys. This guide covers how to obtain, use, and manage API keys securely. ## Obtaining API Keys ### Via CLI ```bash theme={null} # Setup authentication runagent setup # View current API key runagent config show --key api_key ``` ### Via Dashboard 1. Log in to [dashboard.run-agent.ai](https://dashboard.run-agent.ai) 2. Navigate to API Keys section 3. Click "Create New Key" 4. Copy and save securely ## Using API Keys ### Header Authentication Include your API key in the Authorization header: ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ https://api.run-agent.ai/v1/agents ``` ### SDK Authentication ```python theme={null} # Python SDK from runagent import RunAgentClient client = RunAgentClient( agent_id="agent-123", api_key="YOUR_API_KEY" ) ``` ### Environment Variable Set the API key as an environment variable: ```bash theme={null} export RUNAGENT_API_KEY="YOUR_API_KEY" ``` ## API Key Types ### Personal Keys * Tied to your user account * Full access to your resources * Should not be shared ### Service Keys * For production applications * Limited scope and permissions * Can be revoked independently ### Temporary Keys * Short-lived tokens * For testing or demos * Auto-expire after set time ## Security Best Practices ### Key Storage Never commit API keys to version control or expose them in client-side code. **DO:** ```python theme={null} # Use environment variables api_key = os.environ["RUNAGENT_API_KEY"] # Or configuration files (gitignored) with open(".secrets/api_key") as f: api_key = f.read().strip() ``` **DON'T:** ```python theme={null} # Never hardcode keys api_key = "sk-abc123..." # WRONG! ``` ### Key Rotation Regularly rotate your API keys: ```bash theme={null} # Generate new key runagent keys create --name "production-2024" # Update your application export RUNAGENT_API_KEY="new-key" # Revoke old key runagent keys revoke "old-key-id" ``` ### Scope Limitation Create keys with minimal required permissions: ```bash theme={null} # Read-only key runagent keys create --scope read --name "monitoring" # Agent-specific key runagent keys create --agent-id agent-123 --name "agent-specific" ``` ## Request Signing For additional security, enable request signing: ```python theme={null} import hmac import hashlib import time def sign_request(method, path, body, secret): timestamp = str(int(time.time())) message = f"{method}\n{path}\n{timestamp}\n{body}" signature = hmac.new( secret.encode(), message.encode(), hashlib.sha256 ).hexdigest() return { "X-Signature": signature, "X-Timestamp": timestamp } ``` ## OAuth 2.0 (Coming Soon) Future support for OAuth 2.0 flow: ```python theme={null} # Authorization URL auth_url = "https://auth.run-agent.ai/oauth/authorize" params = { "client_id": "your-client-id", "redirect_uri": "https://yourapp.com/callback", "response_type": "code", "scope": "agents:read agents:write" } ``` ## Rate Limiting API keys have associated rate limits: | Tier | Requests/Hour | Burst | | ---------- | ------------- | ------ | | Free | 100 | 10 | | Pro | 1,000 | 100 | | Enterprise | Custom | Custom | Rate limit headers: ``` X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 999 X-RateLimit-Reset: 1640995200 ``` ## IP Whitelisting Restrict API key usage to specific IPs: ```bash theme={null} # Add IP to whitelist runagent keys update --add-ip 192.168.1.1 # List whitelisted IPs runagent keys show ``` ## Monitoring Key Usage ### Via CLI ```bash theme={null} # View key usage runagent keys usage # Set usage alerts runagent keys alert --threshold 80 ``` ### Via API ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ https://api.run-agent.ai/v1/keys/usage ``` ## Error Responses ### Invalid Key ```json theme={null} { "error": { "code": "INVALID_API_KEY", "message": "The provided API key is invalid", "status": 401 } } ``` ### Expired Key ```json theme={null} { "error": { "code": "EXPIRED_API_KEY", "message": "The API key has expired", "status": 401 } } ``` ### Rate Limited ```json theme={null} { "error": { "code": "RATE_LIMITED", "message": "Too many requests", "status": 429, "retry_after": 3600 } } ``` ## Troubleshooting ### Key Not Working 1. Check key format (should start with `ra_`) 2. Verify key hasn't expired 3. Ensure proper Authorization header format 4. Check IP whitelist settings 5. Verify rate limits haven't been exceeded ### Permission Denied 1. Check key scope and permissions 2. Verify resource ownership 3. Ensure key is active 4. Check organization settings ## See Also * [API Introduction](/api-reference/introduction) - API overview * [Error Handling](/api-reference/errors) - Error responses * [Rate Limits](/api-reference/rate-limits) - Rate limiting details # Health Check Source: https://docs.run-agent.ai/api-reference/endpoints/health Check agent health status ## GET /v1/agents/\{agent\_id}/health Check the health status of a deployed agent. ### Request ```bash theme={null} GET https://api.run-agent.ai/v1/agents/{agent_id}/health Authorization: Bearer YOUR_API_KEY ``` ### Path Parameters The unique identifier of the agent ### Response Overall health status: `healthy`, `degraded`, or `unhealthy` Individual health check results Agent process health External dependency status Resource utilization Current agent version Uptime in seconds ## Examples ### Basic Health Check ```bash cURL theme={null} curl https://api.run-agent.ai/v1/agents/agent-123/health \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```python Python theme={null} import requests response = requests.get( "https://api.run-agent.ai/v1/agents/agent-123/health", headers={"Authorization": "Bearer YOUR_API_KEY"} ) health = response.json() print(f"Status: {health['status']}") ``` ```javascript JavaScript theme={null} const response = await fetch( 'https://api.run-agent.ai/v1/agents/agent-123/health', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const health = await response.json(); console.log(`Status: ${health.status}`); ``` ### Response Examples #### Healthy Agent ```json theme={null} { "status": "healthy", "checks": { "agent": { "status": "healthy", "response_time_ms": 45 }, "dependencies": { "openai_api": "healthy", "database": "healthy" }, "resources": { "memory_usage_percent": 65, "cpu_usage_percent": 20 } }, "version": "1.2.3", "uptime": 3600, "last_request": "2024-01-01T12:00:00Z" } ``` #### Degraded Agent ```json theme={null} { "status": "degraded", "checks": { "agent": { "status": "healthy", "response_time_ms": 150 }, "dependencies": { "openai_api": "healthy", "database": "slow" }, "resources": { "memory_usage_percent": 85, "cpu_usage_percent": 75 } }, "version": "1.2.3", "uptime": 7200, "warnings": ["High memory usage", "Database latency detected"] } ``` ## Health Check Logic Status is determined by: 1. **Healthy**: All checks pass 2. **Degraded**: Some checks show warnings but agent is functional 3. **Unhealthy**: Critical checks fail ## Monitoring Integration ### Automated Monitoring ```python theme={null} import time def monitor_agent(agent_id, interval=60): while True: try: response = requests.get( f"https://api.run-agent.ai/v1/agents/{agent_id}/health", headers={"Authorization": "Bearer YOUR_API_KEY"} ) health = response.json() if health['status'] != 'healthy': send_alert(f"Agent {agent_id} is {health['status']}") except Exception as e: send_alert(f"Health check failed: {e}") time.sleep(interval) ``` ### Prometheus Integration ```python theme={null} # Expose metrics for Prometheus from prometheus_client import Gauge agent_health = Gauge('agent_health_status', 'Agent health status', ['agent_id']) memory_usage = Gauge('agent_memory_usage', 'Memory usage percentage', ['agent_id']) def update_metrics(agent_id): health = get_agent_health(agent_id) status_value = {'healthy': 1, 'degraded': 0.5, 'unhealthy': 0} agent_health.labels(agent_id=agent_id).set(status_value[health['status']]) memory = health['checks']['resources']['memory_usage_percent'] memory_usage.labels(agent_id=agent_id).set(memory) ``` ## Best Practices 1. **Regular Monitoring**: Check health every 30-60 seconds 2. **Set Alerts**: Alert on status changes 3. **Track Trends**: Monitor resource usage over time 4. **Implement Retries**: Handle temporary network issues ## See Also * [Monitoring Guide](/runagent-cloud/cloud-deployment#monitoring) - Full monitoring setup * [Status Endpoint](/api-reference/endpoints/get-agent) - Detailed agent info * [Metrics API](/api-reference/webhooks) - Metrics collection # Invoke Agent Source: https://docs.run-agent.ai/api-reference/endpoints/invoke Synchronously invoke an agent ## POST /v1/agents/\{agent\_id}/invoke Invoke an agent and receive a synchronous response. ### Request ```bash theme={null} POST https://api.run-agent.ai/v1/agents/{agent_id}/invoke Content-Type: application/json Authorization: Bearer YOUR_API_KEY ``` ### Path Parameters The unique identifier of the agent to invoke ### Request Body The input query or prompt for the agent Additional parameters for the agent Sampling temperature (0.0 to 2.0) Maximum tokens in response Additional context for the agent Session ID for maintaining conversation context ### Response The agent's response Token usage information Tokens used in the prompt Tokens used in the response Total tokens used Additional metadata Time taken in seconds Version of the agent ## Examples ### Basic Invocation ```bash cURL theme={null} curl -X POST https://api.run-agent.ai/v1/agents/agent-123/invoke \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "What is the weather like in San Francisco?" }' ``` ```python Python theme={null} import requests response = requests.post( "https://api.run-agent.ai/v1/agents/agent-123/invoke", headers={ "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, json={ "query": "What is the weather like in San Francisco?" } ) result = response.json() print(result["result"]) ``` ```javascript JavaScript theme={null} const response = await fetch( 'https://api.run-agent.ai/v1/agents/agent-123/invoke', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ query: 'What is the weather like in San Francisco?' }) } ); const result = await response.json(); console.log(result.result); ``` ### With Parameters ```json theme={null} { "query": "Write a story about AI", "parameters": { "temperature": 0.8, "max_tokens": 500, "style": "science fiction" }, "session_id": "user-123-session" } ``` ### Response Example ```json theme={null} { "result": { "answer": "The weather in San Francisco is currently 65°F with partly cloudy skies.", "confidence": 0.95, "sources": ["current_weather_api"] }, "usage": { "prompt_tokens": 24, "completion_tokens": 18, "total_tokens": 42 }, "metadata": { "execution_time": 1.23, "agent_version": "1.0.0", "request_id": "req_abc123" } } ``` ## Error Responses ### 400 Bad Request Missing required field: ```json theme={null} { "error": { "code": "MISSING_REQUIRED_FIELD", "message": "Field 'query' is required", "status": 400 } } ``` ### 404 Not Found Agent doesn't exist: ```json theme={null} { "error": { "code": "AGENT_NOT_FOUND", "message": "Agent 'agent-123' not found", "status": 404 } } ``` ### 429 Rate Limited ```json theme={null} { "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "Too many requests", "status": 429, "retry_after": 60 } } ``` ## Best Practices 1. **Include Session ID** for conversations to maintain context 2. **Set Appropriate Timeouts** as agent processing can take time 3. **Handle Errors Gracefully** with retry logic for 5xx errors 4. **Monitor Token Usage** to optimize costs ## See Also * [Stream Endpoint](/api-reference/endpoints/stream) - For streaming responses * [Authentication](/api-reference/authentication) - API authentication * [Error Handling](/api-reference/errors) - Error responses # Stream Agent Response Source: https://docs.run-agent.ai/api-reference/endpoints/stream Stream agent responses in real-time ## POST /v1/agents/\{agent\_id}/stream Stream agent responses using Server-Sent Events (SSE) for real-time output. ### Request ```bash theme={null} POST https://api.run-agent.ai/v1/agents/{agent_id}/stream Content-Type: application/json Authorization: Bearer YOUR_API_KEY Accept: text/event-stream ``` ### Path Parameters The unique identifier of the agent ### Request Body Same as the [invoke endpoint](/api-reference/endpoints/invoke): The input query for the agent Additional parameters Session ID for context ### Response Format Server-Sent Events stream with the following event types: ``` event: start data: {"message": "Stream started"} event: chunk data: {"content": "The weather in "} event: chunk data: {"content": "San Francisco is "} event: done data: {"message": "Stream complete", "usage": {...}} ``` ## Event Types ### start Sent when streaming begins ``` event: start data: {"message": "Stream started", "session_id": "abc123"} ``` ### chunk Content chunks as they're generated ``` event: chunk data: {"content": "Hello, ", "index": 0} ``` ### error Error during streaming ``` event: error data: {"error": "Processing failed", "code": "STREAM_ERROR"} ``` ### done Stream completion with metadata ``` event: done data: { "message": "Stream complete", "usage": { "total_tokens": 150 }, "execution_time": 2.5 } ``` ## Examples ### JavaScript (Browser) ```javascript theme={null} const eventSource = new EventSource( 'https://api.run-agent.ai/v1/agents/agent-123/stream', { headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' } } ); eventSource.onmessage = (event) => { const data = JSON.parse(event.data); if (event.type === 'chunk') { // Append chunk to output document.getElementById('output').innerHTML += data.content; } }; eventSource.onerror = (error) => { console.error('Stream error:', error); eventSource.close(); }; // Send request to start streaming fetch('https://api.run-agent.ai/v1/agents/agent-123/stream', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ query: 'Tell me a story about space' }) }); ``` ### Python ```python theme={null} import requests import json def stream_agent_response(agent_id, query): url = f"https://api.run-agent.ai/v1/agents/{agent_id}/stream" headers = { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json", "Accept": "text/event-stream" } response = requests.post( url, headers=headers, json={"query": query}, stream=True ) for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith('data: '): data = json.loads(line[6:]) if 'content' in data: print(data['content'], end='', flush=True) # Usage stream_agent_response("agent-123", "Explain quantum computing") ``` ### Node.js ```javascript theme={null} const EventSource = require('eventsource'); const eventSource = new EventSource( 'https://api.run-agent.ai/v1/agents/agent-123/stream', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); let fullResponse = ''; eventSource.addEventListener('chunk', (event) => { const data = JSON.parse(event.data); fullResponse += data.content; process.stdout.write(data.content); }); eventSource.addEventListener('done', (event) => { const data = JSON.parse(event.data); console.log('\n\nStream complete:', data); eventSource.close(); }); eventSource.addEventListener('error', (event) => { console.error('Stream error:', event); eventSource.close(); }); ``` ## Handling Stream Interruptions ### Client-Side Reconnection ```javascript theme={null} let reconnectAttempts = 0; const maxReconnects = 3; function connectStream() { const eventSource = new EventSource(url, options); eventSource.onerror = (error) => { eventSource.close(); if (reconnectAttempts < maxReconnects) { reconnectAttempts++; setTimeout(() => { console.log(`Reconnecting... (${reconnectAttempts}/${maxReconnects})`); connectStream(); }, Math.pow(2, reconnectAttempts) * 1000); } }; eventSource.addEventListener('done', () => { reconnectAttempts = 0; // Reset on success }); } ``` ### Resume from Position ```json theme={null} { "query": "Continue the story", "parameters": { "resume_from_index": 150 }, "session_id": "abc123" } ``` ## Stream Control ### Abort Stream Close the connection to stop streaming: ```javascript theme={null} // JavaScript eventSource.close(); // Python response.close() // cURL # Ctrl+C to interrupt ``` ### Rate Control Control streaming speed with parameters: ```json theme={null} { "query": "Explain slowly", "parameters": { "stream_delay_ms": 100, "chunk_size": 10 } } ``` ## Error Handling ### Network Errors ```javascript theme={null} eventSource.onerror = (event) => { if (event.readyState === EventSource.CLOSED) { console.log('Connection closed'); } else { console.error('Connection error:', event); // Implement retry logic } }; ``` ### Stream Errors ``` event: error data: {"error": "Model overloaded", "code": "CAPACITY_ERROR", "retry_after": 30} ``` ## Best Practices 1. **Implement Reconnection Logic** for network interruptions 2. **Handle Partial Responses** gracefully 3. **Set Appropriate Timeouts** for long-running streams 4. **Monitor Memory Usage** when buffering responses 5. **Provide User Feedback** during streaming ## Performance Tips * Use compression when available * Process chunks as they arrive * Implement backpressure handling * Consider chunking large responses ## See Also * [Invoke Endpoint](/api-reference/endpoints/invoke) - Synchronous invocation * [WebSockets](/api-reference/webhooks) - Alternative streaming method * [Error Handling](/api-reference/errors) - Stream error codes # Error Handling Source: https://docs.run-agent.ai/api-reference/errors Understanding and handling API errors ## Overview The RunAgent API uses standard HTTP status codes and returns detailed error information in a consistent format. This guide covers common errors and how to handle them. ## Error Response Format All errors follow this structure: ```json theme={null} { "error": { "code": "ERROR_CODE", "message": "Human-readable error message", "details": { "field": "Additional context" }, "request_id": "req_abc123", "documentation_url": "https://docs.run-agent.ai/errors/ERROR_CODE" } } ``` ## HTTP Status Codes | Status | Meaning | Common Causes | | ------ | ------------------- | --------------------------------------- | | 200 | Success | Request completed successfully | | 201 | Created | Resource created successfully | | 400 | Bad Request | Invalid parameters or malformed request | | 401 | Unauthorized | Missing or invalid API key | | 403 | Forbidden | Insufficient permissions | | 404 | Not Found | Resource doesn't exist | | 409 | Conflict | Resource already exists | | 422 | Unprocessable | Valid syntax but semantic errors | | 429 | Too Many Requests | Rate limit exceeded | | 500 | Internal Error | Server-side error | | 503 | Service Unavailable | Temporary maintenance | ## Common Error Codes ### Authentication Errors #### INVALID\_API\_KEY ```json theme={null} { "error": { "code": "INVALID_API_KEY", "message": "The provided API key is invalid", "status": 401 } } ``` **Solution:** Check your API key format and ensure it's correct. #### EXPIRED\_API\_KEY ```json theme={null} { "error": { "code": "EXPIRED_API_KEY", "message": "The API key has expired", "status": 401 } } ``` **Solution:** Generate a new API key from the dashboard. ### Validation Errors #### MISSING\_REQUIRED\_FIELD ```json theme={null} { "error": { "code": "MISSING_REQUIRED_FIELD", "message": "Required field 'query' is missing", "details": { "field": "query", "requirement": "string, min length 1" }, "status": 400 } } ``` #### INVALID\_FIELD\_TYPE ```json theme={null} { "error": { "code": "INVALID_FIELD_TYPE", "message": "Field 'temperature' must be a number", "details": { "field": "temperature", "provided": "string", "expected": "number" }, "status": 400 } } ``` ### Resource Errors #### AGENT\_NOT\_FOUND ```json theme={null} { "error": { "code": "AGENT_NOT_FOUND", "message": "Agent with ID 'agent-123' not found", "details": { "agent_id": "agent-123" }, "status": 404 } } ``` #### DEPLOYMENT\_FAILED ```json theme={null} { "error": { "code": "DEPLOYMENT_FAILED", "message": "Failed to deploy agent", "details": { "reason": "Invalid configuration", "validation_errors": ["Missing entrypoint"] }, "status": 422 } } ``` ### Rate Limiting #### RATE\_LIMIT\_EXCEEDED ```json theme={null} { "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "API rate limit exceeded", "details": { "limit": 100, "remaining": 0, "reset_at": "2024-01-01T00:00:00Z" }, "status": 429 } } ``` ### Server Errors #### INTERNAL\_ERROR ```json theme={null} { "error": { "code": "INTERNAL_ERROR", "message": "An internal error occurred", "request_id": "req_xyz789", "status": 500 } } ``` ## Error Handling Best Practices ### Python Example ```python theme={null} import requests from time import sleep def call_api_with_retry(url, data, max_retries=3): for attempt in range(max_retries): try: response = requests.post(url, json=data) response.raise_for_status() return response.json() except requests.exceptions.HTTPError as e: if e.response.status_code == 429: # Rate limited - wait and retry retry_after = int(e.response.headers.get('Retry-After', 60)) sleep(retry_after) continue elif e.response.status_code >= 500: # Server error - retry with backoff if attempt < max_retries - 1: sleep(2 ** attempt) continue # Don't retry client errors (4xx) error_data = e.response.json() raise Exception(f"API Error: {error_data['error']['message']}") except requests.exceptions.RequestException as e: # Network error - retry if attempt < max_retries - 1: sleep(2 ** attempt) continue raise raise Exception("Max retries exceeded") ``` ### JavaScript Example ```javascript theme={null} async function callAPIWithRetry(url, data, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${API_KEY}` }, body: JSON.stringify(data) }); if (!response.ok) { const error = await response.json(); if (response.status === 429) { // Rate limited const retryAfter = response.headers.get('Retry-After') || 60; await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); continue; } if (response.status >= 500 && attempt < maxRetries - 1) { // Server error - retry with exponential backoff await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000)); continue; } throw new Error(error.error.message); } return await response.json(); } catch (error) { if (attempt === maxRetries - 1) throw error; // Network error - retry await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000)); } } } ``` ## Debugging Errors ### Request ID Every error includes a `request_id` for debugging: ```bash theme={null} # Contact support with request ID "request_id": "req_abc123xyz" ``` ### Detailed Logging Enable detailed logging in SDKs: ```python theme={null} import logging logging.basicConfig(level=logging.DEBUG) # Now SDK will log all requests/responses client = RunAgentClient(agent_id="...", debug=True) ``` ### Common Solutions 1. **400 Bad Request** * Validate JSON syntax * Check required fields * Verify data types 2. **401 Unauthorized** * Check API key format * Verify key hasn't expired * Ensure proper header format 3. **429 Rate Limited** * Implement exponential backoff * Check rate limit headers * Consider upgrading plan 4. **500 Internal Error** * Retry with backoff * Check status page * Contact support if persistent ## Webhook Error Handling For webhook endpoints, implement proper error handling: ```python theme={null} @app.post("/webhook") async def handle_webhook(request): try: # Process webhook data = await request.json() process_webhook(data) return {"status": "success"} except ValidationError: # Return 400 for validation errors return JSONResponse( status_code=400, content={"error": "Invalid webhook data"} ) except Exception as e: # Return 500 for server errors # RunAgent will retry 500 errors return JSONResponse( status_code=500, content={"error": "Internal error"} ) ``` ## See Also * [API Introduction](/api-reference/introduction) - API overview * [Authentication](/api-reference/authentication) - Auth errors * [Rate Limits](/api-reference/rate-limits) - Rate limiting details # API Introduction Source: https://docs.run-agent.ai/api-reference/introduction RESTful API for interacting with RunAgent ## Overview The RunAgent API is a RESTful interface that allows you to deploy, manage, and interact with AI agents programmatically. All API access is over HTTPS, and data is sent and received as JSON. ## Base URL ``` https://api.run-agent.ai/v1 ``` For local development: ``` http://localhost:8000 ``` ## Authentication All API requests require authentication using an API key: ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ https://api.run-agent.ai/v1/agents ``` Never expose your API key in client-side code or public repositories. ## Request Format ### Headers Required headers for all requests: ```http theme={null} Authorization: Bearer YOUR_API_KEY Content-Type: application/json Accept: application/json ``` ### Request Body POST and PUT requests accept JSON: ```json theme={null} { "query": "Your input here", "parameters": { "temperature": 0.7, "max_tokens": 150 } } ``` ## Response Format ### Success Response ```json theme={null} { "status": "success", "data": { "result": "Agent response here", "metadata": { "execution_time": 1.23, "tokens_used": 150 } } } ``` ### Error Response ```json theme={null} { "status": "error", "error": { "code": "INVALID_INPUT", "message": "Query parameter is required", "details": { "field": "query", "reason": "missing" } } } ``` ## Status Codes | Code | Meaning | | ---- | -------------- | | 200 | Success | | 201 | Created | | 400 | Bad Request | | 401 | Unauthorized | | 404 | Not Found | | 429 | Rate Limited | | 500 | Internal Error | ## Rate Limiting API requests are rate limited: * **Free tier**: 100 requests per hour * **Pro tier**: 1,000 requests per hour * **Enterprise**: Custom limits Rate limit headers: ```http theme={null} X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 999 X-RateLimit-Reset: 1640995200 ``` ## Pagination List endpoints support pagination: ```bash theme={null} GET /v1/agents?page=2&limit=20 ``` Response includes pagination metadata: ```json theme={null} { "data": [...], "pagination": { "page": 2, "limit": 20, "total": 100, "pages": 5 } } ``` ## Versioning The API is versioned via the URL path: * Current version: `v1` * Legacy support: 12 months * Deprecation notices: 6 months in advance ## Common Patterns ### Async Operations Long-running operations return immediately: ```json theme={null} { "operation_id": "op_123abc", "status": "pending", "check_url": "/v1/operations/op_123abc" } ``` ### Streaming Responses For streaming endpoints, use Server-Sent Events: ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ -H "Accept: text/event-stream" \ https://api.run-agent.ai/v1/agents/123/stream ``` ### Batch Operations Submit multiple requests in one call: ```json theme={null} { "batch": [ {"query": "Question 1"}, {"query": "Question 2"}, {"query": "Question 3"} ] } ``` ## SDK vs Direct API | Feature | SDK | Direct API | | ----------------- | -------- | ---------- | | Ease of use | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | | Type safety | ✅ | ❌ | | Auto-retry | ✅ | ❌ | | Streaming support | ✅ | Manual | | Language support | Multiple | Any | ## Quick Start ```bash theme={null} # List agents curl -H "Authorization: Bearer YOUR_API_KEY" \ https://api.run-agent.ai/v1/agents # Invoke agent curl -X POST \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"query": "Hello"}' \ https://api.run-agent.ai/v1/agents/AGENT_ID/invoke ``` ```python theme={null} import requests headers = { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" } # List agents response = requests.get( "https://api.run-agent.ai/v1/agents", headers=headers ) # Invoke agent response = requests.post( "https://api.run-agent.ai/v1/agents/AGENT_ID/invoke", headers=headers, json={"query": "Hello"} ) ``` ```javascript theme={null} // List agents const response = await fetch('https://api.run-agent.ai/v1/agents', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }); // Invoke agent const result = await fetch('https://api.run-agent.ai/v1/agents/AGENT_ID/invoke', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ query: 'Hello' }) }); ``` ## Next Steps Set up API authentication Explore available endpoints * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Rate Limits Source: https://docs.run-agent.ai/api-reference/rate-limits API rate limiting and quotas ## Overview RunAgent implements rate limiting to ensure fair usage and platform stability. Rate limits apply per API key and vary by subscription tier. ## Rate Limit Tiers | Tier | Requests/Hour | Requests/Minute | Concurrent Requests | | ---------- | ------------- | --------------- | ------------------- | | Free | 100 | 10 | 2 | | Pro | 1,000 | 100 | 10 | | Team | 5,000 | 500 | 25 | | Enterprise | Custom | Custom | Custom | ## Rate Limit Headers Every API response includes rate limit information: ```http theme={null} X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 999 X-RateLimit-Reset: 1640995200 X-RateLimit-Reset-After: 3600 ``` | Header | Description | | ------------------------- | -------------------------------- | | `X-RateLimit-Limit` | Maximum requests allowed | | `X-RateLimit-Remaining` | Requests remaining in window | | `X-RateLimit-Reset` | Unix timestamp when limit resets | | `X-RateLimit-Reset-After` | Seconds until limit resets | ## Rate Limit Response When rate limited, you'll receive a 429 response: ```json theme={null} { "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "API rate limit exceeded", "details": { "limit": 100, "remaining": 0, "reset_at": "2024-01-01T13:00:00Z", "retry_after": 3600 }, "status": 429 } } ``` ## Handling Rate Limits ### Exponential Backoff ```python theme={null} import time import requests def call_with_backoff(url, max_retries=5): for attempt in range(max_retries): response = requests.get(url, headers=headers) if response.status_code == 429: # Get retry time from header or use exponential backoff retry_after = int(response.headers.get('Retry-After', 2 ** attempt)) print(f"Rate limited. Waiting {retry_after} seconds...") time.sleep(retry_after) continue return response raise Exception("Max retries exceeded") ``` ### Rate Limit Aware Client ```python theme={null} class RateLimitedClient: def __init__(self, api_key, requests_per_hour=1000): self.api_key = api_key self.requests_per_hour = requests_per_hour self.request_times = [] def _wait_if_needed(self): now = time.time() hour_ago = now - 3600 # Remove old requests self.request_times = [t for t in self.request_times if t > hour_ago] # Check if at limit if len(self.request_times) >= self.requests_per_hour: sleep_time = self.request_times[0] + 3600 - now if sleep_time > 0: time.sleep(sleep_time) def request(self, method, url, **kwargs): self._wait_if_needed() self.request_times.append(time.time()) return requests.request(method, url, **kwargs) ``` ## Quota Types ### API Request Quotas Standard rate limits for API calls: * Invoke endpoint: Standard rate limits apply * Stream endpoint: Counts as single request * Health endpoint: Not rate limited ### Token Quotas Monthly token usage limits: | Tier | Tokens/Month | | ---------- | ------------ | | Free | 100,000 | | Pro | 2,000,000 | | Team | 10,000,000 | | Enterprise | Custom | ### Concurrent Request Limits Maximum simultaneous requests: ```python theme={null} import asyncio from asyncio import Semaphore class ConcurrentLimitedClient: def __init__(self, max_concurrent=10): self.semaphore = Semaphore(max_concurrent) async def request(self, url): async with self.semaphore: # Make request return await make_async_request(url) ``` ## Monitoring Usage ### Check Current Usage ```bash theme={null} GET https://api.run-agent.ai/v1/usage Authorization: Bearer YOUR_API_KEY ``` Response: ```json theme={null} { "period": "2024-01-01T00:00:00Z", "requests": { "used": 523, "limit": 1000, "remaining": 477 }, "tokens": { "used": 45230, "limit": 2000000, "remaining": 1954770 } } ``` ### Usage Alerts Set up alerts when approaching limits: ```bash theme={null} POST https://api.run-agent.ai/v1/alerts { "type": "rate_limit", "threshold": 80, "webhook_url": "https://your-app.com/alerts" } ``` ## Best Practices ### 1. Implement Retry Logic ```javascript theme={null} async function requestWithRetry(url, options, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { const response = await fetch(url, options); if (response.status === 429) { const retryAfter = response.headers.get('Retry-After') || 60; await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); continue; } return response; } catch (error) { if (i === maxRetries - 1) throw error; } } } ``` ### 2. Batch Requests ```python theme={null} # Instead of individual requests for item in items: api.process(item) # 100 requests # Batch them api.process_batch(items) # 1 request ``` ### 3. Cache Responses ```python theme={null} import functools import time def timed_cache(seconds=3600): def decorator(func): cache = {} @functools.wraps(func) def wrapper(*args, **kwargs): key = str(args) + str(kwargs) if key in cache: result, timestamp = cache[key] if time.time() - timestamp < seconds: return result result = func(*args, **kwargs) cache[key] = (result, time.time()) return result return wrapper return decorator @timed_cache(seconds=300) def get_agent_info(agent_id): return api.get_agent(agent_id) ``` ### 4. Use Webhooks Instead of polling: ```python theme={null} # Don't do this while True: status = api.check_status() # Uses rate limit if status == "complete": break time.sleep(1) # Do this api.set_webhook("https://your-app.com/webhook") # Receive notification when complete ``` ## Rate Limit Increases Need higher limits? Options: 1. **Upgrade Plan**: Move to higher tier 2. **Request Increase**: Contact support for custom limits 3. **Enterprise Plan**: Fully customizable limits ## See Also * [Authentication](/api-reference/authentication) - API authentication * [Error Handling](/api-reference/errors) - Rate limit errors * [Best Practices](/resources/troubleshooting) - Optimization tips # Webhooks Source: https://docs.run-agent.ai/api-reference/webhooks Receive real-time notifications for agent events ## Overview Webhooks allow you to receive real-time notifications when events occur in your RunAgent deployment. Configure webhook endpoints to integrate with your systems. ## Webhook Events ### Execution Events | Event | Description | Payload | | ----------------- | ------------------------- | ------------------- | | `agent.invoked` | Agent invocation started | Request details | | `agent.completed` | Agent execution completed | Result and metadata | | `agent.failed` | Agent execution failed | Error details | | `agent.timeout` | Agent execution timed out | Timeout info | ### Deployment Events | Event | Description | Payload | | --------------------------- | ---------------------- | ---------------- | | `deployment.created` | New deployment created | Deployment info | | `deployment.updated` | Deployment updated | Changes | | `deployment.deleted` | Deployment removed | Deletion details | | `deployment.health_changed` | Health status changed | Status info | ## Webhook Configuration ### Via API ```bash theme={null} POST https://api.run-agent.ai/v1/webhooks Content-Type: application/json Authorization: Bearer YOUR_API_KEY { "url": "https://your-app.com/webhook", "events": ["agent.completed", "agent.failed"], "agent_id": "agent-123", "secret": "your-webhook-secret" } ``` ### Via Configuration ```json theme={null} { "webhooks": { "endpoints": [ { "url": "https://your-app.com/webhook", "events": ["agent.*"], "headers": { "X-Custom-Header": "value" } } ] } } ``` ## Webhook Payload ### Standard Structure ```json theme={null} { "id": "evt_abc123", "type": "agent.completed", "created": "2024-01-01T12:00:00Z", "data": { // Event-specific data }, "agent_id": "agent-123", "deployment_id": "dep-456" } ``` ### Event Examples #### agent.completed ```json theme={null} { "id": "evt_abc123", "type": "agent.completed", "created": "2024-01-01T12:00:00Z", "data": { "request_id": "req_xyz789", "input": { "query": "What's the weather?" }, "result": { "response": "The weather is sunny and 72°F" }, "execution_time": 1.23, "tokens_used": 150 }, "agent_id": "agent-123" } ``` #### agent.failed ```json theme={null} { "id": "evt_def456", "type": "agent.failed", "created": "2024-01-01T12:01:00Z", "data": { "request_id": "req_abc789", "error": { "code": "EXECUTION_ERROR", "message": "Agent processing failed", "details": "Model timeout" }, "input": { "query": "Complex request" } }, "agent_id": "agent-123" } ``` ## Webhook Security ### Signature Verification Verify webhook authenticity using HMAC-SHA256: ```python theme={null} import hmac import hashlib def verify_webhook(payload, signature, secret): expected = hmac.new( secret.encode(), payload.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) # In your webhook handler @app.post("/webhook") def handle_webhook(request): signature = request.headers.get("X-RunAgent-Signature") if not verify_webhook(request.body, signature, WEBHOOK_SECRET): return {"error": "Invalid signature"}, 401 # Process webhook data = request.json() process_event(data) ``` ### IP Whitelisting Webhook requests come from these IPs: * `52.89.214.238` * `34.212.75.30` * `54.218.53.128` ## Webhook Implementation ### Express.js Example ```javascript theme={null} const express = require('express'); const crypto = require('crypto'); app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => { const signature = req.headers['x-runagent-signature']; // Verify signature const expectedSignature = crypto .createHmac('sha256', process.env.WEBHOOK_SECRET) .update(req.body) .digest('hex'); if (signature !== expectedSignature) { return res.status(401).send('Unauthorized'); } // Process event const event = JSON.parse(req.body); switch(event.type) { case 'agent.completed': handleCompletion(event.data); break; case 'agent.failed': handleFailure(event.data); break; } res.status(200).send('OK'); }); ``` ### Django Example ```python theme={null} from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseBadRequest import json import hmac import hashlib @csrf_exempt def webhook_handler(request): if request.method != 'POST': return HttpResponseBadRequest('Method not allowed') # Verify signature signature = request.headers.get('X-RunAgent-Signature') expected = hmac.new( settings.WEBHOOK_SECRET.encode(), request.body, hashlib.sha256 ).hexdigest() if not hmac.compare_digest(signature, expected): return HttpResponse('Unauthorized', status=401) # Process event event = json.loads(request.body) if event['type'] == 'agent.completed': process_completion.delay(event['data']) # Celery task return HttpResponse('OK') ``` ## Retry Policy Failed webhook deliveries are retried with exponential backoff: 1. Immediate retry 2. After 1 minute 3. After 5 minutes 4. After 30 minutes 5. After 2 hours After 5 failed attempts, the webhook is marked as failed. ## Testing Webhooks ### Webhook Testing Tool ```bash theme={null} # Send test webhook runagent webhooks test --event agent.completed ``` ### Local Testing with ngrok ```bash theme={null} # Start local server python webhook_server.py # In another terminal ngrok http 8000 # Use ngrok URL for webhook https://abc123.ngrok.io/webhook ``` ## Monitoring Webhooks ### List Webhook Deliveries ```bash theme={null} GET https://api.run-agent.ai/v1/webhooks//deliveries ``` ### Webhook Metrics ```json theme={null} { "webhook_id": "wh_123", "total_deliveries": 1000, "successful": 950, "failed": 50, "average_response_time": 200, "last_delivery": "2024-01-01T12:00:00Z" } ``` ## Best Practices 1. **Respond Quickly**: Return 2xx status within 3 seconds 2. **Process Asynchronously**: Queue events for processing 3. **Implement Idempotency**: Handle duplicate events 4. **Verify Signatures**: Always verify webhook authenticity 5. **Monitor Failures**: Track and alert on webhook failures ## See Also * [Event Types](/api-reference/errors) - Complete event reference * [Security](/api-reference/authentication) - Security best practices * [Rate Limits](/api-reference/rate-limits) - Webhook rate limits # runagent local db Source: https://docs.run-agent.ai/cli/commands/db Deploy agent locally in your own sqlite database ## Description The `db` command group provides database management and monitoring capabilities for local agent deployments. It includes tools for viewing invocation history, analyzing performance metrics, and maintaining database health. ## Subcommands | Command | Description | | ------------- | ------------------------------------------ | | `status` | Show database status and agent information | | `invocations` | List agent invocation history | | `invocation` | View detailed invocation information | | `cleanup` | Clean up old database records | ## `runagent db status` Shows comprehensive database status including agent capacity, invocation statistics, and recent activity. ### Options | Option | Description | Default | | ---------------- | ---------------------------------- | ------- | | `--agent-id` | Show details for specific agent | None | | `--capacity` | Show detailed capacity information | `false` | | `--cleanup-days` | Clean up records older than N days | None | ### Examples ```bash theme={null} # Show general database status runagent db status # Show capacity management details runagent db status --capacity # Show agent-specific information runagent db status --agent-id abc123def456 ``` ## `runagent db invocations` Lists agent invocation history with filtering and formatting options. ### Options | Option | Description | Default | | ------------ | ------------------------------------------- | ------- | | `--agent-id` | Filter by specific agent | None | | `--status` | Filter by status (pending/completed/failed) | None | | `--limit` | Maximum number of results | `20` | | `--format` | Output format (table/json) | `table` | ### Examples ```bash theme={null} # Show recent invocations runagent db invocations # Filter by agent and status runagent db invocations --agent-id abc123 --status completed # Get JSON output for analysis runagent db invocations --format json --limit 50 ``` ## `runagent db invocation` Displays detailed information about a specific invocation including input/output data, timing, and error details. ### Arguments | Argument | Description | Required | | --------------- | ----------------------------- | -------- | | `invocation_id` | Full or partial invocation ID | Yes | ### Options | Option | Description | Default | | ---------- | -------------------------- | ------- | | `--format` | Output format (table/json) | `table` | ### Examples ```bash theme={null} # View invocation details runagent db invocation bb3c7a39-c582-4243-a913 # Get JSON output runagent db invocation bb3c7a39 --format json ``` ## `runagent db cleanup` Removes old database records to maintain performance and reduce storage usage. ### Options | Option | Description | Default | | -------------- | -------------------------------- | ------- | | `--days` | Remove records older than N days | `30` | | `--agent-runs` | Also clean old agent\_runs table | `false` | | `--yes` | Skip confirmation prompt | `false` | ### Examples ```bash theme={null} # Clean up records older than 30 days runagent db cleanup # Clean up records older than 7 days runagent db cleanup --days 7 # Clean up with no confirmation runagent db cleanup --days 14 --yes ``` ## Common Use Cases ### Monitor Agent Performance ```bash theme={null} # Check overall health runagent db status # View recent activity runagent db invocations --limit 10 # Check for errors runagent db invocations --status failed ``` ### Debug Failed Invocations ```bash theme={null} # Find failed invocations runagent db invocations --status failed # Get detailed error information runagent db invocation ``` ### Analyze Agent Usage ```bash theme={null} # View agent-specific metrics runagent db status --agent-id your_agent_id # Export data for analysis runagent db invocations --format json > invocations.json ``` ### Database Maintenance ```bash theme={null} # Check capacity status runagent db status --capacity # Clean up old records runagent db cleanup --days 30 --agent-runs ``` ## Database Schema The database tracks the following key information: * **Agents**: Deployed agent metadata and statistics * **Invocations**: Detailed execution records with timing and I/O data * **Agent Runs**: Legacy execution tracking (maintained for compatibility) Each invocation includes: * Unique invocation ID * Input/output data * Execution timing * Error details (if failed) * SDK type and client information ## Notes * All timestamps are in ISO format * JSON output can be piped to files for further analysis * Cleanup operations are irreversible - use with caution * Database is automatically created when first agent is deployed # runagent deploy Source: https://docs.run-agent.ai/cli/commands/deploy Deploy agent locally or to remote server (remote coming soon) ## Synopsis ```bash theme={null} runagent deploy [OPTIONS] [PATH] ``` ## Description The `deploy` command handles agent deployment workflows. Currently supports local deployment, with remote cloud deployment coming soon. **Note:** Remote deployment features require authentication and are coming soon. Local deployment is fully available through the `serve` command. ## Options | Option | Description | Default | | --------------- | ----------------------------------------------- | ----------------- | | `--folder` | Folder containing agent files | Current directory | | `--local`, `-l` | Deploy locally (redirects to serve) | `false` | | `--id` | Agent ID (for remote start only) | None | | `--framework` | Framework type (auto-detected if not specified) | Auto-detect | | `--config` | JSON configuration for deployment | None | ## Current Usage ### Local Deployment For local deployment, use the `serve` command directly: ```bash theme={null} # Start local development server (recommended) runagent serve . # Or use deploy with --local flag (redirects to serve) runagent deploy --folder . --local ``` The `--local` option internally calls the `serve` command with automatic: * Port allocation * Database management * Agent registration ## Coming Soon: Remote Deployment ### Remote Deployment Workflow (Coming Soon) ```bash theme={null} # Upload agent to remote server (Coming Soon) runagent upload --folder . # Start uploaded agent (Coming Soon) runagent start --id AGENT_ID # Full deployment workflow (Coming Soon) runagent deploy --folder . ``` ### Planned Remote Features ```bash theme={null} # Setup API credentials (Coming Soon) runagent setup --api-key your-api-key ``` ```bash theme={null} # Upload agent code (Coming Soon) runagent upload --folder . ``` ```bash theme={null} # Start on remote server (Coming Soon) runagent start --id AGENT_ID ``` ```bash theme={null} # Combined upload + start (Coming Soon) runagent deploy --folder . ``` ## Local Deployment Process (Available Now) Using `runagent serve` for local deployment: * Checks `runagent.config.json` * Validates entrypoints and framework * Verifies agent structure * Registers agent in local database * Allocates unique port automatically * Handles capacity management (5 agents max) * Starts FastAPI server * Configures endpoints * Enables real-time execution * Agent available at local endpoint * Can execute via Python SDK or CLI ## Examples ### Current Local Deployment ```bash theme={null} # Basic local deployment runagent serve . # With custom port runagent serve . --port 8080 # Replace existing agent runagent serve . --replace agent-id # With animation disabled runagent serve . --no-animation ``` ### Local Deployment via Deploy Command ```bash theme={null} # Local deployment (redirects to serve) runagent deploy --folder . --local # With framework specification runagent deploy --folder . --local --framework langgraph ``` ### Future Remote Examples (Coming Soon) ```bash theme={null} # Full remote deployment (Coming Soon) runagent deploy --folder . # With custom configuration (Coming Soon) runagent deploy --folder . --config '{"memory": "1GB", "timeout": 60}' # Deploy specific agent (Coming Soon) runagent deploy --id existing-agent-id ``` ## Output ### Local Deployment Output ``` 🚀 RunAgent Configuration: Agent ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890 Local: Yes Tag: main 🔌 Auto-allocated address: 127.0.0.1:8450 🌐 URL: http://127.0.0.1:8450 📖 Docs: http://127.0.0.1:8450/docs ✅ Agent started successfully! ``` ### Future Remote Deployment Output (Coming Soon) ``` Validating agent configuration... ✓ Uploading agent files... ✓ Starting remote deployment... ✓ Initializing endpoints... ✓ Deployment successful! Agent ID: 055b73d7-6239-4a94-a156-1193fcf33ff0 Status: Running Endpoint: https://api.run-agent.ai/agents/055b73d7 To test your agent: runagent run --id 055b73d7 --tag main --input '{"query": "test"}' ``` ## Local Database Management Local deployments are managed through a SQLite database: ```bash theme={null} # Check local agent status runagent db-status # View capacity information runagent db-status --capacity # Delete local agent runagent delete --id agent-id ``` **Capacity Limits:** * Maximum 5 agents simultaneously * Automatic port allocation (8450-8454) * Replace oldest agent when at capacity ## Configuration ### Agent Configuration In `runagent.config.json`: ```json theme={null} { "agent_name": "my-agent", "description": "My awesome agent", "framework": "langgraph", "template": "basic", "version": "1.0.0", "agent_architecture": { "entrypoints": [ { "file": "main.py", "module": "agent", "tag": "main" } ] } } ``` ### Future Remote Configuration (Coming Soon) ```json theme={null} { "deployment": { "memory": "512MB", "timeout": 30, "min_instances": 1, "max_instances": 10, "environment_variables": { "LOG_LEVEL": "INFO" } } } ``` ## Validation Checks Before deployment, RunAgent validates: * Configuration file exists and is valid JSON * Required fields are present in config * Entrypoint files exist * Framework is supported * Agent structure is valid * No syntax errors in configuration ## Error Handling ### Common Local Deployment Errors ```bash theme={null} # Database at capacity ❌ Database is full! 💡 Suggested commands: Replace: runagent serve . --replace oldest-agent-id Delete: runagent delete --id agent-id # Port already in use 🔌 Auto-allocated address: 127.0.0.1:8451 # Invalid configuration ❌ Validation error: Missing required field 'agent_name' ``` ## Troubleshooting ```bash theme={null} # Check database status runagent db-status # Check specific agent runagent db-status --agent-id AGENT_ID # Clean up old agents runagent delete --id AGENT_ID ``` ```bash theme={null} # Validate agent structure runagent serve . --verbose # Check configuration cat runagent.config.json | jq . ``` Local deployment automatically handles port allocation: * Starts from port 8450 * Increments if port is busy * Maximum 5 agents (ports 8450-8454) ## Best Practices 1. **Test with Serve**: Always use `runagent serve` for local development 2. **Monitor Capacity**: Check `runagent db-status --capacity` regularly 3. **Clean Up**: Remove unused agents with `runagent delete` 4. **Version Control**: Keep `runagent.config.json` in version control 5. **Environment Setup**: Configure `.env` files properly ## Migration Guide ### Current Workflow ```bash theme={null} # 1. Create agent runagent init my-agent --framework langgraph # 2. Develop locally runagent serve . # 3. Test execution runagent run --id agent-id --tag main --local ``` ### Future Remote Workflow (Coming Soon) ```bash theme={null} # 1. Setup authentication runagent setup --api-key your-key # 2. Deploy remotely runagent deploy --folder . # 3. Test execution runagent run --id agent-id --tag main ``` ## See Also * [`runagent serve`](/cli/commands/serve) - Local development server (recommended) * [`runagent upload`](/cli/commands/upload) - Upload agent to remote (coming soon) * [`runagent start`](/cli/commands/start) - Start remote agent (coming soon) * [`runagent db-status`](/cli/commands/db-status) - Check local database * [`runagent run`](/cli/commands/run) - Execute agents # runagent init Source: https://docs.run-agent.ai/cli/commands/init Initialize a new RunAgent project ## Synopsis ```bash theme={null} runagent init [PROJECT_NAME] [OPTIONS] ``` ## Description The `init` command creates a new RunAgent project with a pre-configured structure and optional template. ## Options | Option | Description | Default | | ------------------- | ------------------------------ | ------------------ | | `--framework`, `-f` | AI framework to use | `langgraph` | | `--template`, `-t` | Project template | Based on framework | | `--path`, `-p` | Directory to create project in | Current directory | | `--no-git` | Skip git initialization | `false` | ## Examples ### Basic Usage ```bash theme={null} # Create a new project runagent init my-agent # Create with specific framework runagent init my-agent --framework crewai # Use a specific template runagent init my-agent --template chatbot ``` ### Advanced Usage ```bash theme={null} # Create in specific directory runagent init my-agent --path ~/projects # Skip git initialization runagent init my-agent --no-git # Interactive mode runagent init ``` ## Project Structure The command creates: ``` my-agent/ ├── agent.py # Main agent code ├── runagent.config.json # Configuration ├── requirements.txt # Dependencies ├── .env.example # Environment template ├── .gitignore # Git ignore rules └── README.md # Project documentation ``` ## Templates Available templates by framework: * `problem-solver` - Multi-step reasoning * `chatbot` - Conversational agent * `researcher` - Web research agent * `crew-basic` - Simple crew setup * `research-crew` - Research team * `dev-crew` - Development team * `minimal` - Bare minimum setup * `api-agent` - REST API integration * `tool-agent` - Multi-tool agent ## Interactive Mode When run without arguments, enters interactive mode: ```bash theme={null} $ runagent init ? Project name: my-awesome-agent ? Select framework: ❯ langgraph crewai agno letta custom ? Choose a template: ❯ problem-solver chatbot minimal ? Initialize git repository? (Y/n) ``` ## Post-Initialization After creating a project: ```bash theme={null} cd my-agent pip install -r requirements.txt cp .env.example .env # Edit .env with your API keys runagent serve . ``` ## See Also * [`runagent template`](/cli/commands/template) - Manage templates * [`runagent serve`](/cli/commands/serve) - Test locally # runagent run Source: https://docs.run-agent.ai/cli/commands/run Run a deployed agent ## Synopsis ```bash theme={null} runagent run [AGENT_ID] [OPTIONS] ``` ## Description Execute a deployed agent with input data and receive the response. ## Options | Option | Description | Default | | -------------------- | ----------------------- | -------- | | `--input`, `-i` | JSON input data | Required | | `--input-file`, `-f` | Read input from file | - | | `--output`, `-o` | Output file path | stdout | | `--stream` | Enable streaming output | false | ## Examples ### Basic Usage ```bash theme={null} # Run with inline input runagent run agent-123 --input '{"query": "Hello"}' # Run with file input runagent run agent-123 --input-file request.json # Save output to file runagent run agent-123 --input '{"query": "Test"}' --output result.json ``` ### Streaming ```bash theme={null} # Stream responses runagent run agent-123 --input '{"query": "Tell me a story"}' --stream ``` ## Input Format The input must be valid JSON: ```json theme={null} { "query": "Your question here", "parameters": { "temperature": 0.7, "max_tokens": 150 } } ``` ## Response Format The CLI and SDK now return a minimal payload when the execution completes: ```json theme={null} { "success": true, "data": "{\"type\": \"string\", \"payload\": \"...\"}", "message": "Agent execution completed successfully", "error": null, "timestamp": "2025-11-12T22:23:35.216480", "request_id": "adffa696-6273-4c5b-a933-883d830fd72c" } ``` * `data` contains the agent output encoded with `serialize_object_to_structured`, so the CLI/SDK can deterministically decode every result type. * Full execution metadata (runtime, VM, invocation ID, etc.) remains available through the local invocation history endpoints and the RunAgent dashboard/middleware. Error responses keep the same envelope but include an `error` object with diagnostic fields. ## See Also * [`runagent deploy`](/cli/commands/deploy) - Deploy an agent first * [`runagent status`](/cli/commands/status) - Check agent status # runagent serve Source: https://docs.run-agent.ai/cli/commands/serve Start local FastAPI server with automatic agent deployment and database management ## Synopsis ```bash theme={null} runagent serve [PATH] [OPTIONS] ``` ## Description The `serve` command starts a local FastAPI server that automatically deploys your agent with database persistence, port allocation, and capacity management. It's the primary command for local development and testing. ## Options | Option | Description | Default | | ------------------- | ---------------------------------------------- | -------------- | | `--port`, `-p` | Preferred port (auto-allocated if unavailable) | Auto-allocated | | `--host`, `-h` | Host to bind server to | `127.0.0.1` | | `--debug` | Run server in debug mode | `false` | | `--replace` | Replace existing agent with this agent ID | None | | `--no-animation` | Skip startup animation | `false` | | `--animation-style` | Animation style (field, ascii, minimal, quick) | `field` | ## Auto Port Allocation The serve command automatically allocates ports starting from **8450**: * **Port Range**: 8450-8454 (supports up to 5 agents) * **Automatic Detection**: Finds next available port if preferred port is busy * **Conflict Resolution**: Never conflicts with existing agents ```bash theme={null} # Uses auto-allocated port runagent serve . # Output: 🔌 Auto-allocated address: 127.0.0.1:8450 # Prefers specific port, falls back to auto-allocation runagent serve . --port 8080 # Output: Using specified address: 127.0.0.1:8080 ``` ## Database Integration Each `serve` command automatically: * **Registers agent** in local SQLite database * **Manages capacity** (maximum 5 agents) * **Persists deployments** between restarts * **Tracks usage statistics** ### Capacity Management ```bash theme={null} # Check current capacity runagent db-status --capacity # Replace oldest agent when at capacity runagent serve . --replace oldest-agent-id # Delete existing agent to free space runagent delete --id agent-id ``` ## Examples ### Basic Usage ```bash theme={null} # Serve current directory with auto port allocation runagent serve . # Serve specific project runagent serve ~/projects/my-agent # Use preferred port runagent serve . --port 8080 ``` ### Advanced Usage ```bash theme={null} # Replace existing agent runagent serve . --replace a1b2c3d4-e5f6-7890 # Debug mode with verbose output runagent serve . --debug # Skip startup animation runagent serve . --no-animation # Quick startup animation runagent serve . --animation-style quick ``` ## Startup Process The serve command follows this process: Displays robotic runner animation (customizable with `--animation-style`) Verifies database capacity (5 agents max) or handles replacement Registers agent in database with unique ID and allocated port Starts FastAPI server with automatic configuration ## Available Endpoints Once running, your agent exposes these REST and WebSocket endpoints: ### REST Endpoints | Endpoint | Method | Description | | ------------------------------------- | ------ | ----------------------------- | | `/` | GET | Agent information and status | | `/health` | GET | Health check | | `/api/v1/agents/{agent_id}/run/{tag}` | POST | Execute agent entrypoint | | `/docs` | GET | Interactive API documentation | | `/redoc` | GET | Alternative API documentation | ### WebSocket Endpoints | Endpoint | Protocol | Description | | ---------------------------------------- | --------- | ---------------------- | | `/api/v1/agents/{agent_id}/stream/{tag}` | WebSocket | Stream agent responses | ## Testing Your Agent ### Health Check ```bash theme={null} curl http://localhost:8450/health ``` ### Execute Agent ```bash theme={null} curl -X POST http://localhost:8450/api/v1/agents/{agent_id}/run/main \ -H "Content-Type: application/json" \ -d '{ "input_data": { "input_args": [], "input_kwargs": {"query": "Hello, agent!"} } }' ``` ### Using Python SDK ```python theme={null} from runagent import RunAgentClient # Connect to local agent client = RunAgentClient( agent_id="your-agent-id", entrypoint_tag="main", local=True ) # Execute agent result = client.run(query="Hello, agent!") print(result) ``` ### Using CLI ```bash theme={null} # Execute local agent runagent run --id agent-id --tag main --local --query="Hello" ``` ## Output Information ### Successful Startup ``` 🚀 Starting local server with auto port allocation... 🔌 Auto-allocated address: 127.0.0.1:8450 🌐 URL: http://127.0.0.1:8450 📖 Docs: http://127.0.0.1:8450/docs ✅ Agent started successfully! 🆔 Agent ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890 📊 Capacity: 1/5 slots used ``` ### Capacity Warning ``` ❌ Database is full! 💡 Suggested commands: Replace: runagent serve . --replace oldest-agent-id Delete: runagent delete --id agent-id ``` ### Replacement Success ``` 🔄 Replacing agent: old-agent-id ✅ Agent replaced successfully! 🆔 New Agent ID: new-agent-id 🔌 Address: 127.0.0.1:8451 ``` ## Agent Configuration The serve command reads from `runagent.config.json`: ```json theme={null} { "agent_name": "my-agent", "description": "My awesome agent", "framework": "langgraph", "template": "basic", "version": "1.0.0", "agent_architecture": { "entrypoints": [ { "file": "main.py", "module": "agent", "tag": "main" }, { "file": "main.py", "module": "agent_stream", "tag": "main_stream" } ] } } ``` ## Development Features ### Automatic Framework Detection ```bash theme={null} # Automatically detects framework from config runagent serve . # Output: Framework: langgraph ``` ### Database Persistence * Agent registrations persist between restarts * Usage statistics are tracked * Port allocations are remembered ### Error Handling Clear error messages for common issues: ```bash theme={null} # Missing configuration ❌ Validation error: No config file found # Invalid entrypoint ❌ Validation error: Module 'agent' not found in main.py # Capacity exceeded ❌ Database at capacity. Use --replace or 'runagent delete' ``` ## Integration with Other Commands ### Database Management ```bash theme={null} # Check all local agents runagent db-status # View specific agent details runagent db-status --agent-id your-agent-id # Clean up agents runagent delete --id agent-id ``` ### Execution ```bash theme={null} # Run agent locally runagent run --id agent-id --tag main --local # Use host/port directly runagent run --host 127.0.0.1 --port 8450 --tag main ``` ## Animation Styles Customize the startup animation: ```bash theme={null} # Default robotic runner in field runagent serve . # ASCII art version runagent serve . --animation-style ascii # Minimal clean version runagent serve . --animation-style minimal # Quick startup runagent serve . --animation-style quick # No animation runagent serve . --no-animation ``` ## Troubleshooting ```bash theme={null} # Check current capacity runagent db-status --capacity # View all agents by age runagent db-status # Replace oldest agent runagent serve . --replace oldest-agent-id # Delete unused agents runagent delete --id agent-id ``` The serve command handles port conflicts automatically: * Starts from port 8450 * Increments if port is busy * Shows allocated address in output * Maximum 5 agents (ports 8450-8454) ```bash theme={null} # Validate configuration runagent serve . --debug # Check config file cat runagent.config.json | jq . # Verify framework detection runagent serve . --verbose ``` ```bash theme={null} # Check entrypoint files exist ls -la main.py # Verify dependencies pip install -r requirements.txt # Test import manually python -c "from main import agent" ``` ## Best Practices 1. **Monitor Capacity**: Regularly check `runagent db-status --capacity` 2. **Clean Up**: Remove unused agents to free database slots 3. **Use Replace**: When at capacity, replace oldest agents rather than failing 4. **Test Locally**: Always test with `serve` before remote deployment 5. **Version Control**: Keep `runagent.config.json` in version control ## Performance Notes * **Single Process**: Each agent runs in a single FastAPI process * **Port Per Agent**: Each agent gets its own port for isolation * **Database Tracking**: Minimal overhead for registration and tracking * **Auto Cleanup**: Detect and handle stale agent registrations ## See Also * [`runagent run`](/cli/commands/run) - Execute deployed agents * [`runagent db-status`](/cli/commands/db-status) - Check database status * [`runagent delete`](/cli/commands/delete) - Remove agents * [`runagent deploy`](/cli/commands/deploy) - Remote deployment (coming soon) * [`runagent logs`](/cli/commands/logs) - View logs (coming soon) # runagent setup (Coming Soon) Source: https://docs.run-agent.ai/cli/commands/setup Setup RunAgent authentication ## Synopsis ```bash theme={null} runagent setup [OPTIONS] ``` ## Description Configure RunAgent authentication and global settings. Creates a configuration file for persistent authentication. ## Options | Option | Description | Default | | --------------- | -------------------------------- | ---------------------------------------------------- | | `--api-key` | API key (prompt if not provided) | - | | `--api-url` | Custom API endpoint | [https://api.run-agent.ai](https://api.run-agent.ai) | | `--config-path` | Config file location | \~/.runagent/config.json | ## Examples ```bash theme={null} # Interactive setup runagent setup # Non-interactive with API key runagent setup --api-key your-api-key-here # Custom API endpoint runagent setup --api-url https://custom.run-agent.ai ``` ## Interactive Setup ``` $ runagent setup Welcome to RunAgent setup! Enter your API key: ******** API endpoint [https://api.run-agent.ai]: Save configuration? [Y/n]: Y Configuration saved to ~/.runagent/config.json Setup complete! You can now use RunAgent. ``` ## Configuration File Creates `~/.runagent/config.json`: ```json theme={null} { "api_key": "your-api-key", "api_url": "https://api.run-agent.ai", "user_id": "user_123", "created_at": "2024-01-01T00:00:00Z" } ``` ## Security * API keys are stored locally * File permissions set to 600 (user read/write only) * Never commit config files to version control ## See Also * [`runagent teardown`](/cli/commands/teardown) - Remove configuration # runagent start (Coming Soon) Source: https://docs.run-agent.ai/cli/commands/start Start an uploaded agent on remote server ## Synopsis ```bash theme={null} runagent start [UPLOAD_ID] [OPTIONS] ``` ## Description Start a previously uploaded agent on RunAgent infrastructure. ## Options | Option | Description | Default | | ------------- | ------------------- | ---------- | | `--env`, `-e` | Environment name | production | | `--instances` | Number of instances | 1 | | `--wait` | Wait for startup | true | ## Examples ```bash theme={null} # Start uploaded agent runagent start upload_abc123 # Start with multiple instances runagent start upload_abc123 --instances 3 # Start in staging environment runagent start upload_abc123 --env staging # Start without waiting runagent start upload_abc123 --no-wait ``` ## Startup Process 1. Allocates resources 2. Initializes container 3. Loads environment variables 4. Starts agent process 5. Runs health checks ## Output ``` Starting agent upload_abc123... Allocating resources... ✓ Initializing container... ✓ Loading environment... ✓ Starting agent... ✓ Health check... ✓ Agent started successfully! Agent ID: agent-xyz789 Status: Running Endpoint: https://api.run-agent.ai/agents/xyz789 ``` ## See Also * [`runagent upload`](/cli/commands/upload) - Upload agent first * [`runagent status`](/cli/commands/status) - Check running status # runagent teardown (Coming Soon) Source: https://docs.run-agent.ai/cli/commands/teardown Remove RunAgent configuration ## Synopsis ```bash theme={null} runagent teardown [OPTIONS] ``` ## Description Remove RunAgent configuration and authentication data from your system. ## Options | Option | Description | Default | | --------------- | ------------------------ | ------- | | `--force`, `-f` | Skip confirmation | false | | `--all` | Remove all RunAgent data | false | ## Examples ```bash theme={null} # Remove configuration (with confirmation) runagent teardown # Force removal without confirmation runagent teardown --force # Remove all RunAgent data runagent teardown --all ``` ## What Gets Removed Standard teardown removes: * `~/.runagent/config.json` * Authentication tokens * Cached credentials With `--all` flag, also removes: * Local deployment data * Log files * Temporary files ## Interactive Confirmation ``` $ runagent teardown This will remove RunAgent configuration from your system. Are you sure? [y/N]: y Removing configuration... ✓ Clearing credentials... ✓ RunAgent configuration removed. ``` ## See Also * [`runagent setup`](/cli/commands/setup) - Set up configuration again # runagent template Source: https://docs.run-agent.ai/cli/commands/template Manage project templates ## Synopsis ```bash theme={null} runagent template [COMMAND] [OPTIONS] ``` ## Description Manage RunAgent project templates. List, preview, and update available templates. ## Commands | Command | Description | | -------- | ---------------------------------- | | `list` | List all available templates | | `info` | Show template details | | `update` | Update templates to latest version | | `create` | Create custom template | ## Examples ### List Templates ```bash theme={null} runagent template list Available templates: langgraph: - problem-solver: Multi-step reasoning agent - chatbot: Conversational AI assistant - researcher: Web research agent crewai: - crew-basic: Simple crew setup - research-crew: Research team custom: - minimal: Bare minimum setup - api-agent: REST API integration ``` ### Template Info ```bash theme={null} runagent template info problem-solver Template: problem-solver Framework: langgraph Description: Multi-step reasoning agent with tool use Author: runagent-dev Updated: 2024-01-15 Size: 2.3 KB Files: - agent.py - tools.py - prompts.py - runagent.config.json - requirements.txt ``` ### Update Templates ```bash theme={null} runagent template update Checking for updates... Updated templates: - problem-solver (v1.0.1 → v1.0.2) - chatbot (v2.0.0 → v2.1.0) Templates updated successfully! ``` ## See Also * [`runagent init`](/cli/commands/init) - Create project from template # runagent upload (Coming Soon) Source: https://docs.run-agent.ai/cli/commands/upload Upload agent to remote server ## Synopsis ```bash theme={null} runagent upload [PATH] [OPTIONS] ``` ## Description Upload your agent code to RunAgent servers without starting it. Useful for preparing deployments or updating code. ## Options | Option | Description | Default | | ------------------- | ---------------------- | ----------- | | `--name`, `-n` | Agent name | From config | | `--skip-validation` | Skip validation checks | false | | `--compress` | Compress before upload | true | ## Examples ```bash theme={null} # Upload current directory runagent upload . # Upload with custom name runagent upload . --name staging-agent # Upload without validation runagent upload . --skip-validation ``` ## Upload Process 1. Validates configuration 2. Packages agent files 3. Compresses (if enabled) 4. Uploads to server 5. Returns upload ID ## Output ``` Validating agent... ✓ Packaging files... ✓ Compressing... ✓ Uploading... ✓ Upload successful! Upload ID: upload_abc123 Size: 2.3 MB Next steps: runagent start upload_abc123 ``` ## See Also * [`runagent start`](/cli/commands/start) - Start uploaded agent * [`runagent deploy`](/cli/commands/deploy) - Upload and start in one command # CLI Examples Source: https://docs.run-agent.ai/cli/examples Common RunAgent CLI usage patterns and workflows ## Common Workflows ### Complete Development Workflow ```bash theme={null} # 1. Create new project runagent init chatbot-agent --framework langgraph # 2. Navigate to project cd chatbot-agent # 3. Install dependencies pip install -r requirements.txt # 4. Set up environment cp .env.example .env # Edit .env with your API keys # 5. Test locally runagent serve . # 6. In another terminal, test the agent curl -X POST http://localhost:8000/invoke \ -H "Content-Type: application/json" \ -d '{"query": "Hello!"}' # 7. Deploy when ready runagent deploy . --local ``` ### Template Management ```bash theme={null} # List all available templates runagent template list # Get details about a template runagent template info problem-solver # Create project from specific template runagent init my-solver --template problem-solver # Update template to latest version runagent template update problem-solver ``` ### Debugging and Development ```bash theme={null} # Run with debug logging runagent serve . --log-level debug # Test specific entrypoint runagent serve . --entrypoint app.process_query # Run with environment overrides OPENAI_API_KEY=sk-test-key runagent serve . # Check configuration validity runagent validate . ``` ### Deployment Management ```bash theme={null} # Deploy with specific name runagent deploy . --name production-chatbot # List all deployments runagent list # Get deployment details runagent status 055b73d7-6239-4a94 # Stream logs from deployment runagent logs 055b73d7-6239-4a94 --follow # Delete deployment runagent delete 055b73d7-6239-4a94 ``` ## Use Case Examples ### Building a Customer Support Bot ```bash theme={null} # Initialize project runagent init support-bot --framework langgraph # Add custom dependencies cd support-bot echo "pandas>=2.0.0" >> requirements.txt echo "sqlalchemy>=2.0.0" >> requirements.txt # Test with sample data cat > test_input.json << EOF { "query": "I need help with my order #12345", "user_id": "user_789", "context": "customer_support" } EOF runagent serve . curl -X POST http://localhost:8000/invoke \ -H "Content-Type: application/json" \ -d @test_input.json ``` ### Creating a Multi-Agent System ```bash theme={null} # Initialize CrewAI project runagent init research-crew --framework crewai # Deploy the crew runagent deploy research-crew/ --local # Run the crew with complex input runagent run --input '{ "task": "Research AI trends in 2024", "agents": ["researcher", "analyst", "writer"], "output_format": "report" }' ``` ### Batch Processing Pipeline ```bash theme={null} # Create batch processor runagent init batch-processor --template data-processor # Process multiple files for file in data/*.json; do runagent run \ --input-file "$file" \ --output "results/$(basename $file)" done # Or use parallel processing ls data/*.json | parallel -j 4 \ 'runagent run --input-file {} --output results/{/}' ``` ## Advanced Patterns ### CI/CD Integration ```yaml theme={null} # .github/workflows/deploy.yml name: Deploy Agent on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v4 with: python-version: '3.9' - name: Install RunAgent run: pip install runagent - name: Deploy env: RUNAGENT_API_KEY: ${{ secrets.RUNAGENT_API_KEY }} run: | runagent deploy . --env production ``` ### Environment Management ```bash theme={null} # Development environment runagent serve . --env development # Staging deployment runagent deploy . --env staging --name staging-agent # Production deployment with specific config RUNAGENT_ENV=production runagent deploy . ``` ### Monitoring and Alerting ```bash theme={null} # Watch logs with filtering runagent logs --follow --filter "ERROR" # Export logs for analysis runagent logs --format json > agent.log # Check health status watch -n 5 'runagent status --format json | jq .health' # Simple alerting script #!/bin/bash while true; do STATUS=$(runagent status --format json | jq -r .status) if [ "$STATUS" != "running" ]; then echo "Agent down! Status: $STATUS" | mail -s "Agent Alert" ops@company.com fi sleep 60 done ``` ## Troubleshooting Commands ### Diagnostic Commands ```bash theme={null} # Check RunAgent installation runagent doctor # Validate project structure runagent validate . --verbose # Test agent imports runagent test-import . # Check API connectivity runagent ping ``` ### Recovery Commands ```bash theme={null} # Force stop local agent runagent stop --force # Clean up orphaned processes runagent cleanup # Reset local configuration runagent teardown && runagent setup # Rebuild deployment runagent rebuild ``` ## Tips and Tricks ### Shell Aliases Add to your `.bashrc` or `.zshrc`: ```bash theme={null} # Quick shortcuts alias ra='runagent' alias ras='runagent serve .' alias rad='runagent deploy .' alias ral='runagent logs' alias rat='runagent template' # Project creation function new-agent() { runagent init "$1" ${@:2} && cd "$1" && code . } # Quick test function test-agent() { curl -X POST http://localhost:8000/invoke \ -H "Content-Type: application/json" \ -d "$1" } ``` ### JSON Output Processing ```bash theme={null} # Pretty print JSON output runagent list --json | jq . # Extract specific fields runagent status --json | jq '.deployment.created_at' # Filter deployments runagent list --json | jq '.deployments[] | select(.status=="running")' ``` ### Batch Operations ```bash theme={null} # Stop all local deployments runagent list --local --json | \ jq -r '.deployments[].id' | \ xargs -I {} runagent stop {} # Export all configurations for id in $(runagent list --json | jq -r '.deployments[].id'); do runagent export $id > "backup/$id.json" done ``` ## See Also * [CLI Overview](/cli/overview) - Complete command reference * [Configuration Guide](/configuration/config-file) - Project configuration * [Deployment Guide](/deployment/local-development) - Deployment strategies # CLI Overview Source: https://docs.run-agent.ai/cli/overview Master the RunAgent command-line interface The RunAgent CLI is your primary tool for creating, testing, and deploying AI agents. It provides a simple yet powerful interface for managing the entire agent lifecycle. ## Installation ```bash theme={null} pip install runagent ``` Verify installation: ```bash theme={null} runagent --version ``` ## Global Options All RunAgent commands support these global options: | Option | Description | | ----------- | -------------------------- | | `--help` | Show help message and exit | | `--version` | Display RunAgent version | | `--verbose` | Enable verbose output | | `--quiet` | Suppress non-error output | ## Available Commands Configure authentication and API keys (Coming Soon) Remove RunAgent configuration (Coming Soon) Initialize a new agent project Manage project templates Run agent locally for testing Upload agent to remote server (Coming Soon) Start uploaded agent on remote server (Coming Soon) Full deployment (upload + start) or local deploy Execute a deployed agent Show local database status and statistics Delete an agent from local database ## Command Structure RunAgent follows a consistent command structure: ```bash theme={null} runagent [GLOBAL_OPTIONS] COMMAND [COMMAND_OPTIONS] [ARGUMENTS] ``` Examples: ```bash theme={null} runagent init my-agent --framework langgraph runagent serve . --port 8080 runagent run --id agent-id --tag main --input '{"query": "Hello"}' ``` *Note: Authentication and remote deployment commands are coming soon* ## Command Categories ### **Setup & Configuration** (Authentication Coming Soon) * `setup` - Configure authentication with API keys (Coming Soon) * `teardown` - Remove all RunAgent configuration (Coming Soon) * `db-status` - Monitor local database and capacity ### **Project Management** * `init` - Create new agent projects from templates * `template` - List and manage available templates ### **Local Development** * `serve` - Start local FastAPI server for testing and deployment * `delete` - Remove agents from local database ### **Remote Deployment** (Coming Soon) * `upload` - Upload agent code to remote server * `start` - Start uploaded agent on remote server * `deploy` - Full deployment workflow (upload + start) ### **Execution** * `run` - Execute deployed agents with flexible input options ## Common Workflows ### Development Workflow ```bash theme={null} runagent setup --api-key your-api-key ``` *Note: Authentication features are coming soon* ```bash theme={null} runagent init my-agent --framework langgraph cd my-agent ``` ```bash theme={null} pip install -r requirements.txt ``` ```bash theme={null} cp .env.example .env # Edit .env with your API keys ``` ```bash theme={null} runagent serve . ``` ```bash theme={null} runagent deploy . ``` *Note: Remote deployment features are coming soon* ### Quick Commands Reference ```bash theme={null} # Initial setup (Coming Soon) runagent setup --api-key your-key # Check configuration status runagent db-status --capacity # Remove configuration (Coming Soon) runagent teardown ``` *Note: Authentication features are coming soon* ```bash theme={null} # Create new project runagent init PROJECT_NAME # List available templates runagent template --list # Create from specific template runagent init PROJECT_NAME --langgraph --template advanced # Interactive mode runagent init --interactive ``` ```bash theme={null} # Start local server (automatically deploys with port allocation) runagent serve . # Use custom port runagent serve . --port 8080 # Replace existing agent runagent serve . --replace agent-id # Check database status runagent db-status ``` ```bash theme={null} # Upload agent (Coming Soon) runagent upload --folder . # Start uploaded agent (Coming Soon) runagent start --id AGENT_ID # Full deployment (upload + start) (Coming Soon) runagent deploy --folder . # Deploy locally with serve command runagent serve . ``` *Note: Remote deployment features are coming soon* ```bash theme={null} # Run agent with parameters runagent run --id AGENT_ID --tag main --param1=value1 --param2=value2 # Run with input file runagent run --id AGENT_ID --tag main --input config.json # Run locally runagent run --id AGENT_ID --tag main --local # Run with host/port runagent run --host localhost --port 8080 --tag main ``` ```bash theme={null} # List local agents runagent db-status # Check capacity runagent db-status --capacity # Delete agent runagent delete --id AGENT_ID # Get agent details runagent db-status --agent-id AGENT_ID ``` ## Configuration Management ### Authentication Setup (Coming Soon) ```bash theme={null} # Setup with API key (Coming Soon) runagent setup --api-key your-api-key # Setup with custom base URL (Coming Soon) runagent setup --api-key your-key --base-url https://custom-api.com # Force reconfiguration (Coming Soon) runagent setup --api-key new-key --force # Remove all configuration (Coming Soon) runagent teardown ``` *Note: Authentication and remote deployment features are coming soon.* The setup command will create a configuration file at: * Linux/Mac: `~/.runagent/user_data.json` * Windows: `%USERPROFILE%\.runagent\user_data.json` ### Environment Variables (Coming Soon) RunAgent CLI will support these environment variables: | Variable | Description | | -------------------- | ------------------------------------------- | | `RUNAGENT_API_KEY` | API key for authentication (Coming Soon) | | `RUNAGENT_BASE_URL` | Custom API endpoint (Coming Soon) | | `RUNAGENT_CACHE_DIR` | Custom cache directory location | | `RUNAGENT_LOG_LEVEL` | Logging level (DEBUG, INFO, WARNING, ERROR) | *Note: Authentication-related environment variables are coming soon.* ## Local Database Management RunAgent maintains a local SQLite database for managing agents: ```bash theme={null} # View database status runagent db-status # Check capacity (5 agents max) runagent db-status --capacity # View specific agent runagent db-status --agent-id AGENT_ID # Delete agent runagent delete --id AGENT_ID # Clean up old records runagent db-status --cleanup-days 30 ``` ### Capacity Management The local database supports up to **5 agents** simultaneously. When at capacity: ```bash theme={null} # Replace oldest agent runagent serve . --replace OLDEST_AGENT_ID # Or delete an agent first runagent delete --id AGENT_ID ``` ## Output Formats Most commands support different output formats: ```bash theme={null} # Default human-readable output runagent template --list # JSON output for scripting runagent template --list --format json # Minimal output runagent serve . --quiet ``` ## Error Handling RunAgent provides clear error messages: ```bash theme={null} $ runagent serve nonexistent Error: Directory 'nonexistent' does not exist $ runagent run --id invalid-id --tag main Error: Agent 'invalid-id' not found ``` ### Common Exit Codes | Code | Meaning | | ---- | ------------------------ | | 0 | Success | | 1 | General error | | 2 | Command line usage error | | 3 | Configuration error | | 4 | Network/API error | | 5 | Authentication error | ## Advanced Usage ### Animation Control ```bash theme={null} # Skip startup animation runagent serve . --no-animation # Use different animation style runagent serve . --animation-style quick runagent serve . --animation-style minimal ``` ### Debugging Enable verbose output for troubleshooting: ```bash theme={null} # Verbose mode runagent --verbose serve . # Debug logging RUNAGENT_LOG_LEVEL=DEBUG runagent serve . # Check configuration status runagent db-status --capacity ``` ### Piping and Scripting ```bash theme={null} # Pipe input from file cat input.json | runagent run --id AGENT_ID --tag main --input - # Use in scripts if runagent db-status --capacity; then echo "Database has available slots" else echo "Database is at capacity" exit 1 fi ``` ### Aliases and Shortcuts Add to your shell configuration: ```bash theme={null} # ~/.bashrc or ~/.zshrc alias ra='runagent' alias ras='runagent serve .' alias rad='runagent deploy .' alias radb='runagent db-status' # Function for quick agent creation new-agent() { runagent init "$1" --framework langgraph && cd "$1" } ``` ## Best Practices Always commit your `runagent.config.json` but never commit `.env` files containing API keys Use `runagent serve` and `runagent deploy-local` to test locally before deploying remotely Use `runagent db-status --capacity` to monitor local database usage Start with templates for faster development: `runagent template --list` Use the CLI in CI/CD pipelines for automated deployments ## Getting Help ```bash theme={null} # General help runagent --help # Command-specific help runagent init --help runagent serve --help runagent run --help # Check version runagent --version # View configuration status runagent db-status --capacity ``` Join our [Discord community](https://discord.gg/runagent) for support and discussions about RunAgent CLI * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Configuration File Source: https://docs.run-agent.ai/configuration/config-file Understanding runagent.config.json The `runagent.config.json` file is the heart of your RunAgent project. It defines how your agent is configured, deployed, and executed. ## Basic Structure ```json theme={null} { "agent_name": "problem_solver", "description": "A simple agent that responds to basic queries", "framework": "langgraph", "template": "problem_solver", "version": "1.0.0", "created_at": "2025-06-25 13:42:03", "template_source": { "repo_url": "https://github.com/runagent-dev/runagent.git", "path": "templates/langgraph/problem_solver", "author": "sawradip" }, "agent_architecture": { "entrypoints": [ { "file": "agents.py", "module": "app.invoke", "type": "generic" }, { "file": "agents.py", "module": "app.stream", "type": "generic_stream" } ] }, "env_vars": { "OPENAI_API_KEY": "${OPENAI_API_KEY}", "CUSTOM_VAR": "fixed_value" } } ``` ## Configuration Fields ### Core Fields Unique identifier for your agent. Used in deployment and SDK initialization. * Must be lowercase * Can contain letters, numbers, hyphens, and underscores * Maximum 50 characters Human-readable description of what your agent does. Displayed in dashboards and listings. The AI framework your agent uses. Supported values: * `langgraph` * `crewai` * `agno` * `letta` * `custom` Semantic version of your agent. Follow [SemVer](https://semver.org/) format. ### Template Information Name of the template used to create this project. Helps with updates and migration. Source information for the template: Git repository URL containing the template Path within the repository to the template Template author's identifier ### Agent Architecture Defines how RunAgent interacts with your code: List of entrypoint configurations. Each entrypoint defines a way to invoke your agent. Python file containing the entrypoint Dot-notation path to the callable object (e.g., `app.invoke`) Type of entrypoint. Supported values: * `generic` - Standard request/response * `generic_stream` - Streaming responses * `async` - Asynchronous invocation * `batch` - Batch processing ### Environment Variables Environment variables for your agent. Supports two formats: 1. **Dynamic substitution**: `"${VAR_NAME}"` - Reads from environment 2. **Fixed values**: `"fixed_value"` - Uses the literal value Never hardcode sensitive values like API keys. Always use dynamic substitution. ## Entrypoint Types ### Generic Entrypoint Standard request/response pattern: ```python theme={null} # agents.py def invoke(input_data: dict) -> dict: """Process input and return result""" query = input_data.get("query") # Process the query return {"result": "processed result"} app = {"invoke": invoke} ``` Configuration: ```json theme={null} { "file": "agents.py", "module": "app.invoke", "type": "generic" } ``` ### Streaming Entrypoint For real-time response streaming: ```python theme={null} # agents.py def stream(input_data: dict): """Generator that yields chunks""" query = input_data.get("query") for chunk in process_streaming(query): yield chunk app = {"stream": stream} ``` Configuration: ```json theme={null} { "file": "agents.py", "module": "app.stream", "type": "generic_stream" } ``` ## Advanced Configuration ### Multiple Entrypoints You can define multiple entrypoints for different use cases: ```json theme={null} { "agent_architecture": { "entrypoints": [ { "file": "agents.py", "module": "app.chat", "type": "generic" }, { "file": "agents.py", "module": "app.analyze", "type": "generic" }, { "file": "streaming.py", "module": "streamer.process", "type": "generic_stream" } ] } } ``` ### Environment Variable Patterns ```json theme={null} { "env_vars": { // Dynamic from environment "OPENAI_API_KEY": "${OPENAI_API_KEY}", // Fixed value "MODEL_NAME": "gpt-4", // With default fallback (coming soon) "TEMPERATURE": "${TEMPERATURE:-0.7}", // Complex values "CONFIG_JSON": "${CONFIG_JSON}" } } ``` ## Validation RunAgent validates your configuration on: * `runagent init` - When creating a project * `runagent serve` - Before starting local server * `runagent deploy` - Before deployment Common validation errors: Ensure all required fields (`agent_name`, `framework`, `version`, `agent_architecture`) are present. Check that the module path is correct and the file exists. ```bash theme={null} # Verify the module can be imported python -c "from agents import app; print(app.invoke)" ``` Use one of the supported frameworks or `"custom"` for others. ## Best Practices Follow SemVer for your version numbers to track changes properly Add comments in your code explaining what each entrypoint does Never hardcode secrets. Always use environment variable substitution Test your configuration with `runagent serve` before deploying ## Example Configurations ```json theme={null} { "agent_name": "customer_support", "description": "AI customer support agent", "framework": "langgraph", "version": "2.1.0", "agent_architecture": { "entrypoints": [ { "file": "support_agent.py", "module": "agent.handle_query", "type": "generic" }, { "file": "support_agent.py", "module": "agent.chat_stream", "type": "generic_stream" } ] }, "env_vars": { "OPENAI_API_KEY": "${OPENAI_API_KEY}", "SUPPORT_DB_URL": "${DATABASE_URL}", "MAX_TOKENS": "2000" } } ``` ```json theme={null} { "agent_name": "research_crew", "description": "Multi-agent research system", "framework": "crewai", "version": "1.0.0", "agent_architecture": { "entrypoints": [ { "file": "crew.py", "module": "research_crew.kickoff", "type": "generic" } ] }, "env_vars": { "OPENAI_API_KEY": "${OPENAI_API_KEY}", "SERPER_API_KEY": "${SERPER_API_KEY}" } } ``` # Environment Variables Source: https://docs.run-agent.ai/configuration/environment Managing environment variables and secrets in RunAgent ## Overview Environment variables are used to configure your agent without hardcoding sensitive information. RunAgent provides secure methods for managing environment variables across development and production. ## Local Development ### Using .env Files Create a `.env` file in your project root: ```bash theme={null} # .env OPENAI_API_KEY=sk-... DATABASE_URL=postgresql://localhost/mydb REDIS_URL=redis://localhost:6379 DEBUG=true LOG_LEVEL=info ``` Load in your agent: ```python theme={null} from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Access variables api_key = os.getenv("OPENAI_API_KEY") debug = os.getenv("DEBUG", "false").lower() == "true" ``` ### Best Practices 1. **Never commit .env files** ```gitignore theme={null} # .gitignore .env .env.local .env.*.local ``` 2. **Provide .env.example** ```bash theme={null} # .env.example OPENAI_API_KEY=your-api-key-here DATABASE_URL=postgresql://localhost/mydb DEBUG=false ``` 3. **Validate required variables** ```python theme={null} required_vars = ["OPENAI_API_KEY", "DATABASE_URL"] missing = [var for var in required_vars if not os.getenv(var)] if missing: raise ValueError(f"Missing required environment variables: {missing}") ``` ## Configuration in runagent.config.json ### Dynamic Substitution Use `${VAR_NAME}` syntax for runtime substitution: ```json theme={null} { "env_vars": { "OPENAI_API_KEY": "${OPENAI_API_KEY}", "MODEL_NAME": "gpt-4", "TEMPERATURE": "${TEMPERATURE:-0.7}" } } ``` ### Variable Types 1. **Dynamic variables** - Loaded from environment ```json theme={null} "API_KEY": "${API_KEY}" ``` 2. **Static values** - Hardcoded (non-sensitive only) ```json theme={null} "MODEL_VERSION": "v1.0" ``` 3. **With defaults** (coming soon) ```json theme={null} "TIMEOUT": "${TIMEOUT:-30}" ``` ## Production Deployment ### Setting Variables When deploying, set environment variables: ```bash theme={null} # Local deployment OPENAI_API_KEY=sk-... runagent deploy . --local # Cloud deployment (coming soon) runagent deploy . \ --env OPENAI_API_KEY=$OPENAI_API_KEY \ --env DATABASE_URL=$DATABASE_URL ``` ### Security Best Practices 1. **Use secret management services** * AWS Secrets Manager * Google Secret Manager * Azure Key Vault * HashiCorp Vault 2. **Rotate keys regularly** * Set expiration reminders * Use versioned secrets * Update without downtime 3. **Limit scope** * Use read-only credentials where possible * Create service-specific API keys * Apply principle of least privilege ## Common Patterns ### Configuration Classes ```python theme={null} # config.py import os from dataclasses import dataclass @dataclass class Config: openai_api_key: str model_name: str = "gpt-4" temperature: float = 0.7 max_tokens: int = 1000 @classmethod def from_env(cls): return cls( openai_api_key=os.environ["OPENAI_API_KEY"], model_name=os.getenv("MODEL_NAME", "gpt-4"), temperature=float(os.getenv("TEMPERATURE", "0.7")), max_tokens=int(os.getenv("MAX_TOKENS", "1000")) ) # Usage config = Config.from_env() ``` ### Environment-Specific Settings ```python theme={null} # settings.py import os ENV = os.getenv("ENVIRONMENT", "development") CONFIGS = { "development": { "debug": True, "log_level": "DEBUG", "cache_enabled": False }, "staging": { "debug": False, "log_level": "INFO", "cache_enabled": True }, "production": { "debug": False, "log_level": "WARNING", "cache_enabled": True } } settings = CONFIGS[ENV] ``` ### Validation ```python theme={null} # validate_env.py import os import sys def validate_environment(): errors = [] # Required variables required = { "OPENAI_API_KEY": "OpenAI API key", "DATABASE_URL": "Database connection string" } for var, description in required.items(): if not os.getenv(var): errors.append(f"Missing {description} ({var})") # Validate formats api_key = os.getenv("OPENAI_API_KEY", "") if api_key and not api_key.startswith("sk-"): errors.append("Invalid OpenAI API key format") if errors: print("Environment validation failed:") for error in errors: print(f" - {error}") sys.exit(1) # Run validation on startup validate_environment() ``` ## Special Variables ### RunAgent System Variables | Variable | Description | Default | | ---------------------- | --------------- | ------- | | `RUNAGENT_LOG_LEVEL` | Logging level | `INFO` | | `RUNAGENT_TIMEOUT` | Request timeout | `30` | | `RUNAGENT_MAX_RETRIES` | Retry attempts | `3` | ### Framework-Specific ```python theme={null} # LangChain os.environ["LANGCHAIN_TRACING_V2"] = "true" os.environ["LANGCHAIN_API_KEY"] = "..." # OpenAI os.environ["OPENAI_API_KEY"] = "..." os.environ["OPENAI_ORGANIZATION"] = "..." ``` ## Troubleshooting ### Variable Not Found ```python theme={null} # Debug which variables are available print("Available environment variables:") for key, value in os.environ.items(): if key.startswith("RUNAGENT_") or key in ["OPENAI_API_KEY"]: print(f"{key}={value[:5]}...") # Show only first 5 chars ``` ### Loading Order 1. System environment variables 2. `.env` file (local development) 3. RunAgent configuration (deployment) 4. Runtime overrides ### Common Issues 1. **Quotes in .env files** ```bash theme={null} # Wrong API_KEY="sk-abc123" # Correct API_KEY=sk-abc123 ``` 2. **Spaces around equals** ```bash theme={null} # Wrong API_KEY = sk-abc123 # Correct API_KEY=sk-abc123 ``` 3. **Multiline values** ```bash theme={null} # Use quotes for multiline PROMPT="This is a multiline prompt" ``` ## See Also * [Configuration File](/configuration/config-file) - Config structure * [Security Best Practices](/runagent-cloud/cloud-deployment) - Production security * [Local Development](/deployment/local-development) - Development setup # Project Structure Source: https://docs.run-agent.ai/configuration/project-structure Understanding RunAgent project organization ## Overview A well-organized project structure is key to maintainable and deployable AI agents. This guide covers the standard RunAgent project layout and best practices. ## Basic Structure ``` my-agent/ ├── agent.py # Main agent implementation ├── runagent.config.json # RunAgent configuration ├── requirements.txt # Python dependencies ├── .env # Environment variables (local only) ├── .env.example # Example environment template ├── .gitignore # Git ignore rules ├── README.md # Project documentation └── tests/ # Unit tests (optional) ``` ## Core Files ### agent.py Your main agent implementation: ```python theme={null} # agent.py def invoke(input_data: dict) -> dict: """Main entrypoint for request/response""" # Your agent logic return {"response": processed_result} def stream(input_data: dict): """Optional streaming entrypoint""" for chunk in process_streaming(input_data): yield chunk ``` ### runagent.config.json Configuration file that tells RunAgent how to run your agent: ```json theme={null} { "agent_name": "my-agent", "framework": "langgraph", "version": "1.0.0", "agent_architecture": { "entrypoints": [ { "file": "agent.py", "module": "invoke", "type": "generic" } ] } } ``` ### requirements.txt All Python dependencies: ```txt theme={null} openai>=1.0.0 langchain>=0.1.0 python-dotenv>=1.0.0 # Your other dependencies ``` ## Advanced Structure For larger projects: ``` my-agent/ ├── src/ │ ├── __init__.py │ ├── agent.py # Main agent │ ├── models.py # Data models │ ├── tools.py # Agent tools │ └── utils.py # Utilities ├── prompts/ │ ├── system.txt # System prompts │ └── templates.py # Prompt templates ├── config/ │ ├── development.json # Dev config │ └── production.json # Prod config ├── tests/ │ ├── test_agent.py │ └── test_tools.py ├── docs/ │ └── API.md ├── runagent.config.json ├── requirements.txt ├── requirements-dev.txt # Dev dependencies ├── Makefile # Common commands └── README.md ``` ## Framework-Specific Structures ### LangGraph Projects ``` langgraph-agent/ ├── agents.py # Graph definition ├── nodes/ # Graph nodes │ ├── __init__.py │ ├── process.py │ └── analyze.py ├── edges.py # Edge logic ├── state.py # State schema ├── tools.py # Custom tools └── runagent.config.json ``` ### CrewAI Projects ``` crewai-project/ ├── crew.py # Crew definition ├── agents/ # Individual agents │ ├── researcher.py │ ├── writer.py │ └── reviewer.py ├── tasks/ # Task definitions │ └── tasks.py ├── tools/ # Shared tools └── runagent.config.json ``` ## File Organization Best Practices ### 1. Separate Concerns ```python theme={null} # Good: Separated modules # models.py class InputModel: pass # tools.py def search_tool(): pass # agent.py from models import InputModel from tools import search_tool ``` ### 2. Configuration Management ```python theme={null} # config.py import os from typing import Dict def get_config() -> Dict: env = os.getenv("ENVIRONMENT", "development") configs = { "development": { "debug": True, "timeout": 60 }, "production": { "debug": False, "timeout": 30 } } return configs[env] ``` ### 3. Modular Entrypoints ```python theme={null} # entrypoints.py from src.agent import Agent agent = Agent() def invoke(input_data: dict) -> dict: return agent.process(input_data) def stream(input_data: dict): yield from agent.stream(input_data) ``` ## Environment Management ### Development `.env` file (never commit): ``` OPENAI_API_KEY=sk-... DATABASE_URL=postgresql://... DEBUG=true ``` ### Production Use RunAgent's environment variable management: ```json theme={null} { "env_vars": { "OPENAI_API_KEY": "${OPENAI_API_KEY}", "DATABASE_URL": "${DATABASE_URL}", "DEBUG": "false" } } ``` ## Testing Structure ``` tests/ ├── conftest.py # Pytest configuration ├── fixtures/ # Test data │ └── sample_input.json ├── unit/ # Unit tests │ ├── test_agent.py │ └── test_tools.py └── integration/ # Integration tests └── test_api.py ``` ## Deployment Files ### .gitignore ```gitignore theme={null} # Python __pycache__/ *.py[cod] *$py.class *.so .Python venv/ env/ # Environment .env .env.local # IDE .vscode/ .idea/ *.swp # OS .DS_Store Thumbs.db # RunAgent .runagent/ logs/ ``` ### Makefile ```makefile theme={null} .PHONY: install test run deploy install: pip install -r requirements.txt test: pytest tests/ run: runagent serve . deploy: runagent deploy . clean: find . -type d -name "__pycache__" -exec rm -rf {} + find . -type f -name "*.pyc" -delete ``` ## See Also * [Configuration File](/configuration/config-file) - Config details * [Environment Variables](/configuration/environment) - Environment setup * [First Agent](/get-started/first-agent) - Build your first project # Local Development Source: https://docs.run-agent.ai/deployment/local-development Running and testing agents locally ## Overview Local development with RunAgent provides a fast feedback loop for building and testing your agents before deployment. This guide covers local setup, testing, and debugging. ## Getting Started ### Basic Local Server ```bash theme={null} # Start local server runagent serve . # With custom port runagent serve . --port 8080 # With hot reload disabled runagent serve . --no-reload ``` ### Server Output ``` INFO: Started server process [12345] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` ## Testing Your Agent ### Using cURL ```bash theme={null} # Health check curl http://localhost:8000/health # Invoke agent curl -X POST http://localhost:8000/invoke \ -H "Content-Type: application/json" \ -d '{"query": "Hello, agent!"}' # Stream response curl -X POST http://localhost:8000/stream \ -H "Content-Type: application/json" \ -d '{"query": "Tell me a story"}' \ --no-buffer ``` ### Using Python ```python theme={null} import requests # Test invocation response = requests.post( "http://localhost:8000/invoke", json={"query": "What's the weather?"} ) print(response.json()) # Test streaming response = requests.post( "http://localhost:8000/stream", json={"query": "Explain quantum physics"}, stream=True ) for line in response.iter_lines(): if line: print(line.decode('utf-8')) ``` ### Interactive Testing ```python theme={null} # test_client.py import requests import json BASE_URL = "http://localhost:8000" def test_agent(): while True: query = input("\nEnter query (or 'quit'): ") if query.lower() == 'quit': break response = requests.post( f"{BASE_URL}/invoke", json={"query": query} ) print("\nResponse:") print(json.dumps(response.json(), indent=2)) if __name__ == "__main__": test_agent() ``` ## Development Features ### Hot Reload Changes to your agent code automatically restart the server: ```python theme={null} # agent.py def invoke(input_data): # Make changes here - server auto-reloads return {"response": "Updated response!"} ``` ### Debug Mode ```bash theme={null} # Enable debug logging runagent serve . --log-level debug # Or set environment variable DEBUG=true runagent serve . ``` ### Custom Configuration ```python theme={null} # dev_config.py DEV_CONFIG = { "host": "0.0.0.0", # Expose to network "port": 8080, "reload": True, "log_level": "debug", "access_log": True } # Use in development # runagent serve . --config dev_config.py ``` ## Local API Endpoints | Endpoint | Method | Description | | --------------- | ------ | ----------------------------- | | `/` | GET | Welcome page with API info | | `/health` | GET | Health check endpoint | | `/invoke` | POST | Synchronous agent invocation | | `/stream` | POST | Streaming agent responses | | `/docs` | GET | Interactive API documentation | | `/openapi.json` | GET | OpenAPI schema | ## Debugging Techniques ### Logging ```python theme={null} import logging # Configure logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) def invoke(input_data): logger.debug(f"Received input: {input_data}") try: result = process(input_data) logger.info(f"Processing successful: {result}") return result except Exception as e: logger.error(f"Error processing: {e}", exc_info=True) raise ``` ### Breakpoint Debugging ```python theme={null} def invoke(input_data): # Using built-in debugger breakpoint() # or import pdb; pdb.set_trace() # Your agent logic result = process(input_data) return result ``` ### Performance Profiling ```python theme={null} import time import cProfile import pstats def profile_agent(): profiler = cProfile.Profile() # Profile agent execution profiler.enable() result = invoke({"query": "test"}) profiler.disable() # Print stats stats = pstats.Stats(profiler) stats.sort_stats('cumulative') stats.print_stats(10) # Top 10 functions ``` ## Development Tools ### Makefile ```makefile theme={null} # Makefile for common tasks .PHONY: run test lint format run: runagent serve . --reload test: pytest tests/ -v lint: flake8 . --max-line-length=100 mypy . --ignore-missing-imports format: black . isort . watch: watchmedo auto-restart \ --directory=. \ --pattern="*.py" \ --recursive \ -- runagent serve . ``` ### Docker Development ```dockerfile theme={null} # Dockerfile.dev FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["runagent", "serve", ".", "--host", "0.0.0.0"] ``` ```yaml theme={null} # docker-compose.yml version: '3.8' services: agent: build: context: . dockerfile: Dockerfile.dev ports: - "8000:8000" volumes: - .:/app environment: - OPENAI_API_KEY=${OPENAI_API_KEY} command: runagent serve . --host 0.0.0.0 --reload ``` ## Testing Strategies ### Unit Tests ```python theme={null} # tests/test_agent.py import pytest from agent import invoke def test_invoke_success(): result = invoke({"query": "test"}) assert "response" in result def test_invoke_error(): with pytest.raises(ValueError): invoke({}) # Missing required field @pytest.mark.parametrize("query,expected", [ ("Hello", "greeting"), ("Calculate", "math"), ("Search", "web") ]) def test_query_routing(query, expected): result = invoke({"query": query}) assert result["type"] == expected ``` ### Integration Tests ```python theme={null} # tests/test_integration.py import requests import subprocess import time def test_full_workflow(): # Start server proc = subprocess.Popen(["runagent", "serve", "."]) time.sleep(2) # Wait for startup try: # Test endpoints response = requests.get("http://localhost:8000/health") assert response.status_code == 200 response = requests.post( "http://localhost:8000/invoke", json={"query": "test"} ) assert response.status_code == 200 finally: proc.terminate() ``` ## Common Issues ### Port Already in Use ```bash theme={null} # Find process using port lsof -i :8000 # Kill process kill -9 # Or use different port runagent serve . --port 8001 ``` ### Module Import Errors ```bash theme={null} # Check Python path python -c "import sys; print(sys.path)" # Add current directory export PYTHONPATH="${PYTHONPATH}:." ``` ### Environment Variables Not Loading ```bash theme={null} # Check if .env exists ls -la .env # Load manually set -a source .env set +a runagent serve . ``` ## See Also * [Cloud Deployment](/runagent-cloud/cloud-deployment) - Deploy to production * [CLI Reference](/cli/overview) - Complete CLI documentation * [Troubleshooting](/resources/troubleshooting) - Common issues # Architecture Overview Source: https://docs.run-agent.ai/explanation/architecture-overview Understand RunAgent system architecture and how it works **Prerequisites**: Understanding of [Core Concepts](/explanation/core-concepts) and basic knowledge of distributed systems ## Overview RunAgent is built on a modern, scalable architecture that enables Python-based AI agents to be accessed from any programming language. The system is designed for high performance, reliability, and ease of use. ## High-Level Architecture ```mermaid theme={null} graph TB subgraph "Client Applications" PY[Python SDK] JS[JavaScript SDK] GO[Go SDK] RS[Rust SDK] end subgraph "RunAgent Platform" LB[Load Balancer] API[REST API Gateway] WS[WebSocket Gateway] AG[Agent Manager] VM[Firecracker VMs] end subgraph "Python Agents" A1[Agent 1] A2[Agent 2] A3[Agent N] end subgraph "Infrastructure" DB[(Database)] CACHE[(Cache)] MON[Monitoring] LOG[Logging] end PY --> LB JS --> LB GO --> LB RS --> LB LB --> API LB --> WS API --> AG WS --> AG AG --> VM VM --> A1 VM --> A2 VM --> A3 AG --> DB AG --> CACHE AG --> MON AG --> LOG ``` ## Core Components ### 1. **Client SDKs** RunAgent provides native SDKs for multiple programming languages: * **Python SDK**: Full-featured with sync/async support * **JavaScript SDK**: TypeScript support with async/await * **Go SDK**: Idiomatic Go with context-aware operations * **Rust SDK**: High-performance with zero-cost abstractions Each SDK provides: * **Authentication**: API key management * **Request/Response**: Synchronous and asynchronous calls * **Streaming**: Real-time response streaming * **Error Handling**: Language-appropriate error types * **Retry Logic**: Automatic retry with backoff ### 2. **API Gateway** The API Gateway handles: * **Request Routing**: Routes requests to appropriate agents * **Authentication**: Validates API keys and permissions * **Rate Limiting**: Enforces rate limits per client * **Load Balancing**: Distributes load across agent instances * **Protocol Translation**: Converts between HTTP and WebSocket ### 3. **Agent Manager** The Agent Manager is responsible for: * **Agent Lifecycle**: Starting, stopping, and monitoring agents * **Configuration Management**: Loading and validating configurations * **Health Monitoring**: Checking agent health and availability * **Scaling**: Automatically scaling agents based on demand * **Resource Management**: Allocating and managing resources ### 4. **Firecracker MicroVMs** RunAgent uses Firecracker for secure, isolated agent execution: * **Security**: Each agent runs in its own microVM * **Isolation**: Complete process and resource isolation * **Performance**: Near-native performance with minimal overhead * **Scalability**: Fast boot times and efficient resource usage * **Sandboxing**: Secure execution environment ## Data Flow ### 1. **Request Processing** ```mermaid theme={null} sequenceDiagram participant C as Client SDK participant LB as Load Balancer participant API as API Gateway participant AM as Agent Manager participant VM as Firecracker VM participant A as Python Agent C->>LB: HTTP/WebSocket Request LB->>API: Route Request API->>AM: Validate & Route AM->>VM: Execute Agent VM->>A: Call Entrypoint A->>VM: Return Response VM->>AM: Stream Response AM->>API: Forward Response API->>LB: Send Response LB->>C: Return to Client ``` ### 2. **Streaming Response** ```mermaid theme={null} sequenceDiagram participant C as Client SDK participant WS as WebSocket Gateway participant AM as Agent Manager participant VM as Firecracker VM participant A as Python Agent C->>WS: WebSocket Connection WS->>AM: Route Stream Request AM->>VM: Execute Streaming Agent VM->>A: Call Streaming Entrypoint loop Stream Response A->>VM: Yield Chunk VM->>AM: Forward Chunk AM->>WS: Stream Chunk WS->>C: Send Chunk end A->>VM: Stream Complete VM->>AM: Stream End AM->>WS: Close Stream WS->>C: Close Connection ``` ## Security Architecture ### 1. **Multi-Layer Security** ```mermaid theme={null} graph TB subgraph "Security Layers" AUTH[Authentication] AUTHZ[Authorization] RATE[Rate Limiting] VALID[Input Validation] SANDBOX[Sandboxing] ISOLATION[Process Isolation] end subgraph "Client Request" REQ[HTTP/WebSocket Request] end subgraph "Agent Execution" AGENT[Python Agent] end REQ --> AUTH AUTH --> AUTHZ AUTHZ --> RATE RATE --> VALID VALID --> SANDBOX SANDBOX --> ISOLATION ISOLATION --> AGENT ``` ### 2. **Firecracker Security Model** * **MicroVM Isolation**: Each agent runs in its own microVM * **Resource Limits**: CPU, memory, and network constraints * **File System**: Restricted file system access * **Network**: Controlled network access * **Process**: Complete process isolation ## Scalability Architecture ### 1. **Horizontal Scaling** ```mermaid theme={null} graph TB subgraph "Load Balancer" LB[Load Balancer] end subgraph "Agent Instances" A1[Agent Instance 1] A2[Agent Instance 2] A3[Agent Instance 3] AN[Agent Instance N] end subgraph "Auto-scaling" AS[Auto-scaler] METRICS[Metrics Collector] end LB --> A1 LB --> A2 LB --> A3 LB --> AN METRICS --> AS AS --> A1 AS --> A2 AS --> A3 AS --> AN ``` ### 2. **Auto-scaling Triggers** * **CPU Usage**: Scale up when CPU usage exceeds threshold * **Memory Usage**: Scale up when memory usage is high * **Request Rate**: Scale up when request rate increases * **Response Time**: Scale up when response times are slow * **Queue Length**: Scale up when request queue is long ## Performance Architecture ### 1. **Caching Strategy** ```mermaid theme={null} graph TB subgraph "Client Side" CLIENT[Client SDK] CLIENT_CACHE[Client Cache] end subgraph "API Gateway" API[API Gateway] API_CACHE[API Cache] end subgraph "Agent Manager" AM[Agent Manager] AM_CACHE[Agent Cache] end CLIENT --> CLIENT_CACHE CLIENT_CACHE --> API API --> API_CACHE API_CACHE --> AM AM --> AM_CACHE AM_CACHE --> AGENT[Python Agent] ``` ### 2. **Performance Optimizations** * **Connection Pooling**: Reuse connections for efficiency * **Request Batching**: Batch multiple requests together * **Response Compression**: Compress responses to reduce bandwidth * **CDN Integration**: Use CDN for static content * **Database Optimization**: Optimize database queries and indexes ## Monitoring and Observability ### 1. **Monitoring Stack** ```mermaid theme={null} graph TB subgraph "Applications" AGENT[Python Agent] API[API Gateway] AM[Agent Manager] end subgraph "Metrics Collection" PROMETHEUS[Prometheus] GRAFANA[Grafana] end subgraph "Logging" ELASTIC[Elasticsearch] KIBANA[Kibana] end subgraph "Tracing" JAEGER[Jaeger] ZIPKIN[Zipkin] end AGENT --> PROMETHEUS API --> PROMETHEUS AM --> PROMETHEUS AGENT --> ELASTIC API --> ELASTIC AM --> ELASTIC AGENT --> JAEGER API --> JAEGER AM --> JAEGER ``` ### 2. **Key Metrics** * **Request Rate**: Requests per second * **Response Time**: Average and P95 response times * **Error Rate**: Percentage of failed requests * **Resource Usage**: CPU, memory, and network usage * **Agent Health**: Agent availability and performance ## Deployment Architecture ### 1. **Cloud Deployment** ```mermaid theme={null} graph TB subgraph "Cloud Provider" subgraph "Load Balancer" LB[Load Balancer] end subgraph "API Tier" API1[API Gateway 1] API2[API Gateway 2] end subgraph "Agent Tier" AGENT1[Agent Manager 1] AGENT2[Agent Manager 2] end subgraph "VM Tier" VM1[Firecracker VM 1] VM2[Firecracker VM 2] VM3[Firecracker VM 3] end subgraph "Data Tier" DB[(Database)] CACHE[(Cache)] end end LB --> API1 LB --> API2 API1 --> AGENT1 API2 --> AGENT2 AGENT1 --> VM1 AGENT1 --> VM2 AGENT2 --> VM3 AGENT1 --> DB AGENT2 --> CACHE ``` ### 2. **Local Development** ```mermaid theme={null} graph TB subgraph "Local Machine" CLI[RunAgent CLI] SERVER[Local Server] AGENT[Python Agent] end CLI --> SERVER SERVER --> AGENT ``` ## Error Handling Architecture ### 1. **Error Propagation** ```mermaid theme={null} graph TB subgraph "Error Sources" AGENT[Python Agent] VM[Firecracker VM] AM[Agent Manager] API[API Gateway] end subgraph "Error Handling" VALIDATE[Validation] RETRY[Retry Logic] FALLBACK[Fallback] LOG[Logging] end subgraph "Client Response" CLIENT[Client SDK] end AGENT --> VM VM --> AM AM --> API API --> VALIDATE VALIDATE --> RETRY RETRY --> FALLBACK FALLBACK --> LOG LOG --> CLIENT ``` ### 2. **Error Types** * **Client Errors**: Authentication, validation, rate limiting * **Server Errors**: Internal server errors, agent failures * **Network Errors**: Connection timeouts, network issues * **Agent Errors**: Python exceptions, function errors ## Future Architecture ### 1. **Planned Enhancements** * **Multi-Region Deployment**: Global agent deployment * **Edge Computing**: Deploy agents closer to users * **GPU Support**: GPU-accelerated agent execution * **Custom Runtimes**: Support for additional languages * **Advanced Caching**: Intelligent response caching ### 2. **Scalability Improvements** * **Kubernetes Integration**: Native Kubernetes support * **Service Mesh**: Istio integration for advanced networking * **Event-Driven Architecture**: Event-based agent communication * **Stream Processing**: Real-time data processing capabilities ## Best Practices ### 1. **Agent Design** * **Stateless**: Design agents to be stateless * **Idempotent**: Make operations idempotent * **Error Handling**: Implement proper error handling * **Resource Management**: Manage resources efficiently * **Monitoring**: Add appropriate logging and metrics ### 2. **Performance Optimization** * **Caching**: Use caching for expensive operations * **Streaming**: Use streaming for long-running operations * **Batch Processing**: Batch multiple operations together * **Resource Limits**: Set appropriate resource limits * **Connection Pooling**: Use connection pooling ## Next Steps Learn about production deployment requirements Understand RunAgent's security model Learn advanced performance optimization techniques Deploy your agents to production **🎉 Excellent!** You now understand RunAgent's architecture and how it enables seamless multi-language AI agent deployment. This knowledge will help you build more effective agents and troubleshoot issues! * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Changelog Source: https://docs.run-agent.ai/explanation/changelog Recent changes and updates to RunAgent # Changelog All notable changes to RunAgent will be documented in this file. ## \[Unreleased] ### Added * Comprehensive documentation restructuring with Diátaxis framework * New Introduction section with 7 pages including Feature Overview and Quickstart Map * Overview pages for all major sections (Tutorials, How-to, Reference, Explanation, Resources) * Enhanced navigation with role-based and experience-level guidance ### Changed * Improved documentation structure and organization * Better user experience with scannable cards and clear navigation paths * Enhanced positioning with "Why RunAgent?" and cost comparison content ### Fixed * Removed duplicate titles and descriptions from pages * Fixed broken links and navigation references * Cleaned up unused files and empty directories ## \[0.1.0] - 2024-01-XX ### Added * Initial release of RunAgent * Python, JavaScript, Go, and Rust SDKs * Firecracker microVM sandboxing * Streaming response support * Multi-language agent access * Local development server * Framework integrations (LangGraph, CrewAI, Letta, Agno) ### Features * Serverless agent deployment * Auto-scaling capabilities * Real-time streaming responses * Cross-language SDK support * Sandboxed execution environment * Production-ready security model This changelog follows [Keep a Changelog](https://keepachangelog.com/) format. All dates are in YYYY-MM-DD format. # Core Concepts Source: https://docs.run-agent.ai/explanation/core-concepts Understand the fundamental concepts that make RunAgent work **Prerequisites**: Basic understanding of AI agents and completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview RunAgent is built on several core concepts that work together to create a seamless multi-language AI agent deployment platform. Understanding these concepts will help you build more effective agents and troubleshoot issues. ## Entrypoints ### What are Entrypoints? Entrypoints are Python functions that define how your agent can be invoked. They serve as the bridge between your agent's logic and the universal API that RunAgent creates. ```python theme={null} def my_agent(message: str, user_id: str = "default") -> str: """This is an entrypoint function""" return f"Hello {user_id}, you said: {message}" ``` ### Entrypoint Characteristics * **Function Signature**: Defines the API contract for all languages * **Parameters**: Automatically become API parameters * **Return Value**: Becomes the response sent to clients * **Documentation**: Function docstrings become API documentation ### Entrypoint Types #### Synchronous Entrypoints Return a single value immediately: ```python theme={null} def sync_agent(query: str) -> Dict[str, Any]: """Synchronous agent that returns complete response""" return { "response": f"Processed: {query}", "status": "success", "timestamp": datetime.now().isoformat() } ``` #### Streaming Entrypoints Return an iterator for real-time responses: ```python theme={null} def stream_agent(query: str) -> Iterator[str]: """Streaming agent that yields response chunks""" yield f"Starting to process: {query}\n" yield "Analyzing your request...\n" yield "Generating response...\n" yield f"Final result: {query.upper()}\n" ``` ### Entrypoint Naming Convention * **Synchronous**: Use descriptive names like `chat`, `analyze`, `process` * **Streaming**: End with `_stream` suffix like `chat_stream`, `analyze_stream` ## Tags ### What are Tags? Tags are identifiers that map entrypoint functions to API endpoints. They allow you to have multiple entrypoints in the same agent and call them by name. ```json theme={null} { "entrypoints": [ { "file": "main.py", "module": "chat_agent", "tag": "chat" }, { "file": "main.py", "module": "chat_agent_stream", "tag": "chat_stream" } ] } ``` ### Tag Best Practices * Use descriptive, lowercase names * Avoid special characters and spaces * Use underscores for multi-word tags * Keep tags consistent across environments ## Agent Lifecycle ### 1. Initialization When you run `runagent serve .`: 1. **Configuration Loading**: Reads `runagent.config.json` 2. **Entrypoint Discovery**: Imports and validates entrypoint functions 3. **Server Startup**: Starts REST and WebSocket servers 4. **Health Check**: Verifies all entrypoints are callable ### 2. Request Processing When a client makes a request: 1. **Request Validation**: Validates parameters against function signature 2. **Function Invocation**: Calls the appropriate entrypoint function 3. **Response Processing**: Handles return value or streaming 4. **Client Response**: Sends response back to client ### 3. Shutdown When you stop the agent: 1. **Graceful Shutdown**: Finishes processing current requests 2. **Resource Cleanup**: Closes connections and frees resources 3. **Server Stop**: Shuts down REST and WebSocket servers ## Multi-Language Translation ### How Function Signatures Become APIs RunAgent automatically translates Python function signatures into language-specific APIs: ```python theme={null} # Python function def process_data(data: List[Dict], analysis_type: str = "summary") -> Dict[str, Any]: pass ``` Becomes: ```python theme={null} # Python SDK result = client.run(data=[{"key": "value"}], analysis_type="summary") ``` ```javascript theme={null} // JavaScript SDK const result = await client.run({ data: [{"key": "value"}], analysisType: "summary" }); ``` ```go theme={null} // Go SDK result, err := client.Run(ctx, map[string]interface{}{ "data": []map[string]interface{}{{"key": "value"}}, "analysisType": "summary", }) ``` ```rust theme={null} // Rust SDK let result = client.run(&[ ("data", json!([{"key": "value"}])), ("analysis_type", json!("summary")), ]).await?; ``` ### Type Translation Rules | Python Type | JavaScript | Go | Rust | | ---------------- | ---------- | ------------------------ | ------------------------ | | `str` | `string` | `string` | `String` | | `int` | `number` | `int` | `i64` | | `float` | `number` | `float64` | `f64` | | `bool` | `boolean` | `bool` | `bool` | | `List[T]` | `T[]` | `[]T` | `Vec` | | `Dict[str, Any]` | `object` | `map[string]interface{}` | `HashMap` | ## Streaming Architecture ### How Streaming Works 1. **Client Request**: Client calls streaming entrypoint 2. **WebSocket Connection**: Establishes real-time connection 3. **Iterator Processing**: Python generator yields chunks 4. **Real-time Transmission**: Chunks sent immediately to client 5. **Native Iteration**: Client receives chunks in language-appropriate way ### Streaming Patterns #### Python Generator ```python theme={null} def stream_agent(query: str) -> Iterator[str]: yield f"Processing: {query}\n" yield "Step 1: Analyzing...\n" yield "Step 2: Generating...\n" yield f"Result: {query.upper()}\n" ``` #### JavaScript Async Iterator ```javascript theme={null} const stream = await client.run({query: "Hello"}); for await (const chunk of stream) { console.log(chunk); } ``` #### Rust Futures Stream ```rust theme={null} let mut stream = client.run_stream(&[("query", json!("Hello"))]).await?; while let Some(chunk) = stream.next().await { print!("{}", chunk?); } ``` ## Configuration System ### runagent.config.json Structure ```json theme={null} { "agent_name": "my-agent", "description": "A description of what this agent does", "framework": "custom", "agent_architecture": { "entrypoints": [ { "file": "main.py", "module": "function_name", "tag": "endpoint_name" } ] } } ``` ### Configuration Validation RunAgent validates your configuration by: 1. **File Existence**: Checking that specified files exist 2. **Module Import**: Verifying modules can be imported 3. **Function Existence**: Confirming functions exist in modules 4. **Signature Validation**: Ensuring functions are callable 5. **Tag Uniqueness**: Verifying tags are unique ## Error Handling ### Error Types #### Client-Side Errors * **AuthenticationError**: Invalid or missing API key * **AgentNotFoundError**: Agent doesn't exist * **ValidationError**: Invalid request parameters * **RateLimitError**: Too many requests * **TimeoutError**: Request timed out * **NetworkError**: Connection issues #### Server-Side Errors * **ImportError**: Cannot import entrypoint module * **FunctionError**: Entrypoint function raised exception * **ConfigurationError**: Invalid configuration * **ServerError**: Internal server error ### Error Propagation Errors flow from Python functions through RunAgent to client SDKs: ```python theme={null} def my_agent(query: str) -> str: if not query: raise ValueError("Query cannot be empty") return f"Processed: {query}" ``` Becomes: ```python theme={null} # Python SDK try: result = client.run(query="") except ValidationError as e: print(f"Validation error: {e}") ``` ## Security Model ### Sandboxing RunAgent provides multiple layers of security: 1. **Process Isolation**: Each agent runs in its own process 2. **Resource Limits**: CPU and memory constraints 3. **Network Isolation**: Controlled network access 4. **File System**: Restricted file system access ### API Security * **Authentication**: API key-based authentication * **Authorization**: Role-based access control * **Rate Limiting**: Request rate limiting * **Input Validation**: Parameter validation and sanitization ## Performance Considerations ### Scalability RunAgent is designed to scale: 1. **Horizontal Scaling**: Multiple agent instances 2. **Load Balancing**: Automatic request distribution 3. **Auto-scaling**: Dynamic instance management 4. **Caching**: Response caching for performance ### Optimization Tips 1. **Efficient Entrypoints**: Keep functions focused and fast 2. **Streaming**: Use streaming for long-running operations 3. **Caching**: Cache expensive computations 4. **Resource Management**: Monitor memory and CPU usage ## Common Patterns ### 1. **Simple Chat Agent** ```python theme={null} def chat_agent(message: str, user_id: str = "default") -> str: """Simple chat agent""" return f"Hello {user_id}, you said: {message}" ``` ### 2. **Data Processing Agent** ```python theme={null} def process_data(data: List[Dict], operation: str = "sum") -> Dict[str, Any]: """Process data with different operations""" if operation == "sum": return {"result": sum(item.get("value", 0) for item in data)} elif operation == "count": return {"result": len(data)} else: return {"error": "Unknown operation"} ``` ### 3. **Streaming Analysis Agent** ```python theme={null} def analyze_stream(data: str) -> Iterator[str]: """Streaming analysis agent""" yield "Starting analysis...\n" yield f"Processing {len(data)} characters\n" yield "Analyzing content...\n" yield f"Analysis complete: {data.upper()}\n" ``` ## Troubleshooting ### Common Issues 1. **Import Errors**: Check Python path and dependencies 2. **Function Not Found**: Verify module and function names 3. **Type Errors**: Ensure parameter types match 4. **Streaming Issues**: Check iterator return type 5. **Configuration Errors**: Validate JSON syntax ### Debug Tips 1. **Enable Logging**: Use verbose logging for debugging 2. **Test Locally**: Test functions before deploying 3. **Check Dependencies**: Ensure all imports are available 4. **Validate Configuration**: Use configuration validation tools 5. **Monitor Performance**: Track response times and resource usage ## Next Steps Learn about RunAgent's system architecture Understand production deployment requirements Learn about RunAgent's security model Explore advanced agent development patterns **🎉 Great work!** You now understand the core concepts that make RunAgent work. These concepts form the foundation for building powerful, multi-language AI agents! * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Feature Overview Source: https://docs.run-agent.ai/explanation/feature-overview A high-level map of what RunAgent can do today — and what is coming > See what RunAgent supports — from serverless deployment to streaming SDKs, security, observability, and agent workflows. ## Start Small, Scale Big Write one Python function, deploy it, and call it from any language. Use LangGraph, CrewAI, or your own custom agent. Full SDKs in Python, JS, Go, Rust; REST/WebSocket APIs with streaming. *** ## Capabilities at a Glance | Feature | What It Enables | | -------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | **Secure Isolation** | Each agent runs in its own isolated environment for security and resource containment | | **Automatic Scaling** | RunAgent scales agents automatically under load with fast cold starts | | **Real-Time Streaming** | Clients receive tokens as they are generated — ideal for chat UIs and interactive applications | | **Cross-Language Access** | Call the same agent from JavaScript, Go, Python, Rust without extra infrastructure | | **State & Memory** *(coming soon)* | Agents can optionally hold memory across calls for richer, contextual behavior | | **Security & Auth** *(in progress)* | Agent-scoped API keys, role-based access, sandbox limits | | **Telemetry & Observability** *(future)* | Logs, metrics, traces to monitor latency, errors, and usage patterns | | **Agent-to-Agent (A2A)** *(vision)* | Agents can call and coordinate with other agents for complex workflows | | **Versioning, Rollbacks, Rate Limits** *(roadmap)* | Control agent versions, limit usage, and revert deployments if needed | *** ## How It Works (High Level) 1. **Write an agent** - Create a Python function with entrypoint configuration 2. **Deploy serverlessly** - RunAgent handles isolation, sandboxing, and automatic scaling 3. **Call via SDK / REST / WebSocket** - Use streaming, synchronous calls, across multiple languages 4. **Monitor & scale** - Track logs, metrics, retries, and rate limits 5. **Iterate & evolve** - Deploy new versions, add memory, enable agent communication *** ## Production-Ready Features Deploy agents to production in seconds with `runagent deploy .` - no infrastructure configuration needed. Works seamlessly with LangGraph, CrewAI, AutoGen, AG2, Letta, and custom frameworks. Python, JavaScript/TypeScript, Go, and Rust SDKs with idiomatic APIs. C++ and C# coming soon. WebSocket-based streaming works natively across all SDKs with minimal code changes. *** ## Next Steps * Start with **[Deploy your first agent](/tutorials/deploy-your-first-agent)** * Explore **[Frameworks & How-tos](/explanation/frameworks-overview)** * Dive into **[SDK / API Reference](/reference/sdk/overview)** * Or read about **[Architecture & Concepts](/explanation/core-concepts)** *** This page is a **landing overview**. For detailed instructions, go to the linked pages above. * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Frameworks Overview Source: https://docs.run-agent.ai/explanation/frameworks-overview Deploy agents built with any AI framework ## Supported Frameworks RunAgent is designed to work with any AI agent framework. We provide first-class support for popular frameworks while allowing custom implementations. Build stateful, multi-step agents with graph-based workflows Create multi-agent systems with role-based collaboration Develop agents with built-in memory and reasoning Build conversational agents with long-term memory Orchestrate LLM chains into sophisticated workflows Build context-aware document indices for LLM retrieval ## Quick Start Examples ```bash theme={null} runagent init my-agent --framework langgraph cd my-agent # Edit agents.py with your LangGraph logic runagent serve . ``` ```bash theme={null} runagent init my-crew --framework crewai cd my-crew # Define your crew in crew.py runagent serve . ``` ```bash theme={null} runagent init my-custom --framework custom cd my-custom # Implement your agent logic runagent serve . ``` ## Framework Integration All frameworks integrate with RunAgent through: 1. **Standardized Entrypoints**: Define how to invoke your agent 2. **Configuration**: Specify framework in `runagent.config.json` 3. **Environment Management**: Handle API keys and settings 4. **Deployment**: Same process regardless of framework ## Best Practices by Framework * Keep graphs simple and readable * Use appropriate state persistence * Handle edge cases in transitions * Test each node independently * Define clear agent roles * Minimize agent dependencies * Use appropriate delegation patterns * Monitor inter-agent communication * Follow RunAgent conventions * Implement proper error handling * Document your approach * Consider open-sourcing if general-purpose ## Migration Between Frameworks RunAgent makes it easy to switch frameworks: 1. **Keep business logic separate** from framework code 2. **Use consistent interfaces** for inputs/outputs 3. **Test thoroughly** after migration 4. **Update configuration** in `runagent.config.json` ## Community Frameworks We're always adding support for new frameworks. Coming soon: * AutoGen * BabyAGI * AgentGPT * Custom community frameworks ## Contributing Framework Support Want to add support for a new framework? 1. Check our [contribution guidelines](https://github.com/runagent-dev/runagent/contribute) 2. Create a template for the framework 3. Add documentation 4. Submit a pull request ## Next Steps Build your first LangGraph agent Create a multi-agent crew * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Installation Source: https://docs.run-agent.ai/explanation/installation Install RunAgent CLI and SDK on your system RunAgent provides Python, JavaScript, Rust, and Go SDKs along with a powerful CLI for deploying and managing AI agents across multiple frameworks. ## Install RunAgent CLI Before installing RunAgent, ensure you have Python 3.8+. ```pip pip theme={null} pip install runagent ``` ```uv uv theme={null} uv add runagent ``` The CLI comes bundled with the Python SDK for seamless local development. Check that RunAgent is installed correctly: ```bash theme={null} runagent --version ``` For cloud deployment and middleware sync features, configure your authentication: ```bash theme={null} runagent setup ``` This will prompt you to choose between: * **Express Setup (Browser login)**: Opens your browser for secure authentication * **Manual Setup**: Enter your API key directly **Express Setup** uses device code authentication - you'll get a code to enter in your browser, and the CLI will automatically complete the setup once you authenticate. To view your current configuration: ```bash theme={null} runagent whoami ``` To reconfigure: ```bash theme={null} runagent setup --again ``` ## Install RunAgent SDK When RunAgent CLI is installed, the Python SDK is installed as a dependency. You can install it manually as well. ```pip pip theme={null} pip install runagent ``` ```uv uv theme={null} uv add runagent ``` The CLI comes bundled with the Python SDK for seamless local development. Before installing the SDK, ensure you have Node.js 16+. ```npm npm theme={null} npm install runagent ``` ```pnpm pnpm theme={null} pnpm add runagent ``` ```bun bun theme={null} bun add runagent ``` ```yarn yarn theme={null} yarn add runagent ``` The JavaScript SDK comes with full TypeScript support out of the box: * Native async/await and Promise support * Streaming response handling * Type-safe agent invocation Before installing the SDK, ensure you have Rust 1.70+. ```toml Cargo.toml theme={null} [dependencies] runagent = "0.1.0" tokio = { version = "1.0", features = ["full"] } serde_json = "1.0" ``` ```bash cargo theme={null} cargo add runagent ``` The Rust SDK provides: * High-performance async operations * Streaming support with futures * Memory-safe agent interactions Before installing the SDK, ensure you have Go 1.19+. ```bash go theme={null} go get github.com/runagent-dev/runagent-go ``` ```go main.go theme={null} import "github.com/runagent-dev/runagent-go/pkg/client" ``` The Go SDK will provide: * Idiomatic Go interfaces * Goroutine-based streaming * Context-aware operations ## Framework Templates RunAgent provides pre-built templates for popular AI frameworks to get you started quickly: ```bash CLI theme={null} runagent init my_langgraph_agent --langgraph ``` * Pre-configured LangGraph agent setup * Streaming and non-streaming entrypoints * Sample state management examples * Ready-to-deploy configuration ```bash CLI theme={null} runagent init my_langchain_agent --langchain ``` * LangChain agent with tool support * Memory and conversation handling * Streaming response capabilities * Production-ready configuration ```bash CLI theme={null} runagent init my_crew_agent --crewai ``` * Multi-agent crew setup * Task coordination examples * Role-based agent configuration * Collaborative workflow templates ```bash CLI theme={null} runagent init my_custom_agent ``` * Minimal agent template * Basic entrypoint examples * Configuration file template * Development server setup ## Next Steps After installation, you can: 1. **Initialize your first agent**: `runagent init my_agent` 2. **Start the development server**: `runagent serve my_agent` 3. **Connect from your application** using any of our SDKs 4. **Deploy to production** (coming soon): `runagent deploy my_agent` * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Introduction Source: https://docs.run-agent.ai/explanation/introduction Deploy AI agents to production in seconds, not hours RunAgent lets you deploy AI agents in seconds(self-host or in Cloud) and integrate those in any software access them from any language with full streaming support. ## Key Benefits * **Deploy agents in seconds** - Serverless infrastructure with automatic scaling * **Access from Python, JS, Go, Rust and coming more** - Native-feeling SDKs for every language * **Built-in streaming** - Real-time token streaming for responsive applications ## Quick Actions Get started with a complete tutorial Integrate with popular AI frameworks Access agents from any language Hero Light Hero Dark ## The Problem Every AI Developer Faces Suppose you've built an incredible AI agent in Python. It uses **LangGraph for complex reasoning**, leverages **powerful tools**, and produces **amazing results**. Your team loves it! ### Then reality hits: Your whole team is excited to use it! But the **frontend team** needs to access it in JavaScript, your **mobile app team** wants it in Kotlin, your **Unity team** wants it in C#, your **systems team** requires it in Rust. ### The traditional approach? Build separate implementations, REST APIs, WebSocket handlers... **Sound exhausting?** That's because it is! ## What RunAgent Actually Does RunAgent fundamentally changes how AI agent deployment works. Your Python function signatures automatically become API contracts (REST or Streaming) for every supported language. Once `runagent.config.json` of your project points to your Python function, they are automatically converted to corresponding API endpoints, and all language SDKs automatically adapt. No API versioning, no breaking changes. The fastest way to experience the magic is with **RunAgent CLI**: This installs the powerful RunAgent CLI, which is used to deploy and manage your agents. ```bash theme={null} pip install runagent ``` Let's start with a minimal Agent example. ```bash theme={null} runagent init my_agent cd my_agent ``` This creates a new directory with everything you need to get started: ``` my_agent/ ├── main.py # Your agent's functions (already defined!) ├── runagent.config.json # Entrypoints already configured! └── requirements.txt # Dependencies ``` **What `runagent init` created for you:** * A `main.py` file with example agent functions (`mock_response` and `mock_response_stream`) * A `runagent.config.json` file with entrypoints already configured * All the boilerplate needed to make your Python agent accessible from any language The `runagent.config.json` file contains all the configuration for your agent, including: ```json theme={null} { "agent_name": "my_agent", "description": "My AI agent", "framework": "default", "template": "default", "version": "1.0.0", "created_at": "2025-01-15T10:30:00", "agent_id": "f7066c98-0eb2-488c-bb37-a869a93d51ce", "template_source": { "repo_url": "https://github.com/runagent-dev/runagent.git", "author": "runagent-cli", "path": "templates/default/default" }, "agent_architecture": { "entrypoints": [ { "file": "main.py", "module": "mock_response", "tag": "minimal" }, { "file": "main.py", "module": "mock_response_stream", "tag": "minimal_stream" } ] }, "auth_settings": { "type": "none" }, "env_vars": {} } ``` **Key fields:** * `agent_id`: A unique identifier for your agent (generated automatically) * `agent_architecture.entrypoints`: Defines which Python functions are accessible as API endpoints * `auth_settings`: Authentication configuration (defaults to "none") * `env_vars`: Environment variables for your agent Start your agent locally to test it: ```bash theme={null} runagent serve . ``` You will see output similar to: ```bash theme={null} Agent Details: - Agent ID: f7066c98-0eb2-488c-bb37-a869a93d51ce - Host: 127.0.0.1 - Port: 8451 - Framework: default - Status: ready Server running at: http://127.0.0.1:8451 API Documentation: http://127.0.0.1:8451/docs Available endpoints: - POST /api/v1/agents/.../execute/minimal - Run your agent INFO: Uvicorn running on http://127.0.0.1:8451 (Press CTRL+C to quit) ``` That's it! Your agent is now running and accessible through standard REST API as well as all RunAgent SDKs. Using the RunAgent SDKs, you can access your agent from any supported language. You only need the agent ID and the entrypoint tag. Your `mock_response` function now becomes accessible in multiple languages: ```python Python theme={null} from runagent import RunAgentClient # Create a client pointing to your agent ra = RunAgentClient( agent_id="f7066c98-0eb2-488c-bb37-a869a93d51ce", entrypoint_tag="minimal", local=True ) # Call your agent agent_result = ra.run( role="user", message="Analyze the benefits of remote work for software teams" ) print(agent_result) ``` ```javascript JavaScript theme={null} import { RunAgentClient } from 'runagent'; // Create a client pointing to your agent const ra = new RunAgentClient({ agentId: 'f7066c98-0eb2-488c-bb37-a869a93d51ce', entrypointTag: 'minimal', local: true, }); // Call your agent const analysis = await ra.run({ role: "user", message: "Analyze the benefits of remote work for software teams" }); console.log(analysis); ``` ```rust Rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { // Create a client pointing to your agent let client = RunAgentClient::new( "f7066c98-0eb2-488c-bb37-a869a93d51ce", "minimal", true ).await?; // Call your agent let response = client.run(&[ ("role", json!("user")), ("message", json!("Analyze the benefits of remote work for software teams")) ]).await?; println!("Response: {}", response); Ok(()) } ``` ```go Go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { // Create a client pointing to your agent agentClient, err := client.NewWithAddress( "f7066c98-0eb2-488c-bb37-a869a93d51ce", "minimal", true, "localhost", 8453, ) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer agentClient.Close() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() // Call your agent result, err := agentClient.Run(ctx, map[string]interface{}{ "message": "Analyze the benefits of remote work for software teams", "role": "user", }) if err != nil { log.Fatalf("Failed to run agent: %v", err) } fmt.Printf("Result: %v\n", result) } ``` Notice how the same agent logic is accessible from all languages with idiomatic syntax for each. That's the core workflow. You're now ready to **deploy your AI agents** and **integrate them into your applications**. ## From Local Testing to Production in Seconds Once you've tested your agent locally and confirmed everything works, deploying to production is just one command away. **RunAgent Cloud** is the fastest AI agent deployment platform, designed to take your local agent from development to production instantly. No complex infrastructure setup, no deployment headaches. ### Deploy to Production ```bash theme={null} runagent deploy . ``` That's it. Your agent is now live and accessible globally with: * **Automatic scaling** - Handle one request or one million * **Global edge network** - Low latency worldwide * **Zero infrastructure management** - Focus on your agent, not servers * **Production-ready security** - Enterprise-grade isolation and security Your deployed agent gets a production URL and agent ID. Simply update your SDK clients to use the production endpoint: ```python theme={null} # Switch from local to production ra = RunAgentClient( agent_id="your-production-agent-id", entrypoint_tag="minimal", local=False # Now pointing to RunAgent Cloud ) ``` The same code you tested locally now runs in a fully managed production environment. Explore advanced deployment options, environment variables, and monitoring capabilities. ## Agent Framework Support RunAgent works with any Python-based AI agent framework: Deploy your LangGraph agents with built-in state management and workflow execution. Deploy multi-agent CrewAI systems with coordinated execution and monitoring. Deploy Microsoft AutoGen multi-agent conversations with step-by-step execution. Deploy AG2 conversational agents with fact-checking and multi-turn interactions. Deploy Agno AI agents with print response capabilities and streaming support. Deploy Letta memory-enabled agents with persistent conversations and tool integration. Use any Python-based framework by defining simple entrypoint functions. ## Multi-Language SDK Support RunAgent provides native-like access to your deployed agents across multiple languages: Python client with streaming capabilities. Access your agents like local functions with full type safety and Python idioms. Full TypeScript support with streaming and Promise-based APIs. Perfect for modern web applications with async/await patterns. High-performance async SDK with futures and streaming support. Zero-cost abstractions for systems programming and performance-critical applications. Idiomatic Go client with context-aware operations and channel-based streaming. Built for concurrent, scalable applications. We're actively developing SDKs for additional languages including C++, C#, Java, and PHP. Want to contribute or request a specific language? Join our Discord community. ## Real-Time Streaming Across Languages In addition to standard REST API responses, you can also stream your agent responses seamlessly through our SDKs. When your entrypoint streams a response, RunAgent makes it feel native in every language SDK: When you ran `runagent init`, it automatically created both a non-streaming and a streaming function for you. The streaming function is already defined in `main.py` and configured in `runagent.config.json`: ```python main.py theme={null} def mock_response_stream(message, role="user") -> Iterator[str]: """Test the mock agent with streaming responses""" # Your streaming agent logic here # Yield chunks of the response as they're generated for chunk in generate_response_chunks(message): yield chunk ``` The `runagent.config.json` already includes this entrypoint with the tag `minimal_stream` (note the `_stream` suffix, which tells RunAgent this is a streaming endpoint). The tag for a streaming entrypoint must end with a `_stream` suffix. This is how RunAgent identifies it as a streaming endpoint. Start your agent locally (the streaming endpoint is already available): ```bash theme={null} runagent serve . ``` Using the RunAgent SDKs, you can stream responses from your agent. The streaming experience feels natural in each language: ```python Python theme={null} from runagent import RunAgentClient # Create a client with the streaming tag ra = RunAgentClient( agent_id="f7066c98-0eb2-488c-bb37-a869a93d51ce", entrypoint_tag="minimal_stream", local=True ) # Stream the response chunk by chunk for chunk in ra.run( role="user", message="Analyze the benefits of remote work for software teams" ): print(chunk, end='', flush=True) ``` ```javascript JavaScript theme={null} import { RunAgentClient } from 'runagent'; // Create a client with the streaming tag const client = new RunAgentClient({ agentId: 'f7066c98-0eb2-488c-bb37-a869a93d51ce', entrypointTag: 'minimal_stream', local: true }); await client.initialize(); // Stream the response chunk by chunk const stream = await client.runStream({ role: "user", message: "Analyze the benefits of remote work for software teams" }); for await (const chunk of stream) { document.getElementById('output').innerHTML += chunk; } ``` ```rust Rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use futures::StreamExt; #[tokio::main] async fn main() -> Result<(), Box> { // Create a client with the streaming tag let client = RunAgentClient::new( "f7066c98-0eb2-488c-bb37-a869a93d51ce", "minimal_stream", true ).await?; // Stream the response chunk by chunk let mut stream = client.run_stream(&[ ("role", json!("user")), ("message", json!("Analyze the benefits of remote work for software teams")) ]).await?; while let Some(chunk) = stream.next().await { print!("{}", chunk?); } Ok(()) } ``` ```go Go theme={null} package main import ( "context" "fmt" "log" "github.com/runagent-dev/runagent/runagent-go/runagent" ) func main() { // Create a client with the streaming tag client := runagent.NewRunAgentClient(runagent.Config{ AgentID: "f7066c98-0eb2-488c-bb37-a869a93d51ce", EntrypointTag: "minimal_stream", Local: true, }) ctx := context.Background() client.Initialize(ctx) // Stream the response chunk by chunk stream, err := client.RunStream(ctx, map[string]interface{}{ "role": "user", "message": "Analyze the benefits of remote work for software teams", }) if err != nil { log.Fatal(err) } defer stream.Close() for { data, hasMore, err := stream.Next(ctx) if err != nil { log.Fatal(err) } if !hasMore { break } fmt.Printf("%v", data) } } ``` **What's happening behind the scenes**: WebSocket connections, real-time data flow, and native iteration patterns are all handled automatically by RunAgent's infrastructure. ## Next Steps * Head to the [tutorials](/tutorials/deploy-your-first-agent) guide to see the full capabilities * Browse our [framework guides](/how-to/frameworks/langgraph) for LangGraph, CrewAI, and more * Check out [core concepts](/explanation/core-concepts) to understand how it all works - Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) - Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) - Follow us on [X](https://x.com/run_agent) - New here? [Sign up](https://run-agent.ai/dashboard) # Key Concepts at a Glance Source: https://docs.run-agent.ai/explanation/key-concepts-at-a-glance A cheat sheet of what makes RunAgent different in 1 page > TL;DR: RunAgent turns your Python AI agents into multi-language APIs with zero infrastructure headaches. Write once in Python, use everywhere. ## The Magic in 4 Bullets **Sandboxed execution** - Each agent runs in its own secure, isolated environment, preventing resource conflicts and security issues. **Serverless architecture** - Automatically scales from zero to thousands of requests without manual configuration. **Native APIs** - Call the same agent from Python, JavaScript, Go, Rust with language-idiomatic interfaces. **Built-in streaming** - Token-by-token streaming for interactive applications and long-form generation. *** ## Traditional Approach vs RunAgent * Spin up FastAPI server * Build WebSocket handlers for streaming * Set up authentication and rate limiting * Deploy and manage infrastructure * Handle scaling and load balancing * Write SDKs for each language * Manage security and sandboxing * **Result**: Weeks of infrastructure work before you can use your agent * Write Python function * Run `runagent serve .` * Call from any language immediately * **Result**: Agent is live and accessible in seconds *** ## Core Concepts Cheat Sheet | Concept | What It Means | Why It Matters | | --------------- | ------------------------------------------------------ | -------------------------------------------------------- | | **Entrypoints** | Python functions exposed as API endpoints | Your business logic becomes accessible from any language | | **Tags** | Nicknames for your functions (e.g., "chat", "analyze") | Clean, memorable API names instead of function names | | **Streaming** | Real-time token delivery as they are generated | Interactive UIs, progress indicators, better UX | | **Isolation** | Secure, containerized execution environments | Security, resource isolation, fast cold starts | | **SDKs** | Language-native clients that feel like local functions | No need to learn REST APIs or WebSocket protocols | | **Config** | `runagent.config.json` defines your agent's interface | Single source of truth for what your agent can do | *** ## The Developer Experience ```python theme={null} def chat_agent(message: str) -> str: return llm.chat(message) ``` ```bash theme={null} runagent serve . ``` ```python theme={null} # Python result = client.run(message="Hello!") ``` ```javascript theme={null} // JavaScript const result = await client.run({message: "Hello!"}); ``` ```go theme={null} // Go result, _ := client.Run(ctx, map[string]interface{}{"message": "Hello!"}) ``` *** ## What Makes This Different Built specifically for AI agents, not generic microservices. Handles streaming, state, and agent patterns out of the box. No Docker, Kubernetes, or cloud configuration needed. Focus on your agent logic, not deployment. Security, scaling, monitoring, and error handling built-in from day one. Your Python agent becomes a first-class citizen in every supported language ecosystem. *** ## Ready to Dive Deeper? See the magic in action with a 5-minute tutorial Understand entrypoints, streaming, and configuration in detail Learn how RunAgent works under the hood * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Explanation Overview Source: https://docs.run-agent.ai/explanation/overview Concepts and architecture behind RunAgent — the "why" > Understanding the "why" and "how" behind RunAgent. These pages explain the concepts, architecture, and design decisions that make RunAgent work. ## What's in This Section? The Explanation section contains **theory-first, diagram-rich pages** that dive deep into how RunAgent works. Unlike tutorials (which show you how to do things) or how-tos (which solve specific problems), these pages explain the underlying concepts and architecture. **Keep theory here.** Tutorials and how-tos should only include brief callouts. This section is for deep dives into concepts and architecture. ## Start Here Understand the problems RunAgent solves and why it exists Quick cheat sheet of core concepts in one page High-level overview of RunAgent's capabilities and benefits ## Core Concepts & Architecture **Entrypoints, tags, agent lifecycle, and more.** Understand the fundamental building blocks that make RunAgent work. **How RunAgent works under the hood.** Learn about the system architecture, request flow, and component interactions. **Framework integration patterns.** See how RunAgent works with LangGraph, CrewAI, and other AI frameworks. **What RunAgent can do today.** A comprehensive map of current capabilities and upcoming features. ## Production & Operations **Deploying to production.** Scaling, monitoring, error handling, and best practices for production deployments. **Security architecture and best practices.** Learn about sandboxing, authentication, and securing your agents. ## Project Information **What's new and what changed.** Track updates, new features, and breaking changes. **What's coming next.** See planned features, improvements, and the future direction of RunAgent. ## Vision & Future **The future of agent coordination.** How agents will communicate and collaborate with each other. ## How to Use This Section Start with **[Why RunAgent?](./why-runagent)** to understand the problems it solves, then read **[Key Concepts at a Glance](./key-concepts-at-a-glance)** for a quick overview. After that, dive into **[Core Concepts](./core-concepts)** for detailed explanations. Read **[Production Considerations](./production-considerations)** for scaling and monitoring guidance, and **[Security Model](./security)** for security best practices. Check **[Frameworks Overview](./frameworks-overview)** to see how RunAgent integrates with LangGraph, CrewAI, and other frameworks. **[Architecture Overview](./architecture-overview)** explains how RunAgent works internally, including request flow, component interactions, and system design. ## Related Sections Step-by-step guides to build real applications Solutions to specific problems and use cases API documentation and SDK references * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Production Considerations Source: https://docs.run-agent.ai/explanation/production-considerations Essential considerations for deploying RunAgent agents to production **Prerequisites**: Understanding of [Core Concepts](/explanation/core-concepts) and [Architecture Overview](/explanation/architecture-overview) ## Overview Deploying RunAgent agents to production requires careful consideration of performance, reliability, security, and scalability. This guide covers the essential aspects of production deployment. ## Performance Optimization ### 1. **Agent Performance** #### Efficient Entrypoints ```python theme={null} # Good: Efficient, focused function def process_data(data: List[Dict]) -> Dict[str, Any]: """Process data efficiently""" result = {} for item in data: result[item['id']] = item['value'] * 2 return result # Bad: Inefficient, does too much def process_data_slow(data: List[Dict]) -> Dict[str, Any]: """Inefficient processing""" result = {} for item in data: # Unnecessary sleep time.sleep(0.1) # Redundant operations temp = item.copy() temp['processed'] = True result[item['id']] = temp['value'] * 2 return result ``` #### Caching Strategies ```python theme={null} from functools import lru_cache import hashlib @lru_cache(maxsize=1000) def expensive_computation(data_hash: str) -> str: """Cache expensive computations""" # Expensive computation here return f"result_for_{data_hash}" def process_with_cache(data: str) -> str: """Process data with caching""" data_hash = hashlib.md5(data.encode()).hexdigest() return expensive_computation(data_hash) ``` #### Memory Management ```python theme={null} import gc from typing import Iterator def process_large_dataset(data: Iterator[Dict]) -> Iterator[Dict]: """Process large datasets efficiently""" for item in data: # Process item result = process_item(item) yield result # Clean up periodically if random.random() < 0.1: # 10% chance gc.collect() ``` ### 2. **Network Performance** #### Connection Pooling ```python theme={null} from runagent import RunAgentClient import asyncio class OptimizedAgentClient: def __init__(self, agent_id: str, pool_size: int = 10): self.pool = asyncio.Queue(maxsize=pool_size) self.agent_id = agent_id self._initialize_pool() async def _initialize_pool(self): """Initialize connection pool""" for _ in range(self.pool.maxsize): client = RunAgentClient( agent_id=self.agent_id, entrypoint_tag="main", local=False ) await self.pool.put(client) async def get_client(self): """Get client from pool""" return await self.pool.get() async def return_client(self, client): """Return client to pool""" await self.pool.put(client) ``` #### Request Batching ```python theme={null} async def batch_requests(requests: List[Dict]) -> List[Dict]: """Batch multiple requests together""" client = RunAgentClient(agent_id="your_agent", entrypoint_tag="batch") # Send batched request result = await client.run(requests=requests) return result['responses'] ``` ### 3. **Database Optimization** #### Connection Management ```python theme={null} import asyncpg from contextlib import asynccontextmanager class DatabaseManager: def __init__(self, connection_string: str, pool_size: int = 20): self.connection_string = connection_string self.pool_size = pool_size self.pool = None async def initialize(self): """Initialize connection pool""" self.pool = await asyncpg.create_pool( self.connection_string, min_size=5, max_size=self.pool_size ) @asynccontextmanager async def get_connection(self): """Get database connection""" async with self.pool.acquire() as connection: yield connection ``` ## Reliability and Fault Tolerance ### 1. **Error Handling** #### Comprehensive Error Handling ```python theme={null} import logging from typing import Dict, Any, Optional logger = logging.getLogger(__name__) def robust_agent(data: Dict[str, Any]) -> Dict[str, Any]: """Agent with comprehensive error handling""" try: # Validate input if not data.get('message'): return { 'error': 'Missing required field: message', 'status': 'error' } # Process data result = process_data(data) return { 'result': result, 'status': 'success' } except ValueError as e: logger.error(f"Validation error: {e}") return { 'error': f'Validation error: {str(e)}', 'status': 'error' } except Exception as e: logger.error(f"Unexpected error: {e}") return { 'error': 'Internal server error', 'status': 'error' } ``` #### Retry Logic ```python theme={null} import asyncio from typing import Callable, Any async def retry_with_backoff( func: Callable, max_retries: int = 3, base_delay: float = 1.0 ) -> Any: """Retry function with exponential backoff""" for attempt in range(max_retries): try: return await func() except Exception as e: if attempt == max_retries - 1: raise e delay = base_delay * (2 ** attempt) logger.warning(f"Attempt {attempt + 1} failed: {e}. Retrying in {delay}s") await asyncio.sleep(delay) ``` ### 2. **Health Checks** #### Agent Health Monitoring ```python theme={null} import time from typing import Dict, Any class HealthMonitor: def __init__(self): self.start_time = time.time() self.request_count = 0 self.error_count = 0 def health_check(self) -> Dict[str, Any]: """Comprehensive health check""" uptime = time.time() - self.start_time error_rate = self.error_count / max(self.request_count, 1) return { 'status': 'healthy' if error_rate < 0.1 else 'unhealthy', 'uptime': uptime, 'request_count': self.request_count, 'error_count': self.error_count, 'error_rate': error_rate, 'timestamp': time.time() } def record_request(self, success: bool): """Record request for health monitoring""" self.request_count += 1 if not success: self.error_count += 1 ``` ### 3. **Circuit Breaker Pattern** ```python theme={null} import asyncio from enum import Enum from typing import Callable, Any class CircuitState(Enum): CLOSED = "closed" OPEN = "open" HALF_OPEN = "half_open" class CircuitBreaker: def __init__(self, failure_threshold: int = 5, timeout: float = 60.0): self.failure_threshold = failure_threshold self.timeout = timeout self.failure_count = 0 self.last_failure_time = None self.state = CircuitState.CLOSED async def call(self, func: Callable) -> Any: """Call function with circuit breaker protection""" if self.state == CircuitState.OPEN: if time.time() - self.last_failure_time > self.timeout: self.state = CircuitState.HALF_OPEN else: raise Exception("Circuit breaker is open") try: result = await func() self._on_success() return result except Exception as e: self._on_failure() raise e def _on_success(self): """Handle successful call""" self.failure_count = 0 self.state = CircuitState.CLOSED def _on_failure(self): """Handle failed call""" self.failure_count += 1 self.last_failure_time = time.time() if self.failure_count >= self.failure_threshold: self.state = CircuitState.OPEN ``` ## Security Considerations ### 1. **Input Validation** #### Comprehensive Input Validation ```python theme={null} from typing import Dict, Any, List import re def validate_input(data: Dict[str, Any]) -> Dict[str, Any]: """Validate and sanitize input data""" errors = [] # Validate required fields if 'message' not in data: errors.append("Missing required field: message") # Validate message content if 'message' in data: message = data['message'] if not isinstance(message, str): errors.append("Message must be a string") elif len(message) > 10000: errors.append("Message too long") elif not re.match(r'^[a-zA-Z0-9\s.,!?]+$', message): errors.append("Message contains invalid characters") # Validate user_id if 'user_id' in data: user_id = data['user_id'] if not isinstance(user_id, str): errors.append("User ID must be a string") elif not re.match(r'^[a-zA-Z0-9_-]+$', user_id): errors.append("User ID contains invalid characters") if errors: return {'valid': False, 'errors': errors} return {'valid': True, 'data': data} ``` ### 2. **Authentication and Authorization** #### API Key Management ```python theme={null} import hashlib import hmac from typing import Optional class APIKeyManager: def __init__(self, secret_key: str): self.secret_key = secret_key def generate_key(self, user_id: str) -> str: """Generate API key for user""" message = f"user:{user_id}:{int(time.time())}" signature = hmac.new( self.secret_key.encode(), message.encode(), hashlib.sha256 ).hexdigest() return f"{user_id}:{signature}" def validate_key(self, api_key: str) -> Optional[str]: """Validate API key and return user ID""" try: user_id, signature = api_key.split(':', 1) # Validate signature # Implementation details... return user_id except: return None ``` ### 3. **Data Protection** #### Data Encryption ```python theme={null} from cryptography.fernet import Fernet import base64 class DataEncryption: def __init__(self, key: bytes): self.cipher = Fernet(key) def encrypt(self, data: str) -> str: """Encrypt sensitive data""" encrypted = self.cipher.encrypt(data.encode()) return base64.b64encode(encrypted).decode() def decrypt(self, encrypted_data: str) -> str: """Decrypt sensitive data""" encrypted = base64.b64decode(encrypted_data.encode()) return self.cipher.decrypt(encrypted).decode() ``` ## Monitoring and Observability ### 1. **Logging** #### Structured Logging ```python theme={null} import logging import json from datetime import datetime class StructuredLogger: def __init__(self, name: str): self.logger = logging.getLogger(name) self.logger.setLevel(logging.INFO) # Configure JSON formatter handler = logging.StreamHandler() formatter = logging.Formatter('%(message)s') handler.setFormatter(formatter) self.logger.addHandler(handler) def log_request(self, request_id: str, user_id: str, message: str): """Log request with structured data""" self.logger.info(json.dumps({ 'timestamp': datetime.utcnow().isoformat(), 'level': 'INFO', 'event': 'request', 'request_id': request_id, 'user_id': user_id, 'message_length': len(message) })) def log_response(self, request_id: str, status: str, duration: float): """Log response with structured data""" self.logger.info(json.dumps({ 'timestamp': datetime.utcnow().isoformat(), 'level': 'INFO', 'event': 'response', 'request_id': request_id, 'status': status, 'duration_ms': duration * 1000 })) ``` ### 2. **Metrics Collection** #### Custom Metrics ```python theme={null} import time from typing import Dict, Any class MetricsCollector: def __init__(self): self.metrics = { 'request_count': 0, 'error_count': 0, 'total_duration': 0.0, 'last_request_time': None } def record_request(self, duration: float, success: bool): """Record request metrics""" self.metrics['request_count'] += 1 self.metrics['total_duration'] += duration self.metrics['last_request_time'] = time.time() if not success: self.metrics['error_count'] += 1 def get_metrics(self) -> Dict[str, Any]: """Get current metrics""" avg_duration = ( self.metrics['total_duration'] / max(self.metrics['request_count'], 1) ) return { 'request_count': self.metrics['request_count'], 'error_count': self.metrics['error_count'], 'error_rate': ( self.metrics['error_count'] / max(self.metrics['request_count'], 1) ), 'average_duration': avg_duration, 'last_request_time': self.metrics['last_request_time'] } ``` ### 3. **Alerting** #### Alert Configuration ```python theme={null} class AlertManager: def __init__(self, alert_thresholds: Dict[str, float]): self.thresholds = alert_thresholds self.alerts_sent = set() def check_metrics(self, metrics: Dict[str, Any]): """Check metrics against thresholds""" # Check error rate if metrics['error_rate'] > self.thresholds['error_rate']: self._send_alert('high_error_rate', metrics) # Check response time if metrics['average_duration'] > self.thresholds['response_time']: self._send_alert('slow_response', metrics) def _send_alert(self, alert_type: str, metrics: Dict[str, Any]): """Send alert if not already sent""" alert_key = f"{alert_type}_{int(time.time() / 300)}" # 5-minute buckets if alert_key not in self.alerts_sent: # Send alert (email, Slack, etc.) self._send_notification(alert_type, metrics) self.alerts_sent.add(alert_key) ``` ## Scalability ### 1. **Horizontal Scaling** #### Load Balancing ```python theme={null} import random from typing import List class LoadBalancer: def __init__(self, agent_instances: List[str]): self.instances = agent_instances self.current_index = 0 def get_instance(self) -> str: """Get next available instance""" instance = self.instances[self.current_index] self.current_index = (self.current_index + 1) % len(self.instances) return instance def get_random_instance(self) -> str: """Get random instance""" return random.choice(self.instances) ``` ### 2. **Auto-scaling** #### Scaling Logic ```python theme={null} class AutoScaler: def __init__(self, min_instances: int = 1, max_instances: int = 10): self.min_instances = min_instances self.max_instances = max_instances self.current_instances = min_instances def should_scale_up(self, metrics: Dict[str, Any]) -> bool: """Determine if should scale up""" return ( metrics['request_count'] > 1000 and metrics['average_duration'] > 2.0 and self.current_instances < self.max_instances ) def should_scale_down(self, metrics: Dict[str, Any]) -> bool: """Determine if should scale down""" return ( metrics['request_count'] < 100 and metrics['average_duration'] < 0.5 and self.current_instances > self.min_instances ) ``` ## Deployment Best Practices ### 1. **Environment Configuration** #### Environment-Specific Settings ```python theme={null} import os from typing import Dict, Any class EnvironmentConfig: def __init__(self): self.env = os.getenv('ENVIRONMENT', 'development') self.config = self._load_config() def _load_config(self) -> Dict[str, Any]: """Load environment-specific configuration""" configs = { 'development': { 'debug': True, 'log_level': 'DEBUG', 'max_instances': 1, 'timeout': 30 }, 'staging': { 'debug': False, 'log_level': 'INFO', 'max_instances': 3, 'timeout': 60 }, 'production': { 'debug': False, 'log_level': 'WARNING', 'max_instances': 10, 'timeout': 120 } } return configs.get(self.env, configs['development']) ``` ### 2. **Health Checks** #### Comprehensive Health Checks ```python theme={null} async def health_check() -> Dict[str, Any]: """Comprehensive health check""" checks = { 'database': await check_database(), 'cache': await check_cache(), 'external_apis': await check_external_apis(), 'disk_space': check_disk_space(), 'memory': check_memory() } overall_status = 'healthy' if all(checks.values()) else 'unhealthy' return { 'status': overall_status, 'checks': checks, 'timestamp': datetime.utcnow().isoformat() } ``` ## Next Steps Learn about RunAgent's security model Deploy your agents to the cloud Learn advanced production patterns Set up comprehensive monitoring **🎉 Great work!** You now understand the essential considerations for deploying RunAgent agents to production. These practices will help you build reliable, scalable, and secure AI agent systems! * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Quickstart Map Source: https://docs.run-agent.ai/explanation/quickstart-map Visual navigation guide to find exactly what you need > Not sure where to start? This page guides you to the right content based on your goals and experience level. ## 🎯 Choose Your Path **Perfect for**: First-time users, quick evaluation **Time**: 5 minutes **Outcome**: Working agent accessible from any language **Perfect for**: Technical evaluation, architecture review **Time**: 10-15 minutes **Outcome**: Deep understanding of concepts and architecture **Perfect for**: Production integration, specific use cases **Time**: 30-60 minutes **Outcome**: Working integration with your tech stack **Perfect for**: Comprehensive evaluation, feature discovery **Time**: 15-30 minutes **Outcome**: Complete picture of what RunAgent offers *** ## 👤 Based on Your Role **Start here:** * [Deploy your first agent](/tutorials/deploy-your-first-agent) (5 min) * [Core concepts](/explanation/core-concepts) (10 min) * [SDK reference](/reference/sdk/overview) (as needed) **Then explore:** * [Framework integrations](/how-to/frameworks/langgraph) * [Testing agents](/how-to/advanced-tasks) * [Production deployment](/runagent-cloud/cloud-deployment) **Start here:** * [Why RunAgent?](/explanation/why-runagent) (5 min) * [Feature overview](/explanation/feature-overview) (10 min) * [Architecture overview](/explanation/architecture-overview) (10 min) **Then explore:** * [Real-world examples](/resources/examples) * [Production considerations](/explanation/production-considerations) * [Roadmap](/explanation/roadmap) **Start here:** * [Core concepts](/explanation/core-concepts) (10 min) * [Architecture overview](/explanation/architecture-overview) (15 min) * [Deploy your first agent](/tutorials/deploy-your-first-agent) (5 min) **Then explore:** * [Framework integrations](/how-to/frameworks/langgraph) * [Advanced patterns](/how-to/advanced-tasks) * [Security model](/explanation/security) **Start here:** * [Architecture overview](/explanation/architecture-overview) (15 min) * [Production considerations](/explanation/production-considerations) (10 min) * [Security model](/explanation/security) (10 min) **Then explore:** * [Cloud deployment](/runagent-cloud/cloud-deployment) * [CI/CD integration](/how-to/advanced-tasks) * [Observability](/how-to/advanced-tasks) *** ## 🎯 Based on Your Use Case **Tutorial**: [Customer Support Agent](/tutorials/customer-support-agent) **How-to**: [Streaming responses](/how-to/advanced-tasks) **Reference**: [JavaScript SDK](/sdk/javascript/getting-started) **Tutorial**: [Internal Q\&A Agent](/tutorials/internal-qa-agent) **How-to**: [LangGraph integration](/how-to/frameworks/langgraph) **Reference**: [Python SDK](/sdk/python/getting-started) **Tutorial**: [Multi-Language Wrapper](/tutorials/multi-language-wrapper) **How-to**: [Call from different languages](/how-to/call-from-python) **Reference**: [SDK Overview](/sdk/overview) **How-to**: [CrewAI integration](/how-to/frameworks/crewai) **Explanation**: [Architecture overview](/explanation/architecture-overview) **Reference**: [API Reference](/api-reference/introduction) *** ## 📊 Experience Level Guide **Recommended path:** 1. [Installation](/explanation/installation) (5 min) 2. [Deploy your first agent](/tutorials/deploy-your-first-agent) (5 min) 3. [Core concepts](/explanation/core-concepts) (10 min) 4. [Customer support agent](/tutorials/customer-support-agent) (15 min) **Skip for now:** * Advanced configuration * Production deployment * Custom frameworks **Recommended path:** 1. [Why RunAgent?](/explanation/why-runagent) (5 min) 2. [Feature overview](/explanation/feature-overview) (10 min) 3. [Multi-language wrapper](/tutorials/multi-language-wrapper) (15 min) 4. [Framework integrations](/how-to/frameworks/langgraph) (20 min) **Then explore:** * Production deployment * Advanced patterns * Security considerations **Recommended path:** 1. [Architecture overview](/explanation/architecture-overview) (15 min) 2. [Production considerations](/explanation/production-considerations) (10 min) 3. [Security model](/explanation/security) (10 min) 4. [Cloud deployment](/runagent-cloud/cloud-deployment) (30 min) **Focus on:** * Production readiness * Security and compliance * Performance optimization * Monitoring and observability *** ## 🚨 Common Scenarios **Go to**: [Troubleshooting](/resources/troubleshooting) **Or**: [Installation guide](/explanation/installation) **Quick fix**: Check [FAQ](/resources/faq) **Go to**: [Call from Python](/how-to/call-from-python) **Or**: [SDK Reference](/sdk/overview) **Quick fix**: Check language-specific guides **Go to**: [Cloud deployment](/runagent-cloud/cloud-deployment) **Or**: [Production considerations](/explanation/production-considerations) **Quick fix**: Check [Advanced tasks](/how-to/advanced-tasks) **Go to**: [Frameworks overview](/explanation/frameworks-overview) **Or**: [How-to guides](/how-to/frameworks/langgraph) **Quick fix**: Check framework-specific tutorials *** ## 🎯 Still Not Sure? The fastest way to see RunAgent in action Start from the beginning and explore Get help from other developers **Pro tip**: Most users find what they need within 2-3 clicks from this page. If you are still lost, the [troubleshooting guide](/resources/troubleshooting) covers the most common issues. # Roadmap Source: https://docs.run-agent.ai/explanation/roadmap RunAgent development roadmap and upcoming features **Last Updated**: January 2024 ## Overview RunAgent is continuously evolving to provide the best possible experience for AI agent deployment and multi-language access. This roadmap outlines our planned features and improvements. ## Current Status ### ✅ **Completed Features** * **Core Platform**: Basic agent deployment and execution * **Multi-Language SDKs**: Python, JavaScript, Go, Rust * **Streaming Support**: Real-time response streaming * **Firecracker Integration**: Secure microVM execution * **Auto-scaling**: Automatic agent scaling based on demand * **REST API**: Complete REST API for agent interaction * **WebSocket Support**: Real-time communication * **Configuration System**: Flexible agent configuration * **Error Handling**: Comprehensive error handling and reporting * **Monitoring**: Basic monitoring and logging ## Short-term Roadmap (Q1 2024) ### 🛠️ **In Development** #### Rate Limiting * **Client-based Rate Limiting**: Per-client request rate limits * **Agent-based Rate Limiting**: Per-agent request rate limits * **Dynamic Rate Limiting**: Adaptive rate limiting based on system load * **Rate Limit Headers**: Standard rate limit headers in responses #### Agent Authentication * **API Key Management**: Enhanced API key management system * **Role-based Access Control**: Fine-grained permission system * **Agent-level Authentication**: Individual agent authentication * **OAuth Integration**: OAuth 2.0 support for enterprise users #### Enhanced Monitoring * **Real-time Metrics**: Live performance metrics dashboard * **Alerting System**: Configurable alerts for system issues * **Distributed Tracing**: End-to-end request tracing * **Performance Analytics**: Detailed performance analysis ### 🔜 **Planned for Q1** #### Advanced Caching * **Response Caching**: Intelligent response caching * **Cache Invalidation**: Smart cache invalidation strategies * **Distributed Caching**: Multi-instance cache coordination * **Cache Analytics**: Cache hit/miss analytics #### Improved SDKs * **TypeScript Definitions**: Complete TypeScript support * **Async/Await Patterns**: Enhanced async patterns * **Error Recovery**: Automatic error recovery mechanisms * **Connection Pooling**: Advanced connection pooling ## Medium-term Roadmap (Q2-Q3 2024) ### 🚀 **Major Features** #### Agent Memory * **Persistent Memory**: Long-term memory for agents * **Memory Management**: Efficient memory storage and retrieval * **Memory Sharing**: Shared memory between agent instances * **Memory Analytics**: Memory usage analytics and optimization #### Agent-to-Agent Communication * **Inter-Agent Messaging**: Direct agent-to-agent communication * **Event System**: Event-driven agent communication * **Agent Discovery**: Automatic agent discovery and registration * **Communication Protocols**: Standardized communication protocols #### Advanced Frameworks * **LangChain Integration**: Enhanced LangChain support * **Hugging Face Integration**: Hugging Face model integration * **Custom Runtimes**: Support for additional programming languages * **Framework Templates**: Pre-built framework templates #### Enterprise Features * **Multi-tenancy**: Multi-tenant architecture support * **Enterprise SSO**: Single sign-on integration * **Audit Logging**: Comprehensive audit logging * **Compliance**: SOC 2, GDPR, and HIPAA compliance ### 🔧 **Infrastructure Improvements** #### Scalability * **Kubernetes Integration**: Native Kubernetes support * **Service Mesh**: Istio integration for advanced networking * **Edge Computing**: Edge deployment capabilities * **Global Distribution**: Multi-region deployment #### Performance * **GPU Support**: GPU-accelerated agent execution * **Optimized Serialization**: Faster data serialization * **Connection Optimization**: Advanced connection management * **Resource Optimization**: Intelligent resource allocation ## Long-term Roadmap (Q4 2024+) ### 🌟 **Vision Features** #### AI-Powered Platform * **Intelligent Scaling**: AI-driven auto-scaling * **Predictive Analytics**: Predictive performance analytics * **Anomaly Detection**: Automatic anomaly detection * **Self-healing**: Self-healing system capabilities #### Advanced Agent Capabilities * **Agent Composition**: Composable agent architectures * **Agent Orchestration**: Complex agent workflows * **Agent Learning**: Self-improving agents * **Agent Marketplace**: Public agent marketplace #### Platform Ecosystem * **Plugin System**: Extensible plugin architecture * **Third-party Integrations**: Rich third-party integrations * **Community Features**: Community-driven features * **Open Source**: Open source platform components ## Feature Status Legend * ✅ **Completed**: Feature is fully implemented and available * 🛠️ **In Development**: Feature is currently being developed * 🔜 **Planned**: Feature is planned for upcoming release * 🚀 **Major Feature**: Significant new capability * 🔧 **Infrastructure**: Platform infrastructure improvement * 🌟 **Vision**: Long-term vision feature ## Release Schedule ### **Version 1.0** (Q1 2024) * Rate limiting * Agent authentication * Enhanced monitoring * Advanced caching ### **Version 1.1** (Q2 2024) * Agent memory * Agent-to-agent communication * Advanced frameworks * Enterprise features ### **Version 1.2** (Q3 2024) * Kubernetes integration * GPU support * Edge computing * Global distribution ### **Version 2.0** (Q4 2024) * AI-powered platform * Advanced agent capabilities * Platform ecosystem * Open source components ## Community Feedback We value community input and feedback. Here's how you can contribute: ### **Feature Requests** * **GitHub Issues**: Submit feature requests on GitHub * **Discord Community**: Discuss features in our Discord * **User Surveys**: Participate in our user surveys * **Beta Testing**: Join our beta testing program ### **Priority Factors** * **User Demand**: Number of users requesting the feature * **Technical Feasibility**: How feasible the feature is to implement * **Strategic Alignment**: How well it aligns with our vision * **Resource Requirements**: Development effort required ## Getting Involved ### **Contributing** * **Code Contributions**: Contribute to the codebase * **Documentation**: Help improve documentation * **Testing**: Help test new features * **Feedback**: Provide feedback on features ### **Beta Access** * **Early Access**: Get early access to new features * **Feedback Loop**: Provide feedback during development * **Influence Direction**: Help shape feature development * **Community Recognition**: Get recognized for contributions ## Migration Planning ### **Backward Compatibility** * **API Stability**: Maintain API stability across versions * **Migration Guides**: Provide migration guides for breaking changes * **Deprecation Warnings**: Give advance notice of deprecated features * **Support Timeline**: Maintain support for older versions ### **Upgrade Paths** * **Incremental Updates**: Incremental upgrade paths * **Automated Migration**: Automated migration tools * **Manual Migration**: Manual migration guides * **Support**: Migration support and assistance ## Success Metrics ### **Platform Metrics** * **Agent Deployments**: Number of agents deployed * **API Calls**: Number of API calls processed * **User Satisfaction**: User satisfaction scores * **Performance**: System performance metrics ### **Feature Adoption** * **Feature Usage**: How often features are used * **User Feedback**: User feedback on features * **Performance Impact**: Impact on system performance * **Bug Reports**: Number of bugs reported ## Next Steps Learn about currently available features Join our community and contribute Submit feature requests and feedback Join our beta testing program **🎉 Thank you for your interest in RunAgent's roadmap!** We're committed to building the best possible platform for AI agent deployment. Your feedback and contributions help shape our direction! * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Security Source: https://docs.run-agent.ai/explanation/security RunAgent security model and best practices **Prerequisites**: Understanding of [Core Concepts](/explanation/core-concepts) and [Architecture Overview](/explanation/architecture-overview) ## Overview RunAgent is designed with security as a fundamental principle. This guide covers RunAgent's security model, best practices, and how to secure your agents and data. ## Security Architecture ### 1. **Multi-Layer Security Model** ```mermaid theme={null} graph TB subgraph "Security Layers" AUTH[Authentication] AUTHZ[Authorization] RATE[Rate Limiting] VALID[Input Validation] SANDBOX[Sandboxing] ISOLATION[Process Isolation] ENCRYPT[Encryption] end subgraph "Client Request" REQ[HTTP/WebSocket Request] end subgraph "Agent Execution" AGENT[Python Agent] end REQ --> AUTH AUTH --> AUTHZ AUTHZ --> RATE RATE --> VALID VALID --> SANDBOX SANDBOX --> ISOLATION ISOLATION --> ENCRYPT ENCRYPT --> AGENT ``` ### 2. **Security Boundaries** * **Network Boundary**: API Gateway with authentication and rate limiting * **Process Boundary**: Firecracker microVMs with complete isolation * **Data Boundary**: Encrypted data transmission and storage * **Code Boundary**: Sandboxed execution environment ## Authentication and Authorization ### 1. **API Key Management** #### API Key Structure ```python theme={null} import hashlib import hmac import time from typing import Optional class APIKeyManager: def __init__(self, secret_key: str): self.secret_key = secret_key def generate_key(self, user_id: str, permissions: List[str]) -> str: """Generate API key with permissions""" timestamp = int(time.time()) message = f"{user_id}:{':'.join(permissions)}:{timestamp}" signature = hmac.new( self.secret_key.encode(), message.encode(), hashlib.sha256 ).hexdigest() return f"{user_id}:{signature}:{timestamp}" def validate_key(self, api_key: str) -> Optional[Dict[str, Any]]: """Validate API key and return user info""" try: user_id, signature, timestamp = api_key.split(':') # Check if key is expired (24 hours) if time.time() - int(timestamp) > 86400: return None # Validate signature expected_message = f"{user_id}:{timestamp}" expected_signature = hmac.new( self.secret_key.encode(), expected_message.encode(), hashlib.sha256 ).hexdigest() if hmac.compare_digest(signature, expected_signature): return { 'user_id': user_id, 'permissions': ['read', 'write'], # Default permissions 'expires_at': int(timestamp) + 86400 } return None except: return None ``` #### Role-Based Access Control ```python theme={null} from enum import Enum from typing import List, Dict, Any class Permission(Enum): READ = "read" WRITE = "write" ADMIN = "admin" STREAM = "stream" class Role: def __init__(self, name: str, permissions: List[Permission]): self.name = name self.permissions = permissions def has_permission(self, permission: Permission) -> bool: return permission in self.permissions class User: def __init__(self, user_id: str, role: Role): self.user_id = user_id self.role = role def can_access(self, permission: Permission) -> bool: return self.role.has_permission(permission) # Define roles ROLES = { 'viewer': Role('viewer', [Permission.READ]), 'user': Role('user', [Permission.READ, Permission.WRITE]), 'admin': Role('admin', [Permission.READ, Permission.WRITE, Permission.ADMIN]), 'streamer': Role('streamer', [Permission.READ, Permission.STREAM]) } ``` ### 2. **OAuth 2.0 Integration** #### OAuth Provider Integration ```python theme={null} import requests from typing import Optional, Dict, Any class OAuthProvider: def __init__(self, client_id: str, client_secret: str, provider_url: str): self.client_id = client_id self.client_secret = client_secret self.provider_url = provider_url def validate_token(self, access_token: str) -> Optional[Dict[str, Any]]: """Validate OAuth access token""" try: response = requests.get( f"{self.provider_url}/userinfo", headers={'Authorization': f'Bearer {access_token}'} ) if response.status_code == 200: user_info = response.json() return { 'user_id': user_info.get('sub'), 'email': user_info.get('email'), 'name': user_info.get('name'), 'permissions': self._get_permissions(user_info) } return None except: return None def _get_permissions(self, user_info: Dict[str, Any]) -> List[str]: """Extract permissions from user info""" # Implementation depends on OAuth provider return ['read', 'write'] ``` ## Input Validation and Sanitization ### 1. **Comprehensive Input Validation** ```python theme={null} import re import json from typing import Dict, Any, List, Optional from dataclasses import dataclass @dataclass class ValidationRule: field: str required: bool = False max_length: Optional[int] = None pattern: Optional[str] = None data_type: type = str class InputValidator: def __init__(self, rules: List[ValidationRule]): self.rules = {rule.field: rule for rule in rules} def validate(self, data: Dict[str, Any]) -> Dict[str, Any]: """Validate input data against rules""" errors = [] sanitized_data = {} for field, rule in self.rules.items(): value = data.get(field) # Check required fields if rule.required and value is None: errors.append(f"Required field '{field}' is missing") continue if value is None: continue # Check data type if not isinstance(value, rule.data_type): errors.append(f"Field '{field}' must be of type {rule.data_type.__name__}") continue # Check max length if rule.max_length and len(str(value)) > rule.max_length: errors.append(f"Field '{field}' exceeds maximum length of {rule.max_length}") continue # Check pattern if rule.pattern and not re.match(rule.pattern, str(value)): errors.append(f"Field '{field}' does not match required pattern") continue # Sanitize value sanitized_value = self._sanitize_value(value, rule.data_type) sanitized_data[field] = sanitized_value if errors: return { 'valid': False, 'errors': errors, 'data': None } return { 'valid': True, 'errors': [], 'data': sanitized_data } def _sanitize_value(self, value: Any, data_type: type) -> Any: """Sanitize value based on data type""" if data_type == str: # Remove potentially dangerous characters return re.sub(r'[<>"\']', '', str(value)) elif data_type == int: return int(value) elif data_type == float: return float(value) elif data_type == bool: return bool(value) else: return value # Define validation rules VALIDATION_RULES = [ ValidationRule('message', required=True, max_length=10000), ValidationRule('user_id', required=True, pattern=r'^[a-zA-Z0-9_-]+$'), ValidationRule('context', required=False, data_type=dict), ValidationRule('stream', required=False, data_type=bool) ] ``` ### 2. **SQL Injection Prevention** ```python theme={null} import sqlite3 from typing import List, Dict, Any class SecureDatabase: def __init__(self, db_path: str): self.db_path = db_path def execute_query(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]: """Execute query with parameterized statements""" with sqlite3.connect(self.db_path) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute(query, params) return [dict(row) for row in cursor.fetchall()] def get_user_data(self, user_id: str) -> List[Dict[str, Any]]: """Get user data safely""" # Use parameterized query to prevent SQL injection query = "SELECT * FROM users WHERE user_id = ?" return self.execute_query(query, (user_id,)) ``` ### 3. **XSS Prevention** ```python theme={null} import html import re from typing import str class XSSPrevention: @staticmethod def sanitize_html(text: str) -> str: """Sanitize HTML to prevent XSS""" # Escape HTML characters sanitized = html.escape(text) # Remove script tags sanitized = re.sub(r'', '', sanitized, flags=re.DOTALL) # Remove javascript: URLs sanitized = re.sub(r'javascript:', '', sanitized, flags=re.IGNORECASE) return sanitized @staticmethod def validate_url(url: str) -> bool: """Validate URL to prevent malicious redirects""" # Only allow http and https protocols if not re.match(r'^https?://', url): return False # Check for suspicious patterns suspicious_patterns = [ r'javascript:', r'data:', r'vbscript:', r'file:' ] for pattern in suspicious_patterns: if re.search(pattern, url, re.IGNORECASE): return False return True ``` ## Data Encryption ### 1. **Data in Transit** #### TLS/SSL Configuration ```python theme={null} import ssl from typing import Dict, Any class TLSConfig: def __init__(self): self.ssl_context = ssl.create_default_context() self.ssl_context.check_hostname = True self.ssl_context.verify_mode = ssl.CERT_REQUIRED def get_secure_context(self) -> ssl.SSLContext: """Get secure SSL context""" return self.ssl_context def configure_ciphers(self, ciphers: List[str]): """Configure allowed ciphers""" self.ssl_context.set_ciphers(':'.join(ciphers)) def set_certificate(self, cert_file: str, key_file: str): """Set certificate and key files""" self.ssl_context.load_cert_chain(cert_file, key_file) ``` ### 2. **Data at Rest** #### Encryption for Sensitive Data ```python theme={null} from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC import base64 import os class DataEncryption: def __init__(self, password: str): self.key = self._derive_key(password) self.cipher = Fernet(self.key) def _derive_key(self, password: str) -> bytes: """Derive encryption key from password""" salt = os.urandom(16) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, ) key = base64.urlsafe_b64encode(kdf.derive(password.encode())) return key def encrypt(self, data: str) -> str: """Encrypt sensitive data""" encrypted = self.cipher.encrypt(data.encode()) return base64.b64encode(encrypted).decode() def decrypt(self, encrypted_data: str) -> str: """Decrypt sensitive data""" encrypted = base64.b64decode(encrypted_data.encode()) return self.cipher.decrypt(encrypted).decode() ``` ## Sandboxing and Isolation ### 1. **Firecracker Security Model** #### Resource Limits ```python theme={null} from typing import Dict, Any class ResourceLimits: def __init__(self): self.limits = { 'cpu_quota': 100000, # CPU quota in microseconds 'memory_limit': 512 * 1024 * 1024, # 512MB memory limit 'disk_limit': 1024 * 1024 * 1024, # 1GB disk limit 'network_bandwidth': 10 * 1024 * 1024, # 10MB/s network limit 'max_processes': 100, 'max_file_descriptors': 1024 } def get_limits(self) -> Dict[str, Any]: """Get resource limits for agent""" return self.limits def apply_limits(self, agent_id: str): """Apply resource limits to agent""" # Implementation would apply limits to Firecracker VM pass ``` #### Network Isolation ```python theme={null} class NetworkIsolation: def __init__(self): self.allowed_hosts = [ 'api.openai.com', 'api.anthropic.com', 'api.cohere.ai' ] self.blocked_ports = [22, 23, 25, 53, 80, 443, 993, 995] def is_allowed_host(self, host: str) -> bool: """Check if host is allowed""" return host in self.allowed_hosts def is_allowed_port(self, port: int) -> bool: """Check if port is allowed""" return port not in self.blocked_ports def create_network_policy(self, agent_id: str) -> Dict[str, Any]: """Create network policy for agent""" return { 'agent_id': agent_id, 'allowed_hosts': self.allowed_hosts, 'blocked_ports': self.blocked_ports, 'max_connections': 10 } ``` ### 2. **Process Isolation** #### Sandbox Configuration ```python theme={null} import subprocess from typing import List, Dict, Any class SandboxConfig: def __init__(self): self.restrictions = { 'no_network': False, 'no_file_system': False, 'no_process_creation': True, 'no_system_calls': True, 'read_only_root': True } def create_sandbox(self, agent_id: str) -> Dict[str, Any]: """Create sandbox configuration for agent""" return { 'agent_id': agent_id, 'restrictions': self.restrictions, 'working_directory': f'/tmp/agent_{agent_id}', 'environment_variables': { 'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': f'/tmp/agent_{agent_id}' } } def execute_in_sandbox(self, command: List[str], sandbox_config: Dict[str, Any]) -> subprocess.CompletedProcess: """Execute command in sandbox""" # Implementation would use Firecracker or similar pass ``` ## Rate Limiting and DDoS Protection ### 1. **Rate Limiting Implementation** ```python theme={null} import time from typing import Dict, Any from collections import defaultdict, deque class RateLimiter: def __init__(self, max_requests: int = 100, window_seconds: int = 60): self.max_requests = max_requests self.window_seconds = window_seconds self.requests = defaultdict(deque) def is_allowed(self, client_id: str) -> bool: """Check if client is within rate limit""" now = time.time() client_requests = self.requests[client_id] # Remove old requests outside window while client_requests and client_requests[0] <= now - self.window_seconds: client_requests.popleft() # Check if under limit if len(client_requests) < self.max_requests: client_requests.append(now) return True return False def get_remaining_requests(self, client_id: str) -> int: """Get remaining requests for client""" now = time.time() client_requests = self.requests[client_id] # Remove old requests while client_requests and client_requests[0] <= now - self.window_seconds: client_requests.popleft() return max(0, self.max_requests - len(client_requests)) ``` ### 2. **DDoS Protection** ```python theme={null} class DDoSProtection: def __init__(self): self.suspicious_ips = set() self.blocked_ips = set() self.request_counts = defaultdict(int) self.last_reset = time.time() def check_request(self, ip: str, user_agent: str) -> bool: """Check if request should be allowed""" now = time.time() # Reset counters every minute if now - self.last_reset > 60: self.request_counts.clear() self.last_reset = now # Check if IP is blocked if ip in self.blocked_ips: return False # Count requests from this IP self.request_counts[ip] += 1 # Check for suspicious patterns if self._is_suspicious(ip, user_agent): self.suspicious_ips.add(ip) return False # Block IP if too many requests if self.request_counts[ip] > 1000: # 1000 requests per minute self.blocked_ips.add(ip) return False return True def _is_suspicious(self, ip: str, user_agent: str) -> bool: """Check for suspicious request patterns""" # Check for common bot patterns bot_patterns = [ 'python-requests', 'curl', 'wget', 'bot', 'crawler' ] for pattern in bot_patterns: if pattern.lower() in user_agent.lower(): return True return False ``` ## Security Monitoring ### 1. **Security Event Logging** ```python theme={null} import logging import json from datetime import datetime from typing import Dict, Any class SecurityLogger: def __init__(self): self.logger = logging.getLogger('security') self.logger.setLevel(logging.INFO) # Configure security log handler handler = logging.FileHandler('security.log') formatter = logging.Formatter('%(message)s') handler.setFormatter(formatter) self.logger.addHandler(handler) def log_auth_failure(self, ip: str, user_id: str, reason: str): """Log authentication failure""" self.logger.warning(json.dumps({ 'timestamp': datetime.utcnow().isoformat(), 'event': 'auth_failure', 'ip': ip, 'user_id': user_id, 'reason': reason })) def log_rate_limit_exceeded(self, ip: str, user_id: str, limit: int): """Log rate limit exceeded""" self.logger.warning(json.dumps({ 'timestamp': datetime.utcnow().isoformat(), 'event': 'rate_limit_exceeded', 'ip': ip, 'user_id': user_id, 'limit': limit })) def log_suspicious_activity(self, ip: str, activity: str, details: Dict[str, Any]): """Log suspicious activity""" self.logger.error(json.dumps({ 'timestamp': datetime.utcnow().isoformat(), 'event': 'suspicious_activity', 'ip': ip, 'activity': activity, 'details': details })) ``` ### 2. **Security Alerts** ```python theme={null} class SecurityAlertManager: def __init__(self): self.alert_thresholds = { 'auth_failures': 10, # 10 failures per minute 'rate_limit_exceeded': 5, # 5 rate limit violations per minute 'suspicious_activity': 3 # 3 suspicious activities per minute } self.alert_counts = defaultdict(int) self.last_reset = time.time() def check_alerts(self, event_type: str, ip: str): """Check if alert should be triggered""" now = time.time() # Reset counters every minute if now - self.last_reset > 60: self.alert_counts.clear() self.last_reset = now # Count events key = f"{event_type}:{ip}" self.alert_counts[key] += 1 # Check threshold if self.alert_counts[key] >= self.alert_thresholds.get(event_type, 0): self._send_alert(event_type, ip, self.alert_counts[key]) def _send_alert(self, event_type: str, ip: str, count: int): """Send security alert""" # Implementation would send alert via email, Slack, etc. print(f"SECURITY ALERT: {event_type} from {ip} ({count} occurrences)") ``` ## Compliance and Auditing ### 1. **Audit Trail** ```python theme={null} class AuditTrail: def __init__(self): self.audit_log = [] def log_action(self, user_id: str, action: str, resource: str, details: Dict[str, Any]): """Log user action for auditing""" audit_entry = { 'timestamp': datetime.utcnow().isoformat(), 'user_id': user_id, 'action': action, 'resource': resource, 'details': details, 'ip_address': self._get_client_ip(), 'user_agent': self._get_user_agent() } self.audit_log.append(audit_entry) def get_audit_log(self, user_id: str = None, start_date: str = None, end_date: str = None) -> List[Dict[str, Any]]: """Get audit log with optional filters""" filtered_log = self.audit_log if user_id: filtered_log = [entry for entry in filtered_log if entry['user_id'] == user_id] if start_date: filtered_log = [entry for entry in filtered_log if entry['timestamp'] >= start_date] if end_date: filtered_log = [entry for entry in filtered_log if entry['timestamp'] <= end_date] return filtered_log ``` ### 2. **Data Retention Policy** ```python theme={null} class DataRetentionManager: def __init__(self, retention_days: int = 90): self.retention_days = retention_days def should_retain(self, timestamp: str) -> bool: """Check if data should be retained""" data_time = datetime.fromisoformat(timestamp) cutoff_time = datetime.utcnow() - timedelta(days=self.retention_days) return data_time > cutoff_time def cleanup_old_data(self, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Remove old data based on retention policy""" return [entry for entry in data if self.should_retain(entry['timestamp'])] ``` ## Security Best Practices ### 1. **Agent Development** ```python theme={null} # Secure agent development practices def secure_agent(data: Dict[str, Any]) -> Dict[str, Any]: """Example of secure agent implementation""" # 1. Validate input validator = InputValidator(VALIDATION_RULES) validation_result = validator.validate(data) if not validation_result['valid']: return { 'error': 'Invalid input', 'details': validation_result['errors'] } # 2. Sanitize data sanitized_data = validation_result['data'] # 3. Process data securely try: result = process_data_securely(sanitized_data) # 4. Log action audit_trail.log_action( user_id=sanitized_data['user_id'], action='agent_execution', resource='data_processing', details={'input_size': len(sanitized_data['message'])} ) return { 'result': result, 'status': 'success' } except Exception as e: # 5. Log error securely security_logger.log_suspicious_activity( ip=get_client_ip(), activity='agent_error', details={'error': str(e)} ) return { 'error': 'Processing failed', 'status': 'error' } ``` ### 2. **Configuration Security** ```python theme={null} # Secure configuration management class SecureConfig: def __init__(self): self.config = self._load_secure_config() def _load_secure_config(self) -> Dict[str, Any]: """Load configuration securely""" return { 'api_key': os.getenv('RUNAGENT_API_KEY'), 'database_url': os.getenv('DATABASE_URL'), 'encryption_key': os.getenv('ENCRYPTION_KEY'), 'jwt_secret': os.getenv('JWT_SECRET') } def get_config(self, key: str) -> str: """Get configuration value securely""" if key not in self.config: raise ValueError(f"Configuration key '{key}' not found") return self.config[key] ``` ## Next Steps Learn about production security requirements Understand RunAgent's security architecture Learn advanced security patterns Understand compliance requirements **🎉 Excellent!** You now understand RunAgent's security model and best practices. These security measures help protect your agents, data, and users from various threats! * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Why RunAgent? Source: https://docs.run-agent.ai/explanation/why-runagent Why choose RunAgent over building your own agent infrastructure > The traditional approach to deploying AI agents is painful. RunAgent eliminates the infrastructure complexity so you can focus on what matters: building great AI agents. ## The Problem Every AI Developer Faces You have built an amazing AI agent in Python. It works perfectly. Now your team wants to use it: * **Frontend team** needs it in JavaScript * **Mobile team** wants it in Kotlin * **Systems team** requires it in Rust * **Unity team** needs it in C# ### The Traditional Approach * Create FastAPI/Flask endpoints * Handle request/response serialization * Write API documentation * Manage versioning and backward compatibility * Implement WebSocket handlers * Manage connection lifecycle * Handle reconnection logic * Deal with message ordering * Implement authentication * Add rate limiting * Manage API keys and scopes * Secure against common attacks * Set up load balancers * Configure auto-scaling * Monitor resource usage * Handle cold starts and warm-up * Create client libraries for each language * Handle async/await patterns * Manage connection pooling * Provide streaming interfaces **Result**: Weeks or months of infrastructure work before your agent is usable. *** ## The RunAgent Solution One command: `runagent serve .` and your agent is live with full API and SDK support. Automatically generates native-feeling APIs for Python, JavaScript, Go, and Rust. Real-time token streaming works out of the box across all languages. Sandboxed execution, API authentication, and rate limiting included. *** ## Cost Comparison **Time Investment:** * 2-4 weeks for basic REST API * 1-2 weeks for streaming support * 2-3 weeks for security implementation * 1-2 weeks per language SDK * Ongoing maintenance and updates **Total: 2-3 months of development time** **Ongoing Costs:** * Infrastructure management * Security updates * SDK maintenance * Monitoring and debugging **Time Investment:** * 5 minutes to deploy * Focus on agent logic only **Ongoing Costs:** * Zero infrastructure management * Automatic updates and security patches * Built-in monitoring and scaling *** ## Real-World Example ### Before RunAgent ```python theme={null} # Your agent logic def analyze_document(content: str) -> str: return llm.analyze(content) # You need to build: # - FastAPI server # - WebSocket handlers # - Authentication middleware # - Rate limiting # - Error handling # - SDKs for JS, Go, Rust # - Deployment configuration # - Monitoring setup ``` **Time to production**: 6-8 weeks ### With RunAgent ```python theme={null} # Your agent logic (same as before) def analyze_document(content: str) -> str: return llm.analyze(content) # Configuration # runagent.config.json { "entrypoints": [{"file": "agent.py", "module": "analyze_document", "tag": "analyze"}] } # Deploy runagent serve . ``` **Time to production**: 5 minutes *** ## What You Get vs What You Build * **Sandboxed execution** (Firecracker microVMs) * **Auto-scaling** (0 to thousands of requests) * **Multi-language SDKs** (Python, JS, Go, Rust) * **Streaming support** (WebSocket + HTTP) * **Authentication** (API keys, scopes) * **Rate limiting** (per-agent, per-user) * **Monitoring** (logs, metrics, traces) * **Error handling** (retries, timeouts) * **Security** (isolation, input validation) * Custom API framework * WebSocket infrastructure * Language-specific clients * Authentication system * Rate limiting logic * Monitoring dashboard * Error handling * Security measures * Deployment automation *** ## The Developer Experience Difference ```bash theme={null} # Week 1-2: Set up FastAPI pip install fastapi uvicorn # Write API endpoints, middleware, etc. # Week 3-4: Add streaming pip install websockets # Implement WebSocket handlers # Week 5-6: Security pip install python-jose # Add auth, rate limiting # Week 7-8: SDKs # Write clients for each language # Week 9-10: Deployment # Docker, Kubernetes, CI/CD ``` ```bash theme={null} # Write your agent def my_agent(query: str) -> str: return process(query) # Deploy runagent serve . # Use from any language # Python, JS, Go, Rust - all work immediately ``` *** ## When to Choose RunAgent * **Rapid prototyping** of AI agents * **Multi-language teams** needing shared agents * **Startups** wanting to focus on AI, not infrastructure * **Production deployments** requiring reliability * **Streaming applications** (chat, real-time analysis) * **Teams** without dedicated DevOps resources * **Simple scripts** that only run locally * **Legacy systems** with complex integration requirements * **Teams** with extensive existing infrastructure * **Applications** requiring custom protocols * **On-premise only** deployments (currently) *** ## The Bottom Line **RunAgent is not just another deployment tool** — it is a complete platform designed specifically for AI agents. It eliminates the 80% of infrastructure work that is common to all agent deployments, letting you focus on the 20% that makes your agent unique. **Time saved**: 2-3 months of development **Focus gained**: 100% on AI agent logic **Languages supported**: 4+ out of the box **Production ready**: From day one *** ## Ready to Get Started? See the difference in 5 minutes Understand how RunAgent works See real-world use cases * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Advanced Tasks Source: https://docs.run-agent.ai/how-to/advanced-tasks Advanced patterns and techniques for production-ready agents # Advanced Tasks This section covers advanced patterns and techniques for building production-ready agents with RunAgent. ## Available Guides * **[Streaming Responses](/how-to/advanced/streaming-responses)** - Real-time streaming patterns and optimization ## Coming Soon Additional advanced task guides are being developed: * **Testing agents** - Unit testing, integration testing, and mocking * **Observability** - Logging, monitoring, and debugging deployed agents * **Security** - Authentication, authorization, and data protection * **CI/CD** - Automated deployment and testing pipelines * **Memory management** - Stateful agents and conversation memory * **Performance optimization** - Caching, batching, and resource management ## Current Resources For now, you can find advanced information in: * [Production Considerations](/explanation/production-considerations) - Essential production requirements * [Security Model](/explanation/security) - Security best practices * [Architecture Overview](/explanation/architecture-overview) - Understanding the system These advanced guides will be available in upcoming releases. Check our [roadmap](/explanation/roadmap) for the latest updates. # Call from Go Source: https://docs.run-agent.ai/how-to/call-from-go Use RunAgent agents from Go applications **Prerequisites**: Go 1.19+ and completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview The Go SDK provides idiomatic access to RunAgent agents with context-aware operations, channel-based streaming, and concurrent processing. It's designed to work seamlessly with Go's concurrency model and error handling patterns. ## Installation ```bash theme={null} go get github.com/runagent-dev/runagent-go ``` ## Basic Usage ### Synchronous Calls ```go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { // Create client c, err := client.NewWithAddress( "your_agent_id_here", "main", true, // local "localhost", 8451, ) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer c.Close() // Create context with timeout ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() // Call your agent result, err := c.Run(ctx, map[string]interface{}{ "message": "Hello, how are you?", "userId": "go_user", }) if err != nil { log.Fatalf("Failed to run agent: %v", err) } fmt.Printf("Response: %v\n", result) } ``` ### Asynchronous Calls ```go theme={null} package main import ( "context" "fmt" "log" "sync" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { c, err := client.NewWithAddress( "your_agent_id_here", "main", true, "localhost", 8451, ) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer c.Close() // Run multiple requests concurrently var wg sync.WaitGroup results := make(chan string, 5) for i := 0; i < 5; i++ { wg.Add(1) go func(i int) { defer wg.Done() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := c.Run(ctx, map[string]interface{}{ "message": fmt.Sprintf("Request %d", i), "userId": "go_user", }) if err != nil { log.Printf("Request %d failed: %v", i, err) return } results <- fmt.Sprintf("Request %d: %v", i, result) }(i) } // Close results channel when all goroutines are done go func() { wg.Wait() close(results) }() // Print results for result := range results { fmt.Println(result) } } ``` ## Advanced Features ### 1. Streaming Responses ```go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { c, err := client.NewWithAddress( "your_agent_id_here", "streaming", // Note: tag ends with _stream true, "localhost", 8451, ) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() // Stream responses stream, err := c.RunStream(ctx, map[string]interface{}{ "message": "Tell me a story", "userId": "go_user", }) if err != nil { log.Fatalf("Failed to start stream: %v", err) } defer stream.Close() // Process stream for { data, hasMore, err := stream.Next(ctx) if err != nil { log.Fatalf("Stream error: %v", err) } if !hasMore { break } fmt.Print(data) } } ``` ### 2. Error Handling ```go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { c, err := client.NewWithAddress( "your_agent_id_here", "main", true, "localhost", 8451, ) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := c.Run(ctx, map[string]interface{}{ "message": "Test message", }) if err != nil { // Handle different error types switch err.(type) { case *client.AuthenticationError: log.Fatal("Authentication failed. Check your API key.") case *client.AgentNotFoundError: log.Fatal("Agent not found. Check your agent ID.") case *client.ValidationError: log.Fatalf("Validation error: %v", err) case *client.RateLimitError: log.Fatal("Rate limit exceeded. Please wait and try again.") case *client.TimeoutError: log.Fatal("Request timed out. Please try again.") case *client.NetworkError: log.Fatal("Network error. Check your connection.") default: log.Fatalf("Unexpected error: %v", err) } } fmt.Printf("Success: %v\n", result) } ``` ### 3. Custom Headers and Metadata ```go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { // Create client with custom configuration c, err := client.NewWithConfig(client.Config{ AgentID: "your_agent_id_here", EntrypointTag: "main", Local: true, Host: "localhost", Port: 8451, Headers: map[string]string{ "X-Request-ID": "unique-request-id", "X-User-ID": "go_user", }, Timeout: 30 * time.Second, }) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := c.Run(ctx, map[string]interface{}{ "message": "Hello with custom headers", "metadata": map[string]interface{}{ "source": "go_app", "version": "1.0.0", }, }) if err != nil { log.Fatalf("Failed to run agent: %v", err) } fmt.Printf("Response: %v\n", result) } ``` ## Configuration ### Environment Variables ```bash theme={null} # Set API key export RUNAGENT_API_KEY="your-api-key" # Set API URL export RUNAGENT_API_URL="https://api.run-agent.ai" # Set default agent ID export RUNAGENT_AGENT_ID="your-agent-id" ``` ### Configuration File Create `~/.runagent/config.json`: ```json theme={null} { "apiKey": "your-api-key", "apiUrl": "https://api.run-agent.ai", "defaultAgentId": "your-agent-id", "timeout": 30000, "retryAttempts": 3 } ``` ### Programmatic Configuration ```go theme={null} package main import ( "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { c, err := client.NewWithConfig(client.Config{ AgentID: "your_agent_id_here", EntrypointTag: "main", Local: true, APIKey: "your-api-key", APIURL: "https://api.run-agent.ai", Timeout: 30 * time.Second, RetryAttempts: 3, }) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer c.Close() } ``` ## Best Practices ### 1. **Connection Management** ```go theme={null} package main import ( "context" "fmt" "log" "sync" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) type AgentManager struct { client *client.Client mu sync.RWMutex } func NewAgentManager(agentID, entrypointTag string) (*AgentManager, error) { c, err := client.NewWithAddress(agentID, entrypointTag, true, "localhost", 8451) if err != nil { return nil, err } return &AgentManager{client: c}, nil } func (am *AgentManager) Run(ctx context.Context, message string, options map[string]interface{}) (interface{}, error) { am.mu.RLock() defer am.mu.RUnlock() params := map[string]interface{}{ "message": message, } // Merge options for k, v := range options { params[k] = v } return am.client.Run(ctx, params) } func (am *AgentManager) Close() error { am.mu.Lock() defer am.mu.Unlock() if am.client != nil { am.client.Close() am.client = nil } return nil } // Usage func main() { manager, err := NewAgentManager("your_agent_id", "main") if err != nil { log.Fatal(err) } defer manager.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := manager.Run(ctx, "Hello", map[string]interface{}{ "userId": "go_user", }) if err != nil { log.Fatal(err) } fmt.Printf("Response: %v\n", result) } ``` ### 2. **Retry Logic** ```go theme={null} package main import ( "context" "fmt" "log" "math" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func runWithRetry(c *client.Client, ctx context.Context, message string, maxRetries int) (interface{}, error) { var lastErr error for attempt := 0; attempt < maxRetries; attempt++ { result, err := c.Run(ctx, map[string]interface{}{ "message": message, }) if err == nil { return result, nil } lastErr = err if attempt < maxRetries-1 { // Exponential backoff backoff := time.Duration(math.Pow(2, float64(attempt))) * time.Second time.Sleep(backoff) } } return nil, lastErr } func main() { c, err := client.NewWithAddress("your_agent_id", "main", true, "localhost", 8451) if err != nil { log.Fatal(err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() result, err := runWithRetry(c, ctx, "Hello with retry", 3) if err != nil { log.Fatal(err) } fmt.Printf("Response: %v\n", result) } ``` ### 3. **Logging and Monitoring** ```go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) type MonitoredAgent struct { client *client.Client logger *log.Logger } func NewMonitoredAgent(agentID, entrypointTag string, logger *log.Logger) (*MonitoredAgent, error) { c, err := client.NewWithAddress(agentID, entrypointTag, true, "localhost", 8451) if err != nil { return nil, err } return &MonitoredAgent{ client: c, logger: logger, }, nil } func (ma *MonitoredAgent) Run(ctx context.Context, message string) (interface{}, error) { ma.logger.Printf("Starting request: %s", message) startTime := time.Now() result, err := ma.client.Run(ctx, map[string]interface{}{ "message": message, }) duration := time.Since(startTime) if err != nil { ma.logger.Printf("Request failed after %v: %v", duration, err) return nil, err } ma.logger.Printf("Request completed in %v", duration) return result, nil } func (ma *MonitoredAgent) Close() { ma.client.Close() } // Usage func main() { logger := log.New(os.Stdout, "[AGENT] ", log.LstdFlags) agent, err := NewMonitoredAgent("your_agent_id", "main", logger) if err != nil { log.Fatal(err) } defer agent.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := agent.Run(ctx, "Hello with monitoring") if err != nil { log.Fatal(err) } fmt.Printf("Response: %v\n", result) } ``` ## Common Patterns ### 1. **Agent Factory Pattern** ```go theme={null} package main import ( "context" "fmt" "log" "github.com/runagent-dev/runagent-go/pkg/client" ) type AgentFactory struct { baseConfig client.Config } func NewAgentFactory(baseConfig client.Config) *AgentFactory { return &AgentFactory{baseConfig: baseConfig} } func (af *AgentFactory) GetAgent(agentID, entrypointTag string) (*client.Client, error) { config := af.baseConfig config.AgentID = agentID config.EntrypointTag = entrypointTag return client.NewWithConfig(config) } func (af *AgentFactory) GetChatAgent(agentID string) (*client.Client, error) { return af.GetAgent(agentID, "chat") } func (af *AgentFactory) GetAnalysisAgent(agentID string) (*client.Client, error) { return af.GetAgent(agentID, "analyze") } // Usage func main() { factory := NewAgentFactory(client.Config{ Local: true, Timeout: 30 * time.Second, }) chatAgent, err := factory.GetChatAgent("your_agent_id") if err != nil { log.Fatal(err) } defer chatAgent.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := chatAgent.Run(ctx, map[string]interface{}{ "message": "Hello", }) if err != nil { log.Fatal(err) } fmt.Printf("Response: %v\n", result) } ``` ### 2. **Agent Wrapper Pattern** ```go theme={null} package main import ( "context" "fmt" "log" "github.com/runagent-dev/runagent-go/pkg/client" ) type AgentWrapper struct { client *client.Client agentID string entrypointTag string } func NewAgentWrapper(agentID, entrypointTag string, options client.Config) (*AgentWrapper, error) { c, err := client.NewWithConfig(options) if err != nil { return nil, err } return &AgentWrapper{ client: c, agentID: agentID, entrypointTag: entrypointTag, }, nil } func (aw *AgentWrapper) Call(ctx context.Context, options map[string]interface{}) (interface{}, error) { return aw.client.Run(ctx, options) } func (aw *AgentWrapper) Chat(ctx context.Context, message, userID string) (string, error) { result, err := aw.client.Run(ctx, map[string]interface{}{ "message": message, "userId": userID, }) if err != nil { return "", err } // Extract response from result if response, ok := result.(map[string]interface{})["response"]; ok { return fmt.Sprintf("%v", response), nil } return fmt.Sprintf("%v", result), nil } func (aw *AgentWrapper) Analyze(ctx context.Context, data, analysisType string) (interface{}, error) { return aw.client.Run(ctx, map[string]interface{}{ "data": data, "analysisType": analysisType, }) } func (aw *AgentWrapper) Stream(ctx context.Context, message string) (string, error) { stream, err := aw.client.RunStream(ctx, map[string]interface{}{ "message": message, }) if err != nil { return "", err } defer stream.Close() var response string for { data, hasMore, err := stream.Next(ctx) if err != nil { return "", err } if !hasMore { break } response += fmt.Sprintf("%v", data) } return response, nil } func (aw *AgentWrapper) Close() { aw.client.Close() } // Usage func main() { agent, err := NewAgentWrapper("your_agent_id", "main", client.Config{ Local: true, Timeout: 30 * time.Second, }) if err != nil { log.Fatal(err) } defer agent.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() response, err := agent.Chat(ctx, "Hello, how are you?", "go_user") if err != nil { log.Fatal(err) } fmt.Printf("Response: %s\n", response) } ``` ### 3. **Agent Pool Pattern** ```go theme={null} package main import ( "context" "fmt" "log" "sync" "github.com/runagent-dev/runagent-go/pkg/client" ) type AgentPool struct { agents []*client.Client mu sync.RWMutex index int } func NewAgentPool(agentConfigs []client.Config) (*AgentPool, error) { agents := make([]*client.Client, len(agentConfigs)) for i, config := range agentConfigs { agent, err := client.NewWithConfig(config) if err != nil { return nil, err } agents[i] = agent } return &AgentPool{agents: agents}, nil } func (ap *AgentPool) GetAgent() *client.Client { ap.mu.Lock() defer ap.mu.Unlock() agent := ap.agents[ap.index] ap.index = (ap.index + 1) % len(ap.agents) return agent } func (ap *AgentPool) Call(ctx context.Context, options map[string]interface{}) (interface{}, error) { agent := ap.GetAgent() return agent.Run(ctx, options) } func (ap *AgentPool) Close() { ap.mu.Lock() defer ap.mu.Unlock() for _, agent := range ap.agents { agent.Close() } } // Usage func main() { pool, err := NewAgentPool([]client.Config{ {AgentID: "agent1", EntrypointTag: "main", Local: true}, {AgentID: "agent2", EntrypointTag: "main", Local: true}, {AgentID: "agent3", EntrypointTag: "main", Local: true}, }) if err != nil { log.Fatal(err) } defer pool.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := pool.Call(ctx, map[string]interface{}{ "message": "Hello from pool", }) if err != nil { log.Fatal(err) } fmt.Printf("Response: %v\n", result) } ``` ## Error Handling ### Common Error Types ```go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func handleErrors(c *client.Client, ctx context.Context, message string) { result, err := c.Run(ctx, map[string]interface{}{ "message": message, }) if err != nil { switch err.(type) { case *client.AuthenticationError: log.Fatal("Authentication failed. Check your API key.") case *client.AgentNotFoundError: log.Fatal("Agent not found. Check your agent ID.") case *client.ValidationError: log.Fatalf("Validation error: %v", err) case *client.RateLimitError: log.Fatal("Rate limit exceeded. Please wait and try again.") case *client.TimeoutError: log.Fatal("Request timed out. Please try again.") case *client.NetworkError: log.Fatal("Network error. Check your connection.") default: log.Fatalf("Unexpected error: %v", err) } } fmt.Printf("Success: %v\n", result) } ``` ## Performance Optimization ### 1. **Connection Pooling** ```go theme={null} package main import ( "context" "fmt" "log" "sync" "github.com/runagent-dev/runagent-go/pkg/client" ) type ConnectionPool struct { pool []*client.Client mu sync.RWMutex index int } func NewConnectionPool(agentID, entrypointTag string, poolSize int) (*ConnectionPool, error) { pool := make([]*client.Client, poolSize) for i := 0; i < poolSize; i++ { c, err := client.NewWithAddress(agentID, entrypointTag, true, "localhost", 8451) if err != nil { return nil, err } pool[i] = c } return &ConnectionPool{pool: pool}, nil } func (cp *ConnectionPool) GetClient() *client.Client { cp.mu.Lock() defer cp.mu.Unlock() client := cp.pool[cp.index] cp.index = (cp.index + 1) % len(cp.pool) return client } func (cp *ConnectionPool) Run(ctx context.Context, options map[string]interface{}) (interface{}, error) { client := cp.GetClient() return client.Run(ctx, options) } func (cp *ConnectionPool) Close() { cp.mu.Lock() defer cp.mu.Unlock() for _, client := range cp.pool { client.Close() } } // Usage func main() { pool, err := NewConnectionPool("your_agent_id", "main", 5) if err != nil { log.Fatal(err) } defer pool.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := pool.Run(ctx, map[string]interface{}{ "message": "Hello", }) if err != nil { log.Fatal(err) } fmt.Printf("Response: %v\n", result) } ``` ### 2. **Caching** ```go theme={null} package main import ( "context" "crypto/md5" "fmt" "log" "sync" "github.com/runagent-dev/runagent-go/pkg/client" ) type CachedAgent struct { client *client.Client cache map[string]interface{} mu sync.RWMutex } func NewCachedAgent(agentID, entrypointTag string) (*CachedAgent, error) { c, err := client.NewWithAddress(agentID, entrypointTag, true, "localhost", 8451) if err != nil { return nil, err } return &CachedAgent{ client: c, cache: make(map[string]interface{}), }, nil } func (ca *CachedAgent) cacheKey(options map[string]interface{}) string { // Simple cache key generation (in production, use a proper hash) key := fmt.Sprintf("%v", options) hash := md5.Sum([]byte(key)) return fmt.Sprintf("%x", hash) } func (ca *CachedAgent) Run(ctx context.Context, options map[string]interface{}) (interface{}, error) { cacheKey := ca.cacheKey(options) ca.mu.RLock() if result, exists := ca.cache[cacheKey]; exists { ca.mu.RUnlock() return result, nil } ca.mu.RUnlock() result, err := ca.client.Run(ctx, options) if err != nil { return nil, err } ca.mu.Lock() ca.cache[cacheKey] = result ca.mu.Unlock() return result, nil } func (ca *CachedAgent) Close() { ca.client.Close() } // Usage func main() { cachedAgent, err := NewCachedAgent("your_agent_id", "main") if err != nil { log.Fatal(err) } defer cachedAgent.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := cachedAgent.Run(ctx, map[string]interface{}{ "message": "Hello", }) if err != nil { log.Fatal(err) } fmt.Printf("Response: %v\n", result) } ``` ## Testing ### Unit Testing ```go theme={null} package main import ( "context" "testing" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func TestAgentClient(t *testing.T) { c, err := client.NewWithAddress("test_agent", "main", true, "localhost", 8451) if err != nil { t.Fatalf("Failed to create client: %v", err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := c.Run(ctx, map[string]interface{}{ "message": "Hello", }) if err != nil { t.Fatalf("Failed to run agent: %v", err) } if result == nil { t.Error("Expected non-nil result") } } func TestAgentClientError(t *testing.T) { c, err := client.NewWithAddress("invalid_agent", "main", true, "localhost", 8451) if err != nil { t.Fatalf("Failed to create client: %v", err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = c.Run(ctx, map[string]interface{}{ "message": "Hello", }) if err == nil { t.Error("Expected error for invalid agent") } } ``` ### Integration Testing ```go theme={null} package main import ( "context" "testing" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func TestAgentIntegration(t *testing.T) { c, err := client.NewWithAddress("test_agent", "main", true, "localhost", 8451) if err != nil { t.Fatalf("Failed to create client: %v", err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := c.Run(ctx, map[string]interface{}{ "message": "Hello", }) if err != nil { t.Fatalf("Failed to run agent: %v", err) } if result == nil { t.Error("Expected non-nil result") } } func TestAgentStreaming(t *testing.T) { c, err := client.NewWithAddress("test_agent", "streaming", true, "localhost", 8451) if err != nil { t.Fatalf("Failed to create client: %v", err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() stream, err := c.RunStream(ctx, map[string]interface{}{ "message": "Hello", }) if err != nil { t.Fatalf("Failed to start stream: %v", err) } defer stream.Close() var response string for { data, hasMore, err := stream.Next(ctx) if err != nil { t.Fatalf("Stream error: %v", err) } if !hasMore { break } response += fmt.Sprintf("%v", data) } if response == "" { t.Error("Expected non-empty response") } } ``` ## Next Steps Learn advanced concurrency patterns for Go Deploy your Go applications to production Integrate with other programming languages Optimize your Go applications for production **🎉 Great work!** You've learned how to use RunAgent agents from Go applications. The Go SDK provides idiomatic access with context-aware operations and channel-based streaming! # Call from JavaScript Source: https://docs.run-agent.ai/how-to/call-from-javascript Use RunAgent agents from JavaScript/Node.js applications **Prerequisites**: Node.js 16+ and completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview The JavaScript SDK provides native-feeling access to RunAgent agents with full TypeScript support, async/await patterns, and streaming capabilities. It's designed to work seamlessly in both Node.js and browser environments. ## Installation ```bash theme={null} npm install runagent ``` ## Basic Usage ### Synchronous Calls ```javascript theme={null} import { RunAgentClient } from 'runagent'; // Connect to your agent const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'main', local: true // Set to false for production }); // Call your agent const result = await client.run({ message: 'Hello, how are you?', userId: 'javascript_user' }); console.log(`Response: ${result.response}`); ``` ### Asynchronous Calls ```javascript theme={null} import { RunAgentClient } from 'runagent'; async function main() { // Connect to your agent const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'main', local: true }); // Call your agent asynchronously const result = await client.run({ message: 'Hello, how are you?', userId: 'javascript_user' }); console.log(`Response: ${result.response}`); } // Run the async function main().catch(console.error); ``` ## Advanced Features ### 1. Streaming Responses ```javascript theme={null} import { RunAgentClient } from 'runagent'; // Connect to streaming entrypoint const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'streaming', // Note: tag ends with _stream local: true }); // Stream responses const stream = await client.run({ message: 'Tell me a story' }); for await (const chunk of stream) { process.stdout.write(chunk); } ``` ### 2. Batch Processing ```javascript theme={null} import { RunAgentClient } from 'runagent'; async function batchProcessing() { const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'main', local: true }); // Process multiple requests concurrently const promises = Array.from({ length: 10 }, (_, i) => client.run({ message: `Process item ${i}`, userId: 'batch_user' }) ); const results = await Promise.all(promises); results.forEach((result, i) => { console.log(`Item ${i}: ${result.response}`); }); } batchProcessing().catch(console.error); ``` ### 3. Error Handling ```javascript theme={null} import { RunAgentClient, RunAgentError } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'main', local: true }); try { const result = await client.run({ message: 'Test message' }); console.log(`Success: ${result.response}`); } catch (error) { if (error instanceof RunAgentError) { console.error(`RunAgent error: ${error.message}`); } else { console.error(`Unexpected error: ${error.message}`); } } ``` ### 4. Custom Headers and Metadata ```javascript theme={null} import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'main', local: true, headers: { 'X-Request-ID': 'unique-request-id', 'X-User-ID': 'javascript_user' } }); const result = await client.run({ message: 'Hello with custom headers', metadata: { source: 'javascript_app', version: '1.0.0' } }); ``` ## Configuration ### Environment Variables ```bash theme={null} # Set API key export RUNAGENT_API_KEY="your-api-key" # Set API URL export RUNAGENT_API_URL="https://api.run-agent.ai" # Set default agent ID export RUNAGENT_AGENT_ID="your-agent-id" ``` ### Configuration File Create `~/.runagent/config.json`: ```json theme={null} { "apiKey": "your-api-key", "apiUrl": "https://api.run-agent.ai", "defaultAgentId": "your-agent-id", "timeout": 30000, "retryAttempts": 3 } ``` ### Programmatic Configuration ```javascript theme={null} import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'main', local: true, apiKey: 'your-api-key', apiUrl: 'https://api.run-agent.ai', timeout: 30000, retryAttempts: 3 }); ``` ## Best Practices ### 1. **Connection Management** ```javascript theme={null} import { RunAgentClient } from 'runagent'; class AgentManager { constructor(agentId, entrypointTag) { this.agentId = agentId; this.entrypointTag = entrypointTag; this.client = null; } async getClient() { if (!this.client) { this.client = new RunAgentClient({ agentId: this.agentId, entrypointTag: this.entrypointTag, local: true }); } return this.client; } async run(message, options = {}) { const client = await this.getClient(); return client.run({ message, ...options }); } } // Usage const agentManager = new AgentManager('your_agent_id', 'main'); const result = await agentManager.run('Hello'); ``` ### 2. **Retry Logic** ```javascript theme={null} import { RunAgentClient } from 'runagent'; async function runWithRetry(client, message, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await client.run({ message }); } catch (error) { if (attempt === maxRetries - 1) { throw error; } // Exponential backoff await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000) ); } } } const client = new RunAgentClient({ agentId: 'your_agent_id', entrypointTag: 'main', local: true }); const result = await runWithRetry(client, 'Hello with retry'); ``` ### 3. **Logging and Monitoring** ```javascript theme={null} import { RunAgentClient } from 'runagent'; class MonitoredAgent { constructor(agentId, entrypointTag) { this.client = new RunAgentClient({ agentId, entrypointTag, local: true }); } async run(message) { console.log(`Starting request: ${message}`); const startTime = Date.now(); try { const result = await this.client.run({ message }); const duration = Date.now() - startTime; console.log(`Request completed in ${duration}ms`); return result; } catch (error) { const duration = Date.now() - startTime; console.error(`Request failed after ${duration}ms: ${error.message}`); throw error; } } } // Usage const monitoredAgent = new MonitoredAgent('your_agent_id', 'main'); const result = await monitoredAgent.run('Hello with monitoring'); ``` ## Common Patterns ### 1. **Agent Factory Pattern** ```javascript theme={null} import { RunAgentClient } from 'runagent'; class AgentFactory { constructor(baseConfig) { this.baseConfig = baseConfig; } getAgent(agentId, entrypointTag) { return new RunAgentClient({ ...this.baseConfig, agentId, entrypointTag }); } getChatAgent(agentId) { return this.getAgent(agentId, 'chat'); } getAnalysisAgent(agentId) { return this.getAgent(agentId, 'analyze'); } } // Usage const factory = new AgentFactory({ local: true, timeout: 30000 }); const chatAgent = factory.getChatAgent('your_agent_id'); const result = await chatAgent.run({ message: 'Hello' }); ``` ### 2. **Agent Wrapper Pattern** ```javascript theme={null} import { RunAgentClient } from 'runagent'; class AgentWrapper { constructor(agentId, entrypointTag, options = {}) { this.client = new RunAgentClient({ agentId, entrypointTag, ...options }); this.agentId = agentId; this.entrypointTag = entrypointTag; } async call(options) { return this.client.run(options); } async chat(message, userId = 'default') { const result = await this.client.run({ message, userId }); return result.response || ''; } async analyze(data, analysisType = 'summary') { return this.client.run({ data, analysisType }); } async stream(message) { let response = ''; const stream = await this.client.run({ message }); for await (const chunk of stream) { response += chunk; } return response; } } // Usage const agent = new AgentWrapper('your_agent_id', 'main', { local: true }); const response = await agent.chat('Hello, how are you?'); ``` ### 3. **Agent Pool Pattern** ```javascript theme={null} import { RunAgentClient } from 'runagent'; class AgentPool { constructor(agentConfigs) { this.agents = agentConfigs.map(config => new RunAgentClient(config)); this.currentIndex = 0; } getAgent() { const agent = this.agents[this.currentIndex]; this.currentIndex = (this.currentIndex + 1) % this.agents.length; return agent; } async call(options) { const agent = this.getAgent(); return agent.run(options); } } // Usage const pool = new AgentPool([ { agentId: 'agent1', entrypointTag: 'main', local: true }, { agentId: 'agent2', entrypointTag: 'main', local: true }, { agentId: 'agent3', entrypointTag: 'main', local: true } ]); const result = await pool.call({ message: 'Hello from pool' }); ``` ## Error Handling ### Common Error Types ```javascript theme={null} import { RunAgentError, AuthenticationError, AgentNotFoundError, ValidationError, RateLimitError, TimeoutError, NetworkError } from 'runagent'; async function handleErrors(client, message) { try { return await client.run({ message }); } catch (error) { if (error instanceof AuthenticationError) { console.error('Authentication failed. Check your API key.'); } else if (error instanceof AgentNotFoundError) { console.error('Agent not found. Check your agent ID.'); } else if (error instanceof ValidationError) { console.error(`Validation error: ${error.message}`); } else if (error instanceof RateLimitError) { console.error('Rate limit exceeded. Please wait and try again.'); } else if (error instanceof TimeoutError) { console.error('Request timed out. Please try again.'); } else if (error instanceof NetworkError) { console.error('Network error. Check your connection.'); } else if (error instanceof RunAgentError) { console.error(`RunAgent error: ${error.message}`); } else { console.error(`Unexpected error: ${error.message}`); } throw error; } } ``` ## Performance Optimization ### 1. **Connection Pooling** ```javascript theme={null} import { RunAgentClient } from 'runagent'; class ConnectionPool { constructor(agentId, entrypointTag, poolSize = 5) { this.pool = []; this.agentId = agentId; this.entrypointTag = entrypointTag; // Pre-populate pool for (let i = 0; i < poolSize; i++) { const client = new RunAgentClient({ agentId, entrypointTag, local: true }); this.pool.push(client); } this.currentIndex = 0; } getClient() { const client = this.pool[this.currentIndex]; this.currentIndex = (this.currentIndex + 1) % this.pool.length; return client; } async run(options) { const client = this.getClient(); return client.run(options); } } // Usage const pool = new ConnectionPool('your_agent_id', 'main', 5); const result = await pool.run({ message: 'Hello' }); ``` ### 2. **Caching** ```javascript theme={null} import { RunAgentClient } from 'runagent'; import crypto from 'crypto'; class CachedAgent { constructor(agentId, entrypointTag) { this.client = new RunAgentClient({ agentId, entrypointTag, local: true }); this.cache = new Map(); } _cacheKey(options) { const keyData = JSON.stringify(options, Object.keys(options).sort()); return crypto.createHash('md5').update(keyData).digest('hex'); } async run(options) { const cacheKey = this._cacheKey(options); if (this.cache.has(cacheKey)) { return this.cache.get(cacheKey); } const result = await this.client.run(options); this.cache.set(cacheKey, result); return result; } } // Usage const cachedAgent = new CachedAgent('your_agent_id', 'main'); const result = await cachedAgent.run({ message: 'Hello' }); ``` ## Testing ### Unit Testing ```javascript theme={null} import { describe, it, expect, vi, beforeEach } from 'vitest'; import { RunAgentClient } from 'runagent'; describe('RunAgentClient', () => { let client; beforeEach(() => { client = new RunAgentClient({ agentId: 'test_agent', entrypointTag: 'main', local: true }); }); it('should run successfully', async () => { // Mock successful response vi.spyOn(client, 'run').mockResolvedValue({ response: 'Hello', status: 'success' }); const result = await client.run({ message: 'Hello' }); expect(result.response).toBe('Hello'); expect(client.run).toHaveBeenCalledWith({ message: 'Hello' }); }); it('should handle errors', async () => { // Mock error response vi.spyOn(client, 'run').mockRejectedValue(new Error('Test error')); await expect(client.run({ message: 'Hello' })).rejects.toThrow('Test error'); }); }); ``` ### Integration Testing ```javascript theme={null} import { describe, it, expect } from 'vitest'; import { RunAgentClient } from 'runagent'; describe('Agent Integration', () => { let client; beforeEach(() => { client = new RunAgentClient({ agentId: 'test_agent', entrypointTag: 'main', local: true }); }); it('should respond to messages', async () => { const result = await client.run({ message: 'Hello' }); expect(result).toHaveProperty('response'); expect(result).toHaveProperty('status'); expect(result.status).toBe('success'); }); it('should stream responses', async () => { const stream = await client.run({ message: 'Hello' }); let response = ''; for await (const chunk of stream) { response += chunk; } expect(response.length).toBeGreaterThan(0); }); }); ``` ## Browser Usage ### HTML Integration ```html theme={null} RunAgent JavaScript Example
``` ## Next Steps Learn advanced async patterns for JavaScript Deploy your JavaScript applications to production Integrate with other programming languages Optimize your JavaScript applications for production **🎉 Great work!** You've learned how to use RunAgent agents from JavaScript applications. The JavaScript SDK provides native-feeling access with full TypeScript support and async/await patterns! # Call from Python Source: https://docs.run-agent.ai/how-to/call-from-python Use RunAgent agents from Python applications **Prerequisites**: Python 3.8+ and completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview The Python SDK provides native-feeling access to RunAgent agents with full type safety, async support, and streaming capabilities. It's designed to feel like calling local Python functions. ## Installation ```bash theme={null} pip install runagent ``` ## Basic Usage ### Synchronous Calls ```python theme={null} from runagent import RunAgentClient # Connect to your agent client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True # Set to False for production ) # Call your agent result = client.run( message="Hello, how are you?", user_id="python_user" ) print(f"Response: {result['response']}") ``` ### Asynchronous Calls ```python theme={null} import asyncio from runagent import AsyncRunAgentClient async def main(): # Connect to your agent client = AsyncRunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True ) # Call your agent asynchronously result = await client.run( message="Hello, how are you?", user_id="python_user" ) print(f"Response: {result['response']}") # Run the async function asyncio.run(main()) ``` ## Advanced Features ### 1. Streaming Responses ```python theme={null} from runagent import RunAgentClient # Connect to streaming entrypoint client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="streaming", # Note: tag ends with _stream local=True ) # Stream responses for chunk in client.run(message="Tell me a story"): print(chunk, end="", flush=True) ``` ### 2. Batch Processing ```python theme={null} from runagent import RunAgentClient import asyncio async def batch_processing(): client = AsyncRunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True ) # Process multiple requests concurrently tasks = [ client.run(message=f"Process item {i}", user_id="batch_user") for i in range(10) ] results = await asyncio.gather(*tasks) for i, result in enumerate(results): print(f"Item {i}: {result['response']}") asyncio.run(batch_processing()) ``` ### 3. Error Handling ```python theme={null} from runagent import RunAgentClient, RunAgentError client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True ) try: result = client.run(message="Test message") print(f"Success: {result['response']}") except RunAgentError as e: print(f"RunAgent error: {e}") except Exception as e: print(f"Unexpected error: {e}") ``` ### 4. Custom Headers and Metadata ```python theme={null} from runagent import RunAgentClient client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True, headers={ "X-Request-ID": "unique-request-id", "X-User-ID": "python_user" } ) result = client.run( message="Hello with custom headers", metadata={ "source": "python_app", "version": "1.0.0" } ) ``` ## Configuration ### Environment Variables ```bash theme={null} # Set API key export RUNAGENT_API_KEY="your-api-key" # Set API URL export RUNAGENT_API_URL="https://api.run-agent.ai" # Set default agent ID export RUNAGENT_AGENT_ID="your-agent-id" ``` ### Configuration File Create `~/.runagent/config.json`: ```json theme={null} { "api_key": "your-api-key", "api_url": "https://api.run-agent.ai", "default_agent_id": "your-agent-id", "timeout": 30, "retry_attempts": 3 } ``` ### Programmatic Configuration ```python theme={null} from runagent import RunAgentClient client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True, api_key="your-api-key", api_url="https://api.run-agent.ai", timeout=30, retry_attempts=3 ) ``` ## Best Practices ### 1. **Connection Management** ```python theme={null} from runagent import RunAgentClient from contextlib import contextmanager @contextmanager def get_client(agent_id: str, entrypoint_tag: str): client = RunAgentClient( agent_id=agent_id, entrypoint_tag=entrypoint_tag, local=True ) try: yield client finally: # Cleanup if needed pass # Usage with get_client("your_agent_id", "main") as client: result = client.run(message="Hello") ``` ### 2. **Retry Logic** ```python theme={null} from runagent import RunAgentClient import time import random def run_with_retry(client, message, max_retries=3): for attempt in range(max_retries): try: return client.run(message=message) except Exception as e: if attempt == max_retries - 1: raise e time.sleep(random.uniform(1, 3)) # Exponential backoff client = RunAgentClient(agent_id="your_agent_id", entrypoint_tag="main", local=True) result = run_with_retry(client, "Hello with retry") ``` ### 3. **Logging and Monitoring** ```python theme={null} import logging from runagent import RunAgentClient # Setup logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True ) def monitored_run(message: str): logger.info(f"Starting request: {message}") start_time = time.time() try: result = client.run(message=message) duration = time.time() - start_time logger.info(f"Request completed in {duration:.2f}s") return result except Exception as e: duration = time.time() - start_time logger.error(f"Request failed after {duration:.2f}s: {e}") raise result = monitored_run("Hello with monitoring") ``` ## Common Patterns ### 1. **Agent Factory Pattern** ```python theme={null} from runagent import RunAgentClient from typing import Dict, Any class AgentFactory: def __init__(self, base_config: Dict[str, Any]): self.base_config = base_config def get_agent(self, agent_id: str, entrypoint_tag: str) -> RunAgentClient: config = self.base_config.copy() config.update({ "agent_id": agent_id, "entrypoint_tag": entrypoint_tag }) return RunAgentClient(**config) def get_chat_agent(self, agent_id: str) -> RunAgentClient: return self.get_agent(agent_id, "chat") def get_analysis_agent(self, agent_id: str) -> RunAgentClient: return self.get_agent(agent_id, "analyze") # Usage factory = AgentFactory({ "local": True, "timeout": 30 }) chat_agent = factory.get_chat_agent("your_agent_id") result = chat_agent.run(message="Hello") ``` ### 2. **Agent Wrapper Pattern** ```python theme={null} from runagent import RunAgentClient from typing import Dict, Any, Optional class AgentWrapper: def __init__(self, agent_id: str, entrypoint_tag: str, **kwargs): self.client = RunAgentClient( agent_id=agent_id, entrypoint_tag=entrypoint_tag, **kwargs ) self.agent_id = agent_id self.entrypoint_tag = entrypoint_tag def call(self, **kwargs) -> Dict[str, Any]: """Generic call method""" return self.client.run(**kwargs) def chat(self, message: str, user_id: str = "default") -> str: """Chat-specific method""" result = self.client.run(message=message, user_id=user_id) return result.get("response", "") def analyze(self, data: str, analysis_type: str = "summary") -> Dict[str, Any]: """Analysis-specific method""" return self.client.run(data=data, analysis_type=analysis_type) def stream(self, message: str) -> str: """Streaming method""" response = "" for chunk in self.client.run(message=message): response += chunk return response # Usage agent = AgentWrapper("your_agent_id", "main", local=True) response = agent.chat("Hello, how are you?") ``` ### 3. **Agent Pool Pattern** ```python theme={null} from runagent import RunAgentClient from typing import List, Dict, Any import random import threading class AgentPool: def __init__(self, agent_configs: List[Dict[str, Any]]): self.agents = [] self.lock = threading.Lock() for config in agent_configs: agent = RunAgentClient(**config) self.agents.append(agent) def get_agent(self) -> RunAgentClient: """Get a random agent from the pool""" with self.lock: return random.choice(self.agents) def call(self, **kwargs) -> Dict[str, Any]: """Call any available agent""" agent = self.get_agent() return agent.run(**kwargs) # Usage pool = AgentPool([ {"agent_id": "agent1", "entrypoint_tag": "main", "local": True}, {"agent_id": "agent2", "entrypoint_tag": "main", "local": True}, {"agent_id": "agent3", "entrypoint_tag": "main", "local": True} ]) result = pool.call(message="Hello from pool") ``` ## Error Handling ### Common Error Types ```python theme={null} from runagent import ( RunAgentError, AuthenticationError, AgentNotFoundError, ValidationError, RateLimitError, TimeoutError, NetworkError ) def handle_errors(client, message): try: return client.run(message=message) except AuthenticationError: print("Authentication failed. Check your API key.") except AgentNotFoundError: print("Agent not found. Check your agent ID.") except ValidationError as e: print(f"Validation error: {e}") except RateLimitError: print("Rate limit exceeded. Please wait and try again.") except TimeoutError: print("Request timed out. Please try again.") except NetworkError: print("Network error. Check your connection.") except RunAgentError as e: print(f"RunAgent error: {e}") except Exception as e: print(f"Unexpected error: {e}") ``` ## Performance Optimization ### 1. **Connection Pooling** ```python theme={null} from runagent import RunAgentClient import threading from queue import Queue class ConnectionPool: def __init__(self, agent_id: str, entrypoint_tag: str, pool_size: int = 5): self.pool = Queue(maxsize=pool_size) self.agent_id = agent_id self.entrypoint_tag = entrypoint_tag # Pre-populate pool for _ in range(pool_size): client = RunAgentClient( agent_id=agent_id, entrypoint_tag=entrypoint_tag, local=True ) self.pool.put(client) def get_client(self) -> RunAgentClient: return self.pool.get() def return_client(self, client: RunAgentClient): self.pool.put(client) # Usage pool = ConnectionPool("your_agent_id", "main", pool_size=5) client = pool.get_client() try: result = client.run(message="Hello") finally: pool.return_client(client) ``` ### 2. **Caching** ```python theme={null} from runagent import RunAgentClient import hashlib import json from functools import lru_cache class CachedAgent: def __init__(self, agent_id: str, entrypoint_tag: str): self.client = RunAgentClient( agent_id=agent_id, entrypoint_tag=entrypoint_tag, local=True ) self.cache = {} def _cache_key(self, **kwargs) -> str: """Generate cache key from parameters""" key_data = json.dumps(kwargs, sort_keys=True) return hashlib.md5(key_data.encode()).hexdigest() def run(self, **kwargs) -> Dict[str, Any]: cache_key = self._cache_key(**kwargs) if cache_key in self.cache: return self.cache[cache_key] result = self.client.run(**kwargs) self.cache[cache_key] = result return result # Usage cached_agent = CachedAgent("your_agent_id", "main") result = cached_agent.run(message="Hello") ``` ## Testing ### Unit Testing ```python theme={null} import unittest from unittest.mock import Mock, patch from runagent import RunAgentClient class TestAgentClient(unittest.TestCase): def setUp(self): self.client = RunAgentClient( agent_id="test_agent", entrypoint_tag="main", local=True ) @patch('runagent.client.requests.post') def test_run_success(self, mock_post): # Mock successful response mock_response = Mock() mock_response.json.return_value = {"response": "Hello"} mock_response.status_code = 200 mock_post.return_value = mock_response result = self.client.run(message="Hello") self.assertEqual(result["response"], "Hello") mock_post.assert_called_once() def test_run_error(self): with self.assertRaises(RunAgentError): self.client.run(message="") if __name__ == "__main__": unittest.main() ``` ### Integration Testing ```python theme={null} import pytest from runagent import RunAgentClient @pytest.fixture def agent_client(): return RunAgentClient( agent_id="test_agent", entrypoint_tag="main", local=True ) def test_agent_response(agent_client): result = agent_client.run(message="Hello") assert "response" in result assert result["status"] == "success" def test_agent_streaming(agent_client): response = "" for chunk in agent_client.run(message="Hello"): response += chunk assert len(response) > 0 ``` ## Next Steps Learn advanced async patterns for Python Deploy your Python applications to production Integrate with other programming languages Optimize your Python applications for production **🎉 Great work!** You've learned how to use RunAgent agents from Python applications. The Python SDK provides native-feeling access with full type safety and async support! * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Call from Rust Source: https://docs.run-agent.ai/how-to/call-from-rust Use RunAgent agents from Rust applications Use RunAgent agents from Rust applications with high-performance, type-safe execution. ## Prerequisites * Rust 1.70 or higher * Completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview The Rust SDK provides production-ready access to RunAgent agents with: * **Zero-cost abstractions** for optimal performance * **Futures-based async operations** powered by Tokio * **Compile-time type safety** with comprehensive error handling * **Seamless integration** with Rust's ownership model ## Installation Add the following dependencies to your `Cargo.toml`: ```toml theme={null} [dependencies] runagent = "0.1.0" tokio = { version = "1.0", features = ["full"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" ``` ## Basic Usage ### Synchronous Execution Execute an agent and wait for the complete response: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { // Create client connection let client = RunAgentClient::new( "your_agent_id_here", "main", true, // local deployment ).await?; // Execute agent with parameters let result = client.run(&[ ("message", json!("Hello, how are you?")), ("userId", json!("rust_user")), ]).await?; println!("Response: {}", result); Ok(()) } ``` ### Asynchronous Execution Process multiple requests concurrently for improved throughput: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use futures::future::join_all; #[tokio::main] async fn main() -> Result<(), Box> { let client = RunAgentClient::new( "your_agent_id_here", "main", true, ).await?; // Create concurrent requests let futures = (0..5).map(|i| { let client = client.clone(); async move { client.run(&[ ("message", json!(format!("Request {}", i))), ("userId", json!("rust_user")), ]).await } }); // Execute all requests concurrently let results = join_all(futures).await; for (i, result) in results.into_iter().enumerate() { match result { Ok(response) => println!("Request {}: {}", i, response), Err(e) => println!("Request {} failed: {}", i, e), } } Ok(()) } ``` ## Advanced Features ### Streaming Responses Process responses as they arrive for real-time applications: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use futures::StreamExt; #[tokio::main] async fn main() -> Result<(), Box> { let client = RunAgentClient::new( "your_agent_id_here", "streaming", // Entrypoint tag must end with _stream true, ).await?; // Create streaming connection let mut stream = client.run_stream(&[ ("message", json!("Tell me a story")), ("userId", json!("rust_user")), ]).await?; // Process chunks as they arrive while let Some(chunk) = stream.next().await { match chunk { Ok(data) => print!("{}", data), Err(e) => { eprintln!("Stream error: {}", e); break; } } } Ok(()) } ``` ### Error Handling Handle different error types with Rust's type-safe error handling: ```rust theme={null} use runagent::client::RunAgentClient; use runagent::types::{RunAgentError, RunAgentResult}; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { let client = RunAgentClient::new( "your_agent_id_here", "main", true, ).await?; let result = client.run(&[ ("message", json!("Test message")), ]).await; match result { Ok(response) => { println!("Success: {}", response); } Err(e) => { match e { RunAgentError::Authentication { .. } => { eprintln!("Authentication failed. Check your API key."); } RunAgentError::AgentNotFoundError => { eprintln!("Agent not found. Verify the agent ID."); } RunAgentError::Validation { message } => { eprintln!("Validation error: {}", message); } RunAgentError::RateLimitError => { eprintln!("Rate limit exceeded. Please retry later."); } RunAgentError::TimeoutError => { eprintln!("Request timed out."); } RunAgentError::NetworkError => { eprintln!("Network error. Check your connection."); } _ => { eprintln!("Unexpected error: {}", e); } } } } Ok(()) } ``` ### Custom Configuration Configure the client with custom headers and timeouts: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use std::collections::HashMap; #[tokio::main] async fn main() -> Result<(), Box> { // Prepare custom headers let mut headers = HashMap::new(); headers.insert("X-Request-ID".to_string(), "unique-request-id".to_string()); headers.insert("X-User-ID".to_string(), "rust_user".to_string()); // Create client with configuration let client = RunAgentClient::new_with_config( "your_agent_id_here", "main", true, Some(headers), Some(30), // timeout in seconds ).await?; let result = client.run(&[ ("message", json!("Hello with custom headers")), ("metadata", json!({ "source": "rust_app", "version": "1.0.0" })), ]).await?; println!("Response: {}", result); Ok(()) } ``` ## Configuration ### Environment Variables Configure the SDK using environment variables: ```bash theme={null} # API authentication export RUNAGENT_API_KEY="your-api-key" # API endpoint export RUNAGENT_API_URL="https://api.run-agent.ai" # Default agent export RUNAGENT_AGENT_ID="your-agent-id" ``` ### Configuration File Create `~/.runagent/config.json`: ```json theme={null} { "apiKey": "your-api-key", "apiUrl": "https://api.run-agent.ai", "defaultAgentId": "your-agent-id", "timeout": 30, "retryAttempts": 3 } ``` ### Programmatic Configuration Configure the client directly in code: ```rust theme={null} use runagent::client::RunAgentClient; use std::collections::HashMap; #[tokio::main] async fn main() -> Result<(), Box> { let mut headers = HashMap::new(); headers.insert("X-Custom-Header".to_string(), "value".to_string()); let client = RunAgentClient::new_with_config( "your_agent_id_here", "main", true, Some(headers), Some(30), // timeout in seconds ).await?; Ok(()) } ``` ## Best Practices ### Connection Management Implement a connection manager for efficient resource usage: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use std::sync::Arc; use tokio::sync::Mutex; struct AgentManager { client: Arc>, } impl AgentManager { async fn new( agent_id: &str, entrypoint_tag: &str ) -> Result> { let client = RunAgentClient::new(agent_id, entrypoint_tag, true).await?; Ok(Self { client: Arc::new(Mutex::new(client)), }) } async fn run( &self, message: &str, options: &[(&str, serde_json::Value)] ) -> Result> { let client = self.client.lock().await; let mut params = vec![("message", json!(message))]; params.extend(options.iter().map(|(k, v)| (*k, v.clone()))); let result = client.run(¶ms).await?; Ok(result.to_string()) } } #[tokio::main] async fn main() -> Result<(), Box> { let manager = AgentManager::new("your_agent_id", "main").await?; let result = manager.run("Hello", &[]).await?; println!("Response: {}", result); Ok(()) } ``` ### Retry Logic Implement exponential backoff for resilient operations: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use tokio::time::{sleep, Duration}; async fn run_with_retry( client: &RunAgentClient, message: &str, max_retries: usize, ) -> Result> { let mut last_error = None; for attempt in 0..max_retries { match client.run(&[("message", json!(message))]).await { Ok(result) => return Ok(result.to_string()), Err(e) => { last_error = Some(e); if attempt < max_retries - 1 { let backoff = Duration::from_secs(2_u64.pow(attempt as u32)); sleep(backoff).await; } } } } Err(last_error.unwrap().into()) } #[tokio::main] async fn main() -> Result<(), Box> { let client = RunAgentClient::new("your_agent_id", "main", true).await?; let result = run_with_retry(&client, "Hello with retry", 3).await?; println!("Response: {}", result); Ok(()) } ``` ### Logging and Monitoring Add observability to your agent interactions: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use std::time::Instant; use tracing::{info, error}; struct MonitoredAgent { client: RunAgentClient, } impl MonitoredAgent { async fn new( agent_id: &str, entrypoint_tag: &str ) -> Result> { let client = RunAgentClient::new(agent_id, entrypoint_tag, true).await?; Ok(Self { client }) } async fn run(&self, message: &str) -> Result> { info!("Starting request: {}", message); let start_time = Instant::now(); match self.client.run(&[("message", json!(message))]).await { Ok(result) => { let duration = start_time.elapsed(); info!("Request completed in {:?}", duration); Ok(result.to_string()) } Err(e) => { let duration = start_time.elapsed(); error!("Request failed after {:?}: {}", duration, e); Err(e.into()) } } } } #[tokio::main] async fn main() -> Result<(), Box> { tracing_subscriber::fmt::init(); let agent = MonitoredAgent::new("your_agent_id", "main").await?; let result = agent.run("Hello with monitoring").await?; println!("Response: {}", result); Ok(()) } ``` ## Common Patterns ### Agent Factory Pattern Create agents with consistent configuration: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use std::collections::HashMap; struct AgentFactory { base_config: AgentConfig, } #[derive(Clone)] struct AgentConfig { local: bool, timeout: Option, headers: Option>, } impl AgentFactory { fn new(base_config: AgentConfig) -> Self { Self { base_config } } async fn get_agent( &self, agent_id: &str, entrypoint_tag: &str ) -> Result> { RunAgentClient::new_with_config( agent_id, entrypoint_tag, self.base_config.local, self.base_config.headers.clone(), self.base_config.timeout, ).await.map_err(|e| e.into()) } async fn get_chat_agent( &self, agent_id: &str ) -> Result> { self.get_agent(agent_id, "chat").await } async fn get_analysis_agent( &self, agent_id: &str ) -> Result> { self.get_agent(agent_id, "analyze").await } } #[tokio::main] async fn main() -> Result<(), Box> { let factory = AgentFactory::new(AgentConfig { local: true, timeout: Some(30), headers: None, }); let chat_agent = factory.get_chat_agent("your_agent_id").await?; let result = chat_agent.run(&[("message", json!("Hello"))]).await?; println!("Response: {}", result); Ok(()) } ``` ### Agent Wrapper Pattern Encapsulate agent functionality with a clean interface: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use futures::StreamExt; struct AgentWrapper { client: RunAgentClient, agent_id: String, entrypoint_tag: String, } impl AgentWrapper { async fn new( agent_id: &str, entrypoint_tag: &str ) -> Result> { let client = RunAgentClient::new(agent_id, entrypoint_tag, true).await?; Ok(Self { client, agent_id: agent_id.to_string(), entrypoint_tag: entrypoint_tag.to_string(), }) } async fn call( &self, params: &[(&str, serde_json::Value)] ) -> Result> { self.client.run(params).await.map(|v| v.to_string()).map_err(|e| e.into()) } async fn chat( &self, message: &str, user_id: &str ) -> Result> { let result = self.client.run(&[ ("message", json!(message)), ("userId", json!(user_id)), ]).await?; Ok(result.to_string()) } async fn analyze( &self, data: &str, analysis_type: &str ) -> Result> { let result = self.client.run(&[ ("data", json!(data)), ("analysisType", json!(analysis_type)), ]).await?; Ok(result.to_string()) } async fn stream(&self, message: &str) -> Result> { let mut stream = self.client.run_stream(&[ ("message", json!(message)) ]).await?; let mut response = String::new(); while let Some(chunk) = stream.next().await { response.push_str(&chunk?.to_string()); } Ok(response) } } #[tokio::main] async fn main() -> Result<(), Box> { let agent = AgentWrapper::new("your_agent_id", "main").await?; let response = agent.chat("Hello, how are you?", "rust_user").await?; println!("Response: {}", response); Ok(()) } ``` ### Agent Pool Pattern Distribute load across multiple agent instances: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use std::sync::Arc; use tokio::sync::Mutex; struct AgentPool { agents: Vec>>, index: Arc>, } impl AgentPool { async fn new( agent_configs: Vec ) -> Result> { let mut agents = Vec::new(); for config in agent_configs { let client = RunAgentClient::new_with_config( &config.agent_id, &config.entrypoint_tag, config.local, config.headers, config.timeout, ).await?; agents.push(Arc::new(Mutex::new(client))); } Ok(Self { agents, index: Arc::new(Mutex::new(0)), }) } async fn get_agent(&self) -> Arc> { let mut index = self.index.lock().await; let agent = self.agents[*index].clone(); *index = (*index + 1) % self.agents.len(); agent } async fn call( &self, params: &[(&str, serde_json::Value)] ) -> Result> { let agent = self.get_agent().await; let client = agent.lock().await; client.run(params).await.map(|v| v.to_string()).map_err(|e| e.into()) } } #[derive(Clone)] struct AgentConfig { agent_id: String, entrypoint_tag: String, local: bool, headers: Option>, timeout: Option, } #[tokio::main] async fn main() -> Result<(), Box> { let pool = AgentPool::new(vec![ AgentConfig { agent_id: "agent1".to_string(), entrypoint_tag: "main".to_string(), local: true, headers: None, timeout: None, }, AgentConfig { agent_id: "agent2".to_string(), entrypoint_tag: "main".to_string(), local: true, headers: None, timeout: None, }, ]).await?; let result = pool.call(&[("message", json!("Hello from pool"))]).await?; println!("Response: {}", result); Ok(()) } ``` ## Performance Optimization ### Connection Pooling Reuse connections for improved performance: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use std::sync::Arc; use tokio::sync::Mutex; struct ConnectionPool { pool: Vec>>, index: Arc>, } impl ConnectionPool { async fn new( agent_id: &str, entrypoint_tag: &str, pool_size: usize ) -> Result> { let mut pool = Vec::new(); for _ in 0..pool_size { let client = RunAgentClient::new(agent_id, entrypoint_tag, true).await?; pool.push(Arc::new(Mutex::new(client))); } Ok(Self { pool, index: Arc::new(Mutex::new(0)), }) } async fn get_client(&self) -> Arc> { let mut index = self.index.lock().await; let client = self.pool[*index].clone(); *index = (*index + 1) % self.pool.len(); client } async fn run( &self, params: &[(&str, serde_json::Value)] ) -> Result> { let client = self.get_client().await; let client = client.lock().await; client.run(params).await.map(|v| v.to_string()).map_err(|e| e.into()) } } #[tokio::main] async fn main() -> Result<(), Box> { let pool = ConnectionPool::new("your_agent_id", "main", 5).await?; let result = pool.run(&[("message", json!("Hello"))]).await?; println!("Response: {}", result); Ok(()) } ``` ### Response Caching Cache responses for frequently requested data: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::RwLock; struct CachedAgent { client: RunAgentClient, cache: Arc>>, } impl CachedAgent { async fn new( agent_id: &str, entrypoint_tag: &str ) -> Result> { let client = RunAgentClient::new(agent_id, entrypoint_tag, true).await?; Ok(Self { client, cache: Arc::new(RwLock::new(HashMap::new())), }) } fn cache_key(&self, params: &[(&str, serde_json::Value)]) -> String { format!("{:?}", params) } async fn run( &self, params: &[(&str, serde_json::Value)] ) -> Result> { let cache_key = self.cache_key(params); // Check cache { let cache = self.cache.read().await; if let Some(result) = cache.get(&cache_key) { return Ok(result.clone()); } } // Execute agent let result = self.client.run(params).await?.to_string(); // Store in cache { let mut cache = self.cache.write().await; cache.insert(cache_key, result.clone()); } Ok(result) } } #[tokio::main] async fn main() -> Result<(), Box> { let cached_agent = CachedAgent::new("your_agent_id", "main").await?; let result = cached_agent.run(&[("message", json!("Hello"))]).await?; println!("Response: {}", result); Ok(()) } ``` ## Testing ### Unit Testing Test your agent interactions: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; #[tokio::test] async fn test_agent_client() { let client = RunAgentClient::new("test_agent", "main", true) .await .unwrap(); let result = client.run(&[("message", json!("Hello"))]).await; assert!(result.is_ok()); } #[tokio::test] async fn test_agent_client_error() { let client = RunAgentClient::new("invalid_agent", "main", true) .await .unwrap(); let result = client.run(&[("message", json!("Hello"))]).await; assert!(result.is_err()); } ``` ### Integration Testing Test complete workflows: ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use futures::StreamExt; #[tokio::test] async fn test_agent_integration() { let client = RunAgentClient::new("test_agent", "main", true) .await .unwrap(); let result = client.run(&[("message", json!("Hello"))]).await; assert!(result.is_ok()); } #[tokio::test] async fn test_agent_streaming() { let client = RunAgentClient::new("test_agent", "streaming", true) .await .unwrap(); let mut stream = client.run_stream(&[("message", json!("Hello"))]) .await .unwrap(); let mut response = String::new(); while let Some(chunk) = stream.next().await { response.push_str(&chunk.unwrap().to_string()); } assert!(!response.is_empty()); } ``` ## Next Steps Continue your journey with RunAgent: * **[Async Patterns](/how-to/advanced-tasks)** - Learn advanced async patterns for Rust * **[Production Deployment](/runagent-cloud/cloud-deployment)** - Deploy your Rust applications to production * **[Multi-Language Integration](/tutorials/multi-language-wrapper)** - Integrate with other programming languages * **[Performance Tuning](/explanation/production-considerations)** - Optimize your Rust applications ## Summary You have learned how to use RunAgent agents from Rust applications. The Rust SDK provides high-performance access with zero-cost abstractions and compile-time type safety, making it ideal for production deployments requiring maximum performance and reliability. # Ag2 Source: https://docs.run-agent.ai/how-to/frameworks/ag2 # AG2 Integration Deploy AG2 (AutoGen 2.0) multi-agent systems with RunAgent *** ## Prerequisites * Basic understanding of AG2/AutoGen * Completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial * Python 3.8 or higher *** ## Overview AG2 (AutoGen 2.0) is a framework for building multi-agent conversational systems with automated agent collaboration. RunAgent makes it easy to deploy AG2 agents and access them from any programming language while maintaining conversation flow. *** ## Installation & Setup ### 1. Install AG2 ```bash theme={null} pip install ag2>=0.9.6 ``` ### 2. Set Environment Variables AG2 requires API keys for LLM providers: ```bash theme={null} export OPENAI_API_KEY=your_openai_api_key_here ``` ### 3. Quick Start with RunAgent ```bash theme={null} runagent init my-ag2-agent --framework ag2 cd my-ag2-agent ``` *** ## Quick Start ### 1. Project Structure After initialization, your project will have: ``` my-ag2-agent/ ├── conversation.py # Main agent code ├── .env # Environment variables ├── requirements.txt # Python dependencies └── runagent.config.json # RunAgent configuration ``` ### 2. Configuration The generated `runagent.config.json`: ```json theme={null} { "agent_name": "my-ag2-agent", "description": "AG2 multi-agent conversation system", "framework": "ag2", "version": "1.0.0", "agent_architecture": { "entrypoints": [ { "file": "conversation.py", "module": "invoke", "tag": "ag2_invoke" }, { "file": "conversation.py", "module": "stream", "tag": "ag2_stream" } ] } } ``` ### 3. Create `.env` File ```bash theme={null} OPENAI_API_KEY=your_openai_api_key_here ``` *** ## Basic AG2 Agent Here's a simple AG2 agent with two conversational agents: ```python theme={null} # conversation.py from autogen import ConversableAgent, LLMConfig # Configure LLM using environment variables llm_config = LLMConfig( api_type="openai", model="gpt-4o-mini" ) # Create agents within the LLM config context with llm_config: assistant = ConversableAgent( name="assistant", system_message="You are a helpful assistant that responds concisely and accurately.", ) fact_checker = ConversableAgent( name="fact_checker", system_message="You are a fact-checking assistant. Verify claims and provide accurate corrections when needed.", ) def invoke(message: str, max_turns: int = 5): """ Non-streaming conversation between assistant and fact checker. Args: message: The user's message to start the conversation max_turns: Maximum number of conversation turns (default: 5) Returns: Conversation result with chat history """ try: result = assistant.initiate_chat( recipient=fact_checker, message=message, max_turns=max_turns ) return { "status": "success", "result": result, "message": "Conversation completed successfully" } except Exception as e: return { "status": "error", "error": str(e), "message": f"Error in AG2 conversation: {str(e)}" } def stream(message: str, max_turns: int = 5): """ Streaming conversation between assistant and fact checker. Args: message: The user's message to start the conversation max_turns: Maximum number of conversation turns (default: 5) Yields: Conversation events as they occur """ try: # Start the conversation response = assistant.run( recipient=fact_checker, message=message, max_turns=max_turns ) # Stream events for event in response.events: if event.type == "text": yield { "type": "text", "content": event.content, "sender": getattr(event, 'sender', 'unknown') } else: yield { "type": event.type, "data": event.model_dump() if hasattr(event, 'model_dump') else str(event) } except Exception as e: yield { "type": "error", "error": str(e), "message": f"Error in AG2 streaming: {str(e)}" } ``` *** ## Advanced AG2 Patterns ### 1. Multi-Agent Collaboration ```python theme={null} # advanced_conversation.py from autogen import ConversableAgent, LLMConfig llm_config = LLMConfig(api_type="openai", model="gpt-4o-mini") with llm_config: # Research agent researcher = ConversableAgent( name="researcher", system_message="You are a research specialist. Gather and present factual information.", ) # Analyst agent analyst = ConversableAgent( name="analyst", system_message="You are a data analyst. Analyze information and provide insights.", ) # Writer agent writer = ConversableAgent( name="writer", system_message="You are a technical writer. Synthesize information into clear, concise reports.", ) def research_workflow(topic: str, max_turns: int = 10): """ Multi-agent research workflow. Flow: User → Researcher → Analyst → Writer """ try: # Stage 1: Research research_result = researcher.initiate_chat( recipient=analyst, message=f"Research the following topic: {topic}", max_turns=max_turns // 2 ) # Stage 2: Analysis and Writing final_result = analyst.initiate_chat( recipient=writer, message="Based on the research, create a comprehensive report.", max_turns=max_turns // 2 ) return { "status": "success", "research": research_result, "final_report": final_result, "topic": topic } except Exception as e: return { "status": "error", "error": str(e), "topic": topic } ``` ### 2. Agent with Custom Tools ```python theme={null} # tool_agent.py from autogen import ConversableAgent, LLMConfig from typing import Annotated llm_config = LLMConfig(api_type="openai", model="gpt-4o-mini") def calculate( expression: Annotated[str, "Mathematical expression to evaluate"] ) -> str: """Calculate a mathematical expression.""" try: # Safe evaluation with limited scope import math allowed = { "abs": abs, "round": round, "min": min, "max": max, "sum": sum, "pow": pow, **{k: v for k, v in math.__dict__.items() if not k.startswith("__")} } result = eval(expression, {"__builtins__": {}}, allowed) return f"Result: {result}" except Exception as e: return f"Error: {str(e)}" def search_info( query: Annotated[str, "Search query"] ) -> str: """Search for information (mock implementation).""" # In production, integrate with actual search API return f"Search results for '{query}': [Mock data - integrate with real search API]" with llm_config: # Tool-enabled assistant assistant = ConversableAgent( name="assistant", system_message="You are a helpful assistant with access to tools. Use them when appropriate.", ) # Register tools assistant.register_function(calculate) assistant.register_function(search_info) # User proxy user_proxy = ConversableAgent( name="user", system_message="You represent the user.", human_input_mode="NEVER", # Automated for RunAgent ) def invoke_with_tools(message: str, max_turns: int = 5): """Conversation with tool access.""" try: result = user_proxy.initiate_chat( recipient=assistant, message=message, max_turns=max_turns ) return { "status": "success", "result": result, "tools_used": ["calculate", "search_info"] } except Exception as e: return { "status": "error", "error": str(e) } ``` ### 3. Conditional Conversation Flow ```python theme={null} # conditional_flow.py from autogen import ConversableAgent, LLMConfig llm_config = LLMConfig(api_type="openai", model="gpt-4o-mini") with llm_config: classifier = ConversableAgent( name="classifier", system_message="Classify user queries into categories: technical, general, urgent.", ) technical_expert = ConversableAgent( name="technical_expert", system_message="You are a technical expert. Provide detailed technical answers.", ) general_assistant = ConversableAgent( name="general_assistant", system_message="You are a general assistant. Provide helpful, friendly responses.", ) def smart_route(message: str, max_turns: int = 5): """Route queries to appropriate agents based on classification.""" try: # First, classify the query classification = classifier.initiate_chat( recipient=general_assistant, message=f"Classify this query: {message}", max_turns=2 ) # Route based on classification (simplified) if "technical" in str(classification).lower(): agent = technical_expert else: agent = general_assistant # Handle the query with appropriate agent result = agent.initiate_chat( recipient=classifier, message=message, max_turns=max_turns ) return { "status": "success", "classification": str(classification), "result": result, "handler": agent.name } except Exception as e: return { "status": "error", "error": str(e) } ``` *** ## Testing Your AG2 Agent ### Python Client ```python theme={null} # test_ag2.py from runagent import RunAgentClient # Test non-streaming client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="ag2_invoke", local=True ) result = client.run( message="The solar system has 8 planets.", max_turns=3 ) print(f"Conversation result: {result}") # Test streaming stream_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="ag2_stream", local=True ) print("\nStreaming conversation:") for chunk in stream_client.run( message="Explain quantum computing", max_turns=4 ): if chunk.get("type") == "text": print(f"{chunk.get('sender', 'Agent')}: {chunk.get('content')}") ``` ### JavaScript Client ```javascript theme={null} // test_ag2.js import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'ag2_invoke', local: true }); await client.initialize(); // Test conversation const result = await client.run({ message: 'What is artificial intelligence?', max_turns: 3 }); console.log('Result:', result); // Test streaming const streamClient = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'ag2_stream', local: true }); await streamClient.initialize(); for await (const chunk of streamClient.run({ message: 'Explain machine learning', max_turns: 3 })) { if (chunk.type === 'text') { console.log(`${chunk.sender}: ${chunk.content}`); } } ``` ### Go Client ```go theme={null} package main import ( "context" "fmt" "github.com/runagent-dev/runagent-go/pkg/client" "encoding/json" ) func main() { client, _ := client.New( "your_agent_id_here", "ag2_invoke", true, ) defer client.Close() ctx := context.Background() result, _ := client.Run(ctx, map[string]interface{}{ "message": "Explain neural networks", "max_turns": 3, }) fmt.Printf("Result: %v\n", result) } ``` *** ## Configuration Examples ### Single Conversation Agent ```json theme={null} { "agent_name": "ag2-assistant", "framework": "ag2", "agent_architecture": { "entrypoints": [ { "file": "conversation.py", "module": "invoke", "tag": "ag2_invoke" }, { "file": "conversation.py", "module": "stream", "tag": "ag2_stream" } ] } } ``` ### Multi-Agent Workflow ```json theme={null} { "agent_name": "ag2-research-team", "framework": "ag2", "agent_architecture": { "entrypoints": [ { "file": "conversation.py", "module": "invoke", "tag": "simple_chat" }, { "file": "advanced_conversation.py", "module": "research_workflow", "tag": "research" }, { "file": "tool_agent.py", "module": "invoke_with_tools", "tag": "tools" } ] } } ``` *** ## Best Practices ### 1. **Agent Design** * Keep system messages clear and specific * Define roles explicitly for each agent * Use appropriate max\_turns to prevent infinite loops ### 2. **Conversation Management** * Set reasonable max\_turns (typically 3-10) * Handle conversation state appropriately * Implement timeout mechanisms for long conversations ### 3. **Error Handling** * Always wrap AG2 operations in try-catch blocks * Return structured error responses * Log conversation failures for debugging ### 4. **Tool Integration** * Register tools explicitly with agents * Use type annotations for tool parameters * Implement safe tool execution with proper validation ### 5. **Performance** * Reuse agent instances when possible * Monitor conversation length and token usage * Implement caching for repeated queries *** ## Common Patterns ### Fact-Checking Pattern Use multiple agents to verify information: ```python theme={null} assistant → fact_checker → validator ``` ### Research Pattern Multi-stage information gathering: ```python theme={null} researcher → analyst → writer ``` ### Routing Pattern Direct queries to specialized agents: ```python theme={null} classifier → [technical_expert | general_assistant] ``` ### Tool-Augmented Pattern Agents with external capabilities: ```python theme={null} assistant + [calculator, search, database] ``` *** ## Troubleshooting ### Common Issues **1. API Key Not Found** * **Solution**: Ensure `OPENAI_API_KEY` is set in environment * Check `.env` file exists and is loaded * Verify key is valid and has credits **2. Conversation Hangs** * **Solution**: Set appropriate `max_turns` parameter * Reduce conversation complexity * Implement timeout mechanisms **3. Agent Not Responding** * **Solution**: Check system messages are clear * Verify LLM config is correct * Review agent initialization code **4. Tool Execution Fails** * **Solution**: Verify tool registration * Check tool function signatures * Ensure type annotations are correct **5. Streaming Not Working** * **Solution**: Use `assistant.run()` instead of `initiate_chat()` * Check event handling in streaming loop * Verify client supports streaming ### Debug Tips Enable verbose logging: ```python theme={null} import logging logging.basicConfig(level=logging.DEBUG) def invoke(message, max_turns): print(f"Debug: Starting conversation with message: {message}") print(f"Debug: Max turns: {max_turns}") # ... rest of code ``` Test conversation locally: ```python theme={null} # test_local.py from conversation import invoke result = invoke("Test message", max_turns=2) print(f"Result: {result}") ``` *** ## Performance Optimization ### 1. **Agent Reuse** Create agents once and reuse: ```python theme={null} # Global agent instances _assistant = None _fact_checker = None def get_agents(): global _assistant, _fact_checker if _assistant is None: llm_config = LLMConfig(api_type="openai", model="gpt-4o-mini") with llm_config: _assistant = ConversableAgent(...) _fact_checker = ConversableAgent(...) return _assistant, _fact_checker ``` ### 2. **Conversation Limits** Set appropriate limits: ```python theme={null} def invoke(message, max_turns=5): # Reasonable max_turns prevents runaway conversations if max_turns > 20: max_turns = 20 # ... rest of code ``` ### 3. **Caching** Implement response caching for repeated queries: ```python theme={null} from functools import lru_cache @lru_cache(maxsize=100) def invoke_cached(message, max_turns): return invoke(message, max_turns) ``` *** ## Next Steps * **[Advanced Patterns](/how-to/advanced-tasks)** - Learn advanced AG2 patterns * **[Production Deployment](/runagent-cloud/cloud-deployment)** - Deploy to production * **[Multi-Language Access](/tutorials/multi-language-wrapper)** - Access from different languages * **[Performance Tuning](/explanation/production-considerations)** - Optimize for production *** ## Additional Resources * [AG2 Documentation](https://ag2.ai/docs) * [AG2 GitHub](https://github.com/ag2ai/ag2) * [RunAgent Discord Community](https://discord.gg/Q9P9AdHVHz) * [RunAgent Documentation](https://docs.run-agent.ai) *** **🎉 Great work!** You've learned how to deploy AG2 multi-agent systems with RunAgent. AG2's collaborative agent architecture combined with RunAgent's multi-language access creates powerful, flexible conversational AI systems! # Agno Source: https://docs.run-agent.ai/how-to/frameworks/agno Deploy Agno AI agents with RunAgent **Prerequisites**: Basic understanding of Agno and completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview Agno is a framework for building AI agents with print response capabilities and streaming support. RunAgent makes it easy to deploy Agno agents and access them from any programming language while maintaining the framework's unique characteristics. ## Quick Start ### 1. Create an Agno Agent ```bash theme={null} runagent init my-agno-agent --framework agno cd my-agno-agent ``` ### 2. Install Dependencies ```bash theme={null} pip install -r requirements.txt ``` ### 3. Configure Your Agent The generated `runagent.config.json` will be pre-configured for Agno: ```json theme={null} { "agent_name": "my-agno-agent", "description": "Agno AI agent with print capabilities", "framework": "agno", "agent_architecture": { "entrypoints": [ { "file": "agent.py", "module": "agno_agent", "tag": "main" } ] } } ``` ## Basic Agno Agent Here's a simple Agno agent that demonstrates the core concepts: ```python agent.py theme={null} from agno import Agent, Tool from typing import Dict, Any, List, Optional import json from datetime import datetime # Define tools def calculate(expression: str) -> str: """Calculate mathematical expressions safely""" try: # Simple safe evaluation (in production, use a proper math parser) allowed_chars = set('0123456789+-*/.() ') if all(c in allowed_chars for c in expression): result = eval(expression) return f"Result: {result}" else: return "Error: Invalid characters in expression" except Exception as e: return f"Error: {str(e)}" def get_current_time() -> str: """Get current time""" return datetime.now().strftime("%Y-%m-%d %H:%M:%S") def format_text(text: str, format_type: str = "uppercase") -> str: """Format text in different ways""" if format_type == "uppercase": return text.upper() elif format_type == "lowercase": return text.lower() elif format_type == "title": return text.title() else: return text # Create tools tools = [ Tool(name="calculate", function=calculate, description="Calculate mathematical expressions"), Tool(name="get_time", function=get_current_time, description="Get current time"), Tool(name="format_text", function=format_text, description="Format text in different ways") ] # Create Agno agent agno_agent = Agent( name="AgnoAssistant", tools=tools, system_message="You are a helpful Agno assistant. You can perform calculations, get time, and format text. Always show your work step by step." ) def agno_agent(message: str, user_id: str = "default") -> Dict[str, Any]: """Main entrypoint for the Agno agent""" try: # Process message with Agno response = agno_agent.process_message(message) return { "response": response, "user_id": user_id, "timestamp": datetime.now().isoformat(), "status": "success" } except Exception as e: return { "response": f"Error: {str(e)}", "user_id": user_id, "timestamp": datetime.now().isoformat(), "status": "error" } ``` ## Advanced Agno Patterns ### 1. Streaming Agno Agent ```python streaming_agno.py theme={null} from typing import Iterator, Dict, Any from agno import Agent, Tool def streaming_agno_agent(message: str, user_id: str = "default") -> Iterator[str]: """Streaming Agno agent with step-by-step output""" yield f"🤖 Agno Agent starting processing...\n\n" # Initialize agent agent = Agent( name="StreamingAgnoAssistant", tools=tools, system_message="You are a helpful Agno assistant that shows your work step by step." ) yield f"📝 Processing message: {message}\n\n" # Simulate step-by-step processing yield "🔍 Analyzing request...\n" yield "🛠️ Selecting appropriate tools...\n" yield "⚙️ Executing operations...\n" yield "📊 Formatting results...\n\n" # Process message response = agent.process_message(message) yield f"✅ Response: {response}\n\n" yield "🎉 Processing complete!" ``` ### 2. Specialized Agno Agents ```python specialized_agno.py theme={null} from agno import Agent, Tool from typing import Dict, Any # Math Agent def math_agent(problem: str, user_id: str) -> Dict[str, Any]: """Math-focused Agno agent""" math_tools = [ Tool(name="calculate", function=calculate, description="Calculate mathematical expressions"), Tool(name="solve_equation", function=lambda x: f"Solving equation: {x}", description="Solve equations"), Tool(name="convert_units", function=lambda x: f"Converting units: {x}", description="Convert between units") ] agent = Agent( name="MathAssistant", tools=math_tools, system_message="You are a math assistant. Show all steps and explain your reasoning." ) response = agent.process_message(problem) return { "response": response, "agent_type": "math", "user_id": user_id, "status": "success" } # Text Processing Agent def text_agent(text: str, operation: str, user_id: str) -> Dict[str, Any]: """Text processing Agno agent""" text_tools = [ Tool(name="format_text", function=format_text, description="Format text in different ways"), Tool(name="count_words", function=lambda x: f"Word count: {len(x.split())}", description="Count words"), Tool(name="extract_keywords", function=lambda x: f"Keywords: {x.split()[:5]}", description="Extract keywords") ] agent = Agent( name="TextAssistant", tools=text_tools, system_message="You are a text processing assistant. Help with text manipulation and analysis." ) response = agent.process_message(f"Process this text: {text} with operation: {operation}") return { "response": response, "agent_type": "text", "user_id": user_id, "status": "success" } # Data Analysis Agent def data_agent(data: str, analysis_type: str, user_id: str) -> Dict[str, Any]: """Data analysis Agno agent""" data_tools = [ Tool(name="calculate", function=calculate, description="Calculate mathematical expressions"), Tool(name="statistics", function=lambda x: f"Statistics for: {x}", description="Calculate statistics"), Tool(name="visualize", function=lambda x: f"Visualization: {x}", description="Create data visualizations") ] agent = Agent( name="DataAssistant", tools=data_tools, system_message="You are a data analysis assistant. Help analyze and visualize data." ) response = agent.process_message(f"Analyze this data: {data} with analysis type: {analysis_type}") return { "response": response, "agent_type": "data", "user_id": user_id, "status": "success" } ``` ### 3. Multi-Step Agno Workflow ```python workflow_agno.py theme={null} from agno import Agent, Tool from typing import Dict, Any, List def multi_step_agno_agent(task: str, user_id: str) -> Dict[str, Any]: """Multi-step Agno workflow agent""" # Step 1: Planning Agent planning_tools = [ Tool(name="break_down_task", function=lambda x: f"Breaking down: {x}", description="Break down complex tasks"), Tool(name="identify_requirements", function=lambda x: f"Requirements: {x}", description="Identify requirements") ] planning_agent = Agent( name="PlanningAgent", tools=planning_tools, system_message="You are a planning agent. Break down complex tasks into manageable steps." ) # Step 2: Execution Agent execution_tools = [ Tool(name="calculate", function=calculate, description="Calculate mathematical expressions"), Tool(name="format_text", function=format_text, description="Format text in different ways"), Tool(name="get_time", function=get_current_time, description="Get current time") ] execution_agent = Agent( name="ExecutionAgent", tools=execution_tools, system_message="You are an execution agent. Execute the planned steps." ) # Step 3: Review Agent review_tools = [ Tool(name="check_accuracy", function=lambda x: f"Checking accuracy: {x}", description="Check accuracy"), Tool(name="format_output", function=lambda x: f"Formatting output: {x}", description="Format final output") ] review_agent = Agent( name="ReviewAgent", tools=review_tools, system_message="You are a review agent. Review and improve the results." ) # Execute workflow try: # Planning phase plan = planning_agent.process_message(f"Plan this task: {task}") # Execution phase execution = execution_agent.process_message(f"Execute this plan: {plan}") # Review phase review = review_agent.process_message(f"Review this result: {execution}") return { "task": task, "plan": plan, "execution": execution, "review": review, "user_id": user_id, "status": "success" } except Exception as e: return { "task": task, "error": str(e), "user_id": user_id, "status": "error" } ``` ## Configuration for Multiple Agents Update your `runagent.config.json` to include multiple Agno agents: ```json theme={null} { "agent_name": "advanced-agno-agent", "description": "Advanced Agno multi-agent system", "framework": "agno", "agent_architecture": { "entrypoints": [ { "file": "agent.py", "module": "agno_agent", "tag": "main" }, { "file": "streaming_agno.py", "module": "streaming_agno_agent", "tag": "streaming" }, { "file": "specialized_agno.py", "module": "math_agent", "tag": "math" }, { "file": "specialized_agno.py", "module": "text_agent", "tag": "text" }, { "file": "specialized_agno.py", "module": "data_agent", "tag": "data" }, { "file": "workflow_agno.py", "module": "multi_step_agno_agent", "tag": "workflow" } ] } } ``` ## Testing Your Agno Agent ### Python Client ```python test_agno.py theme={null} from runagent import RunAgentClient # Connect to your Agno agent client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True ) # Test basic functionality result = client.run(message="Calculate 2 + 2 * 3", user_id="test_user") print(f"Math Result: {result['response']}") # Test text processing text_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="text", local=True ) text_result = text_client.run( text="hello world", operation="uppercase", user_id="test_user" ) print(f"Text Result: {text_result['response']}") # Test streaming stream_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="streaming", local=True ) print("Streaming Agno workflow:") for chunk in stream_client.run(message="Calculate the area of a circle with radius 5", user_id="test_user"): print(chunk, end="", flush=True) ``` ### JavaScript Client ```javascript test_agno.js theme={null} import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'main', local: true }); await client.initialize(); const result = await client.run({ message: 'Calculate 2 + 2 * 3', user_id: 'test_user' }); console.log('Math Result:', result.response); ``` ## Best Practices ### 1. **Tool Design** * Create focused, single-purpose tools * Provide clear tool descriptions * Handle tool errors gracefully ### 2. **Agent Configuration** * Use appropriate system messages * Configure agent behavior clearly * Test agent responses ### 3. **Error Handling** * Implement try-catch blocks * Provide meaningful error messages * Log errors for debugging ### 4. **Performance** * Optimize tool execution * Use caching when appropriate * Monitor agent performance ## Common Patterns Use Agno agents for mathematical calculations and problem-solving. Create agents specialized in text processing and formatting. Build agents for data analysis and visualization. Implement complex workflows with multiple agent steps. ## Troubleshooting ### Common Issues 1. **Tool Execution Errors** * Check tool definitions * Verify tool permissions * Handle tool errors 2. **Agent Configuration** * Verify system messages * Check agent settings * Test agent responses 3. **Performance Issues** * Monitor tool execution time * Optimize agent configuration * Use caching when appropriate ### Debug Tips ```python theme={null} # Add debugging to your Agno agents def debug_agno_agent(message: str, user_id: str) -> Dict[str, Any]: print(f"Debug: Processing message from {user_id}: {message}") # Your agent logic here print(f"Debug: Response generated: {response}") return result ``` ## Performance Optimization ### 1. **Tool Optimization** * Cache expensive tool results * Optimize tool execution * Use async tools when possible ### 2. **Agent Configuration** * Optimize system messages * Configure appropriate timeouts * Use efficient agent settings ### 3. **Workflow Optimization** * Minimize unnecessary steps * Use parallel processing when possible * Optimize data flow ## Next Steps Learn advanced Agno patterns and techniques Deploy your Agno agents to production Access your Agno agents from different languages Optimize your Agno agents for production **🎉 Excellent work!** You've learned how to deploy Agno agents with RunAgent. Agno's unique print response capabilities combined with RunAgent's multi-language access create powerful, transparent AI systems! # CrewAI Source: https://docs.run-agent.ai/how-to/frameworks/crewai Deploy CrewAI multi-agent systems with RunAgent **Prerequisites**: Basic understanding of CrewAI and completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview CrewAI is a framework for building multi-agent systems where different AI agents collaborate to solve complex tasks. RunAgent makes it easy to deploy CrewAI crews and access them from any programming language. ## Quick Start ### 1. Create a CrewAI Agent ```bash theme={null} runagent init my-crewai-agent --framework crewai cd my-crewai-agent ``` ### 2. Install Dependencies ```bash theme={null} pip install -r requirements.txt ``` ### 3. Configure Your Agent The generated `runagent.config.json` will be pre-configured for CrewAI: ```json theme={null} { "agent_name": "my-crewai-agent", "description": "CrewAI multi-agent system", "framework": "crewai", "agent_architecture": { "entrypoints": [ { "file": "crew.py", "module": "research_crew", "tag": "research" } ] } } ``` ## Basic CrewAI Agent Here's a simple CrewAI crew that demonstrates the core concepts: ```python crew.py theme={null} from crewai import Agent, Task, Crew, Process from langchain_openai import ChatOpenAI from typing import Dict, Any, List # Initialize the LLM llm = ChatOpenAI(model="gpt-4", temperature=0.7) # Define agents researcher = Agent( role='Research Analyst', goal='Gather comprehensive information on given topics', backstory='You are an expert research analyst with years of experience in data collection and analysis.', verbose=True, allow_delegation=False, llm=llm ) writer = Agent( role='Content Writer', goal='Create engaging and informative content based on research', backstory='You are a skilled content writer who can transform research into compelling narratives.', verbose=True, allow_delegation=False, llm=llm ) reviewer = Agent( role='Content Reviewer', goal='Review and improve content for accuracy and quality', backstory='You are a meticulous reviewer who ensures content meets high standards.', verbose=True, allow_delegation=False, llm=llm ) def research_crew(topic: str) -> Dict[str, Any]: """Main entrypoint for the research crew""" try: # Define tasks research_task = Task( description=f'Research the topic: {topic}. Gather key facts, statistics, and insights.', agent=researcher, expected_output='A comprehensive research report with key findings' ) writing_task = Task( description='Write an engaging article based on the research findings', agent=writer, expected_output='A well-structured article with introduction, body, and conclusion' ) review_task = Task( description='Review the article for accuracy, clarity, and quality', agent=reviewer, expected_output='A polished, publication-ready article' ) # Create crew crew = Crew( agents=[researcher, writer, reviewer], tasks=[research_task, writing_task, review_task], process=Process.sequential, verbose=True ) # Execute the crew result = crew.kickoff() return { "topic": topic, "result": str(result), "status": "success", "agents_used": ["researcher", "writer", "reviewer"] } except Exception as e: return { "topic": topic, "result": f"Error: {str(e)}", "status": "error", "agents_used": [] } ``` ## Advanced CrewAI Patterns ### 1. Hierarchical Crew Structure ```python hierarchical_crew.py theme={null} from crewai import Agent, Task, Crew, Process from typing import Dict, Any, List # Manager agent manager = Agent( role='Project Manager', goal='Coordinate team efforts and ensure project completion', backstory='You are an experienced project manager who excels at team coordination.', verbose=True, allow_delegation=True, llm=llm ) # Specialized agents data_analyst = Agent( role='Data Analyst', goal='Analyze data and extract insights', backstory='You are a data expert with strong analytical skills.', verbose=True, allow_delegation=False, llm=llm ) content_creator = Agent( role='Content Creator', goal='Create engaging content based on data insights', backstory='You are a creative content creator who makes data accessible.', verbose=True, allow_delegation=False, llm=llm ) quality_assurance = Agent( role='Quality Assurance', goal='Ensure content quality and accuracy', backstory='You are a detail-oriented QA specialist.', verbose=True, allow_delegation=False, llm=llm ) def hierarchical_crew(project_description: str) -> Dict[str, Any]: """Hierarchical crew with manager delegation""" try: # Manager task management_task = Task( description=f'Manage the project: {project_description}. Delegate tasks to appropriate team members.', agent=manager, expected_output='Project plan and task assignments' ) # Data analysis task analysis_task = Task( description='Analyze relevant data for the project', agent=data_analyst, expected_output='Data analysis report with key insights' ) # Content creation task content_task = Task( description='Create content based on data analysis', agent=content_creator, expected_output='High-quality content ready for review' ) # QA task qa_task = Task( description='Review and improve the content', agent=quality_assurance, expected_output='Final, polished content' ) # Create crew crew = Crew( agents=[manager, data_analyst, content_creator, quality_assurance], tasks=[management_task, analysis_task, content_task, qa_task], process=Process.sequential, verbose=True ) result = crew.kickoff() return { "project": project_description, "result": str(result), "status": "success", "structure": "hierarchical" } except Exception as e: return { "project": project_description, "result": f"Error: {str(e)}", "status": "error", "structure": "hierarchical" } ``` ### 2. Parallel Processing Crew ```python parallel_crew.py theme={null} from crewai import Agent, Task, Crew, Process from typing import Dict, Any, List # Parallel processing agents market_researcher = Agent( role='Market Researcher', goal='Research market trends and opportunities', backstory='You are a market research expert.', verbose=True, allow_delegation=False, llm=llm ) competitor_analyst = Agent( role='Competitor Analyst', goal='Analyze competitor strategies and positioning', backstory='You are a competitive intelligence specialist.', verbose=True, allow_delegation=False, llm=llm ) customer_researcher = Agent( role='Customer Researcher', goal='Understand customer needs and preferences', backstory='You are a customer insights expert.', verbose=True, allow_delegation=False, llm=llm ) synthesis_agent = Agent( role='Synthesis Agent', goal='Combine insights from all research areas', backstory='You are an expert at synthesizing complex information.', verbose=True, allow_delegation=False, llm=llm ) def parallel_crew(research_topic: str) -> Dict[str, Any]: """Parallel processing crew for comprehensive research""" try: # Parallel research tasks market_task = Task( description=f'Research market trends for: {research_topic}', agent=market_researcher, expected_output='Market analysis report' ) competitor_task = Task( description=f'Analyze competitors in: {research_topic}', agent=competitor_analyst, expected_output='Competitive analysis report' ) customer_task = Task( description=f'Research customer needs for: {research_topic}', agent=customer_researcher, expected_output='Customer insights report' ) # Synthesis task synthesis_task = Task( description='Synthesize all research findings into a comprehensive report', agent=synthesis_agent, expected_output='Comprehensive research synthesis' ) # Create crew with parallel processing crew = Crew( agents=[market_researcher, competitor_analyst, customer_researcher, synthesis_agent], tasks=[market_task, competitor_task, customer_task, synthesis_task], process=Process.sequential, # Synthesis happens after parallel tasks verbose=True ) result = crew.kickoff() return { "topic": research_topic, "result": str(result), "status": "success", "process": "parallel" } except Exception as e: return { "topic": research_topic, "result": f"Error: {str(e)}", "status": "error", "process": "parallel" } ``` ### 3. Streaming CrewAI Agent ```python streaming_crew.py theme={null} from typing import Iterator, Dict, Any from crewai import Agent, Task, Crew, Process def streaming_crew_agent(topic: str) -> Iterator[str]: """Streaming CrewAI agent with progress updates""" yield f"🚀 Starting CrewAI workflow for: {topic}\n\n" # Simulate crew setup yield "👥 Setting up research crew...\n" yield " • Research Analyst: Ready\n" yield " • Content Writer: Ready\n" yield " • Content Reviewer: Ready\n\n" # Simulate task execution tasks = [ "📊 Research Analyst: Gathering information...", "📊 Research Analyst: Analyzing data...", "📊 Research Analyst: Compiling findings...", "✍️ Content Writer: Creating article structure...", "✍️ Content Writer: Writing content...", "✍️ Content Writer: Refining narrative...", "🔍 Content Reviewer: Checking accuracy...", "🔍 Content Reviewer: Improving clarity...", "🔍 Content Reviewer: Finalizing quality...", "✅ Crew: Workflow complete!" ] for i, task in enumerate(tasks): yield f"Step {i+1}: {task}\n" # Simulate processing time import time time.sleep(0.3) yield f"\n🎉 CrewAI workflow complete! Topic '{topic}' processed successfully." ``` ## Configuration for Multiple Crews Update your `runagent.config.json` to include multiple CrewAI crews: ```json theme={null} { "agent_name": "advanced-crewai-agent", "description": "Advanced CrewAI multi-agent system", "framework": "crewai", "agent_architecture": { "entrypoints": [ { "file": "crew.py", "module": "research_crew", "tag": "research" }, { "file": "hierarchical_crew.py", "module": "hierarchical_crew", "tag": "hierarchical" }, { "file": "parallel_crew.py", "module": "parallel_crew", "tag": "parallel" }, { "file": "streaming_crew.py", "module": "streaming_crew_agent", "tag": "streaming" } ] } } ``` ## Testing Your CrewAI Agent ### Python Client ```python test_crewai.py theme={null} from runagent import RunAgentClient # Connect to your CrewAI agent client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="research", local=True ) # Test research crew result = client.run(topic="Artificial Intelligence in Healthcare") print(f"Research Result: {result['result']}") print(f"Agents Used: {result['agents_used']}") # Test hierarchical crew hierarchical_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="hierarchical", local=True ) hierarchical_result = hierarchical_client.run(project_description="Develop a marketing strategy for a new product") print(f"Hierarchical Result: {hierarchical_result['result']}") # Test streaming stream_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="streaming", local=True ) print("Streaming CrewAI workflow:") for chunk in stream_client.run(topic="Climate Change Solutions"): print(chunk, end="", flush=True) ``` ### JavaScript Client ```javascript test_crewai.js theme={null} import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'research', local: true }); await client.initialize(); const result = await client.run({ topic: 'Artificial Intelligence in Healthcare' }); console.log('Research Result:', result.result); console.log('Agents Used:', result.agents_used); ``` ## Best Practices ### 1. **Agent Design** * Give agents clear, specific roles * Use descriptive backstories * Set appropriate delegation permissions ### 2. **Task Definition** * Make tasks specific and measurable * Set clear expected outputs * Consider task dependencies ### 3. **Crew Organization** * Choose appropriate process (sequential vs hierarchical) * Balance agent specialization with collaboration * Monitor crew performance ### 4. **Error Handling** * Implement try-catch blocks * Provide meaningful error messages * Log errors for debugging ## Common Patterns Use multiple agents to research topics from different angles and synthesize findings. Create a pipeline of agents for content creation, editing, and review. Deploy specialized agents to tackle different aspects of complex problems. Use multiple reviewers to ensure high-quality outputs. ## Troubleshooting ### Common Issues 1. **Agent Communication Errors** * Check agent delegation settings * Ensure proper task dependencies * Verify agent roles are clear 2. **Task Execution Failures** * Review task descriptions * Check expected outputs * Verify agent capabilities 3. **Memory Issues** * Limit conversation history * Use appropriate context windows * Implement memory management ### Debug Tips ```python theme={null} # Add debugging to your crews def debug_crew(topic: str) -> Dict[str, Any]: print(f"Debug: Starting crew for topic: {topic}") # Your crew logic here print(f"Debug: Crew completed for topic: {topic}") return result ``` ## Performance Optimization ### 1. **Parallel Processing** * Use parallel tasks when possible * Avoid unnecessary dependencies * Optimize agent communication ### 2. **Resource Management** * Monitor memory usage * Implement timeout handling * Use appropriate LLM models ### 3. **Caching** * Cache expensive operations * Reuse agent instances * Implement result caching ## Next Steps Learn advanced CrewAI patterns and techniques Deploy your CrewAI system to production Access your CrewAI crews from different languages Optimize your CrewAI system for production **🎉 Excellent work!** You've learned how to deploy CrewAI multi-agent systems with RunAgent. CrewAI's collaborative agent approach combined with RunAgent's multi-language access creates powerful distributed AI systems! # Custom Framework Source: https://docs.run-agent.ai/how-to/frameworks/custom Deploy agents built with any Python-based framework **Prerequisites**: Basic Python knowledge and completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview RunAgent supports any Python-based AI framework by defining simple entrypoint functions. This guide shows you how to integrate custom frameworks and create your own AI agents. ## Quick Start ### 1. Create a Custom Agent ```bash theme={null} runagent init my-custom-agent --framework custom cd my-custom-agent ``` ### 2. Install Your Framework ```bash theme={null} pip install your-framework-name ``` ### 3. Configure Your Agent The generated `runagent.config.json` will be pre-configured for custom frameworks: ```json theme={null} { "agent_name": "my-custom-agent", "description": "Custom AI agent", "framework": "custom", "agent_architecture": { "entrypoints": [ { "file": "main.py", "module": "custom_agent", "tag": "main" } ] } } ``` ## Basic Custom Agent Here's a simple custom agent that demonstrates the core concepts: ```python main.py theme={null} from typing import Dict, Any, List, Optional import json from datetime import datetime class CustomAgent: def __init__(self): self.name = "CustomAgent" self.version = "1.0.0" self.capabilities = ["text_processing", "data_analysis", "custom_logic"] def process_request(self, request: str, context: Dict[str, Any] = None) -> Dict[str, Any]: """Process a request using custom logic""" try: # Your custom AI logic here response = self._generate_response(request, context) return { "response": response, "agent": self.name, "version": self.version, "timestamp": datetime.now().isoformat(), "status": "success" } except Exception as e: return { "response": f"Error: {str(e)}", "agent": self.name, "version": self.version, "timestamp": datetime.now().isoformat(), "status": "error" } def _generate_response(self, request: str, context: Dict[str, Any] = None) -> str: """Generate response using custom logic""" # Example: Simple rule-based response if "hello" in request.lower(): return "Hello! How can I help you today?" elif "help" in request.lower(): return "I can help you with various tasks. What do you need?" else: return f"I received your request: {request}. This is a custom response." def custom_agent(request: str, context: Dict[str, Any] = None) -> Dict[str, Any]: """Main entrypoint for the custom agent""" agent = CustomAgent() return agent.process_request(request, context) ``` ## Advanced Custom Patterns ### 1. Streaming Custom Agent ```python streaming_custom.py theme={null} from typing import Iterator, Dict, Any import time def streaming_custom_agent(request: str, context: Dict[str, Any] = None) -> Iterator[str]: """Streaming custom agent with step-by-step output""" yield f"🚀 Custom Agent starting processing...\n\n" yield f"📝 Processing request: {request}\n\n" # Simulate step-by-step processing steps = [ "🔍 Analyzing request...", "🧠 Applying custom logic...", "⚙️ Processing data...", "📊 Generating response...", "✅ Finalizing output..." ] for i, step in enumerate(steps): yield f"Step {i+1}: {step}\n" time.sleep(0.5) # Simulate processing time yield f"\n🎉 Custom processing complete! Response: {request} processed successfully." ``` ### 2. Multi-Modal Custom Agent ```python multimodal_custom.py theme={null} from typing import Dict, Any, List import base64 import json class MultiModalAgent: def __init__(self): self.name = "MultiModalAgent" self.supported_types = ["text", "image", "audio", "data"] def process_multimodal(self, content: str, content_type: str, metadata: Dict[str, Any] = None) -> Dict[str, Any]: """Process multimodal content""" try: if content_type == "text": response = self._process_text(content) elif content_type == "image": response = self._process_image(content) elif content_type == "audio": response = self._process_audio(content) elif content_type == "data": response = self._process_data(content) else: response = f"Unsupported content type: {content_type}" return { "response": response, "content_type": content_type, "agent": self.name, "status": "success" } except Exception as e: return { "response": f"Error processing {content_type}: {str(e)}", "content_type": content_type, "agent": self.name, "status": "error" } def _process_text(self, text: str) -> str: """Process text content""" return f"Processed text: {text[:100]}..." def _process_image(self, image_data: str) -> str: """Process image content""" # In real implementation, decode and process image return f"Processed image: {len(image_data)} bytes" def _process_audio(self, audio_data: str) -> str: """Process audio content""" # In real implementation, decode and process audio return f"Processed audio: {len(audio_data)} bytes" def _process_data(self, data: str) -> str: """Process structured data""" try: parsed_data = json.loads(data) return f"Processed data: {len(parsed_data)} items" except: return f"Processed data: {len(data)} characters" def multimodal_agent(content: str, content_type: str, metadata: Dict[str, Any] = None) -> Dict[str, Any]: """Multimodal custom agent entrypoint""" agent = MultiModalAgent() return agent.process_multimodal(content, content_type, metadata) ``` ### 3. Specialized Custom Agents ```python specialized_custom.py theme={null} from typing import Dict, Any, List import re import json # Document Processing Agent def document_agent(document: str, operation: str, user_id: str) -> Dict[str, Any]: """Document processing custom agent""" try: if operation == "summarize": # Simple summarization (in production, use proper NLP) sentences = document.split('.') summary = '. '.join(sentences[:3]) + '.' response = f"Summary: {summary}" elif operation == "extract_keywords": # Simple keyword extraction words = re.findall(r'\b\w+\b', document.lower()) keywords = list(set(words))[:10] response = f"Keywords: {', '.join(keywords)}" elif operation == "translate": # Simple translation simulation response = f"Translated: {document} (simulated translation)" else: response = f"Unknown operation: {operation}" return { "response": response, "operation": operation, "agent_type": "document", "user_id": user_id, "status": "success" } except Exception as e: return { "response": f"Error: {str(e)}", "operation": operation, "agent_type": "document", "user_id": user_id, "status": "error" } # Code Analysis Agent def code_agent(code: str, language: str, analysis_type: str) -> Dict[str, Any]: """Code analysis custom agent""" try: if analysis_type == "syntax_check": # Simple syntax check simulation if code.strip(): response = "Syntax check passed (simulated)" else: response = "Syntax check failed: Empty code" elif analysis_type == "complexity": # Simple complexity analysis lines = len(code.split('\n')) functions = code.count('def ') response = f"Complexity: {lines} lines, {functions} functions" elif analysis_type == "security": # Simple security check if 'eval(' in code or 'exec(' in code: response = "Security warning: Potentially dangerous code detected" else: response = "Security check passed (simulated)" else: response = f"Unknown analysis type: {analysis_type}" return { "response": response, "language": language, "analysis_type": analysis_type, "agent_type": "code", "status": "success" } except Exception as e: return { "response": f"Error: {str(e)}", "language": language, "analysis_type": analysis_type, "agent_type": "code", "status": "error" } # Data Processing Agent def data_agent(data: str, format_type: str, operation: str) -> Dict[str, Any]: """Data processing custom agent""" try: if format_type == "json": parsed_data = json.loads(data) if operation == "validate": response = "JSON validation passed" elif operation == "transform": response = f"Transformed {len(parsed_data)} items" else: response = f"Unknown operation: {operation}" elif format_type == "csv": lines = data.split('\n') if operation == "validate": response = f"CSV validation passed: {len(lines)} lines" elif operation == "transform": response = f"Transformed {len(lines)} CSV lines" else: response = f"Unknown operation: {operation}" else: response = f"Unsupported format: {format_type}" return { "response": response, "format_type": format_type, "operation": operation, "agent_type": "data", "status": "success" } except Exception as e: return { "response": f"Error: {str(e)}", "format_type": format_type, "operation": operation, "agent_type": "data", "status": "error" } ``` ## Configuration for Multiple Agents Update your `runagent.config.json` to include multiple custom agents: ```json theme={null} { "agent_name": "advanced-custom-agent", "description": "Advanced custom multi-agent system", "framework": "custom", "agent_architecture": { "entrypoints": [ { "file": "main.py", "module": "custom_agent", "tag": "main" }, { "file": "streaming_custom.py", "module": "streaming_custom_agent", "tag": "streaming" }, { "file": "multimodal_custom.py", "module": "multimodal_agent", "tag": "multimodal" }, { "file": "specialized_custom.py", "module": "document_agent", "tag": "document" }, { "file": "specialized_custom.py", "module": "code_agent", "tag": "code" }, { "file": "specialized_custom.py", "module": "data_agent", "tag": "data" } ] } } ``` ## Testing Your Custom Agent ### Python Client ```python test_custom.py theme={null} from runagent import RunAgentClient # Connect to your custom agent client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="main", local=True ) # Test basic functionality result = client.run(request="Hello, how are you?", context={"user": "test"}) print(f"Response: {result['response']}") # Test document processing doc_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="document", local=True ) doc_result = doc_client.run( document="This is a sample document for testing.", operation="summarize", user_id="test_user" ) print(f"Document Result: {doc_result['response']}") # Test streaming stream_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="streaming", local=True ) print("Streaming custom workflow:") for chunk in stream_client.run(request="Process this data", context={"type": "test"}): print(chunk, end="", flush=True) ``` ### JavaScript Client ```javascript test_custom.js theme={null} import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'main', local: true }); await client.initialize(); const result = await client.run({ request: 'Hello, how are you?', context: { user: 'test' } }); console.log('Response:', result.response); ``` ## Best Practices ### 1. **Entrypoint Design** * Keep entrypoint functions simple and focused * Use clear parameter names * Provide meaningful return values ### 2. **Error Handling** * Implement comprehensive error handling * Provide meaningful error messages * Log errors for debugging ### 3. **Performance** * Optimize your custom logic * Use caching when appropriate * Monitor performance metrics ### 4. **Testing** * Test each entrypoint thoroughly * Use mock data for testing * Implement integration tests ## Common Patterns Create agents that use rule-based logic for decision making. Build agents specialized in data transformation and analysis. Create agents that can process different types of content. Implement complex workflows with multiple steps. ## Troubleshooting ### Common Issues 1. **Entrypoint Errors** * Check function signatures * Verify parameter types * Handle exceptions properly 2. **Framework Integration** * Ensure proper imports * Check framework compatibility * Test framework functionality 3. **Performance Issues** * Profile your custom logic * Optimize expensive operations * Use appropriate data structures ### Debug Tips ```python theme={null} # Add debugging to your custom agents def debug_custom_agent(request: str, context: Dict[str, Any] = None) -> Dict[str, Any]: print(f"Debug: Processing request: {request}") print(f"Debug: Context: {context}") # Your custom logic here print(f"Debug: Response generated: {response}") return result ``` ## Performance Optimization ### 1. **Code Optimization** * Use efficient algorithms * Optimize data structures * Minimize memory usage ### 2. **Caching** * Cache expensive operations * Use appropriate cache strategies * Monitor cache performance ### 3. **Async Processing** * Use async/await when appropriate * Implement parallel processing * Optimize I/O operations ## Next Steps Learn advanced custom agent patterns and techniques Deploy your custom agents to production Access your custom agents from different languages Optimize your custom agents for production **🎉 Great work!** You've learned how to deploy custom agents with RunAgent. The flexibility of custom frameworks combined with RunAgent's multi-language access gives you unlimited possibilities for AI agent development! # LangGraph Source: https://docs.run-agent.ai/how-to/frameworks/langgraph Deploy LangGraph agents with RunAgent **Prerequisites**: Basic understanding of LangGraph and completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial ## Overview LangGraph is a powerful framework for building stateful, multi-step AI agents with complex workflows. RunAgent makes it easy to deploy LangGraph agents and access them from any programming language. ## Quick Start ### 1. Create a LangGraph Agent ```bash theme={null} runagent init my-langgraph-agent --framework langgraph cd my-langgraph-agent ``` ### 2. Install Dependencies ```bash theme={null} pip install -r requirements.txt ``` ### 3. Configure Your Agent The generated `runagent.config.json` will be pre-configured for LangGraph: ```json theme={null} { "agent_name": "my-langgraph-agent", "description": "LangGraph agent with stateful workflows", "framework": "langgraph", "agent_architecture": { "entrypoints": [ { "file": "agents.py", "module": "langgraph_agent", "tag": "main" } ] } } ``` ## Basic LangGraph Agent Here's a simple LangGraph agent that demonstrates the core concepts: ```python agents.py theme={null} from typing import Dict, Any, List from langgraph import StateGraph, END from langgraph.graph import StateGraph from langchain_core.messages import HumanMessage, AIMessage from langchain_openai import ChatOpenAI # Define the state structure class AgentState: messages: List[Any] user_input: str response: str step_count: int # Initialize the LLM llm = ChatOpenAI(model="gpt-4", temperature=0.7) def process_input(state: AgentState) -> AgentState: """Process the user input and prepare for reasoning""" state.step_count = 0 state.messages = [HumanMessage(content=state.user_input)] return state def reason_step(state: AgentState) -> AgentState: """Perform reasoning step""" state.step_count += 1 # Add reasoning message reasoning = f"Step {state.step_count}: Analyzing the user's request..." state.messages.append(AIMessage(content=reasoning)) return state def generate_response(state: AgentState) -> AgentState: """Generate the final response""" # Get response from LLM response = llm.invoke(state.messages) state.response = response.content state.messages.append(response) return state def should_continue(state: AgentState) -> str: """Decide whether to continue reasoning or finish""" if state.step_count >= 3: # Max 3 reasoning steps return "finish" elif "complex" in state.user_input.lower(): return "reason" else: return "finish" # Build the graph workflow = StateGraph(AgentState) # Add nodes workflow.add_node("process_input", process_input) workflow.add_node("reason", reason_step) workflow.add_node("generate_response", generate_response) # Add edges workflow.add_edge("process_input", "reason") workflow.add_conditional_edges( "reason", should_continue, { "reason": "reason", "finish": "generate_response" } ) workflow.add_edge("generate_response", END) # Compile the graph app = workflow.compile() def langgraph_agent(user_input: str) -> Dict[str, Any]: """Main entrypoint for the LangGraph agent""" try: # Initialize state initial_state = AgentState( messages=[], user_input=user_input, response="", step_count=0 ) # Run the workflow result = app.invoke(initial_state) return { "response": result.response, "step_count": result.step_count, "messages": [msg.content for msg in result.messages], "status": "success" } except Exception as e: return { "response": f"Error: {str(e)}", "step_count": 0, "messages": [], "status": "error" } ``` ## Advanced LangGraph Patterns ### 1. Multi-Agent Workflows ```python multi_agent.py theme={null} from typing import Dict, Any, List from langgraph import StateGraph, END from langchain_core.messages import HumanMessage, AIMessage, SystemMessage class MultiAgentState: messages: List[Any] user_input: str researcher_output: str writer_output: str final_response: str def researcher_agent(state: MultiAgentState) -> MultiAgentState: """Research agent that gathers information""" research_prompt = f""" Research the following topic: {state.user_input} Provide key facts and insights. """ # Simulate research (in real app, use web search, databases, etc.) state.researcher_output = f"Research findings for: {state.user_input}" return state def writer_agent(state: MultiAgentState) -> MultiAgentState: """Writer agent that creates content""" writer_prompt = f""" Based on this research: {state.researcher_output} Create a comprehensive response to: {state.user_input} """ # Simulate writing (in real app, use LLM) state.writer_output = f"Written content based on: {state.researcher_output}" return state def coordinator_agent(state: MultiAgentState) -> MultiAgentState: """Coordinator that combines outputs""" state.final_response = f""" Research: {state.researcher_output} Content: {state.writer_output} Final Response: Based on the research and writing, here's the complete answer. """ return state # Build multi-agent workflow multi_workflow = StateGraph(MultiAgentState) multi_workflow.add_node("researcher", researcher_agent) multi_workflow.add_node("writer", writer_agent) multi_workflow.add_node("coordinator", coordinator_agent) multi_workflow.add_edge("researcher", "writer") multi_workflow.add_edge("writer", "coordinator") multi_workflow.add_edge("coordinator", END) multi_app = multi_workflow.compile() def multi_agent_workflow(user_input: str) -> Dict[str, Any]: """Multi-agent workflow entrypoint""" initial_state = MultiAgentState( messages=[], user_input=user_input, researcher_output="", writer_output="", final_response="" ) result = multi_app.invoke(initial_state) return { "response": result.final_response, "research": result.researcher_output, "writing": result.writer_output, "status": "success" } ``` ### 2. Conditional Workflows ```python conditional_workflow.py theme={null} from typing import Dict, Any, List from langgraph import StateGraph, END class ConditionalState: user_input: str intent: str response: str confidence: float def classify_intent(state: ConditionalState) -> ConditionalState: """Classify user intent""" input_lower = state.user_input.lower() if any(word in input_lower for word in ["question", "what", "how", "why"]): state.intent = "question" state.confidence = 0.9 elif any(word in input_lower for word in ["task", "do", "help", "assist"]): state.intent = "task" state.confidence = 0.8 else: state.intent = "general" state.confidence = 0.5 return state def handle_question(state: ConditionalState) -> ConditionalState: """Handle question intent""" state.response = f"Answering your question: {state.user_input}" return state def handle_task(state: ConditionalState) -> ConditionalState: """Handle task intent""" state.response = f"Helping you with this task: {state.user_input}" return state def handle_general(state: ConditionalState) -> ConditionalState: """Handle general intent""" state.response = f"General response to: {state.user_input}" return state def route_intent(state: ConditionalState) -> str: """Route based on intent""" return state.intent # Build conditional workflow conditional_workflow = StateGraph(ConditionalState) conditional_workflow.add_node("classify", classify_intent) conditional_workflow.add_node("question_handler", handle_question) conditional_workflow.add_node("task_handler", handle_task) conditional_workflow.add_node("general_handler", handle_general) conditional_workflow.add_edge("classify", "route") conditional_workflow.add_conditional_edges( "classify", route_intent, { "question": "question_handler", "task": "task_handler", "general": "general_handler" } ) conditional_workflow.add_edge("question_handler", END) conditional_workflow.add_edge("task_handler", END) conditional_workflow.add_edge("general_handler", END) conditional_app = conditional_workflow.compile() def conditional_agent(user_input: str) -> Dict[str, Any]: """Conditional workflow entrypoint""" initial_state = ConditionalState( user_input=user_input, intent="", response="", confidence=0.0 ) result = conditional_app.invoke(initial_state) return { "response": result.response, "intent": result.intent, "confidence": result.confidence, "status": "success" } ``` ## Streaming with LangGraph LangGraph agents can also provide streaming responses: ```python streaming_agent.py theme={null} from typing import Iterator, Dict, Any from langgraph import StateGraph, END def streaming_langgraph_agent(user_input: str) -> Iterator[str]: """Streaming LangGraph agent""" yield f"🤖 Starting LangGraph workflow for: {user_input}\n\n" # Simulate workflow steps steps = [ "📝 Processing input...", "🧠 Analyzing context...", "🔍 Gathering information...", "💭 Reasoning through solution...", "✍️ Generating response...", "✅ Finalizing output..." ] for i, step in enumerate(steps): yield f"Step {i+1}: {step}\n" # Simulate processing time import time time.sleep(0.5) yield f"\n🎉 Workflow complete! Response: {user_input} processed successfully." ``` ## Configuration for Multiple Entrypoints Update your `runagent.config.json` to include multiple LangGraph workflows: ```json theme={null} { "agent_name": "advanced-langgraph-agent", "description": "Advanced LangGraph agent with multiple workflows", "framework": "langgraph", "agent_architecture": { "entrypoints": [ { "file": "agents.py", "module": "langgraph_agent", "tag": "basic" }, { "file": "multi_agent.py", "module": "multi_agent_workflow", "tag": "multi_agent" }, { "file": "conditional_workflow.py", "module": "conditional_agent", "tag": "conditional" }, { "file": "streaming_agent.py", "module": "streaming_langgraph_agent", "tag": "streaming" } ] } } ``` ## Testing Your LangGraph Agent ### Python Client ```python test_langgraph.py theme={null} from runagent import RunAgentClient # Connect to your LangGraph agent client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="basic", local=True ) # Test basic workflow result = client.run(user_input="What is the capital of France?") print(f"Response: {result['response']}") print(f"Steps: {result['step_count']}") # Test multi-agent workflow multi_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="multi_agent", local=True ) multi_result = multi_client.run(user_input="Explain quantum computing") print(f"Multi-agent response: {multi_result['response']}") # Test streaming stream_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="streaming", local=True ) print("Streaming response:") for chunk in stream_client.run(user_input="Process this data"): print(chunk, end="", flush=True) ``` ### JavaScript Client ```javascript test_langgraph.js theme={null} import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'basic', local: true }); await client.initialize(); const result = await client.run({ user_input: 'What is the capital of France?' }); console.log('Response:', result.response); console.log('Steps:', result.step_count); ``` ## Best Practices ### 1. **State Management** * Keep state objects simple and focused * Use clear naming conventions * Avoid deep nesting in state ### 2. **Error Handling** * Wrap workflow execution in try-catch blocks * Provide meaningful error messages * Log errors for debugging ### 3. **Performance Optimization** * Use conditional edges to avoid unnecessary steps * Implement early termination when possible * Cache expensive operations ### 4. **Testing** * Test each node independently * Test the complete workflow * Use mock data for testing ## Common Patterns Use LangGraph to create agents that research topics and then write about them. Break complex problems into smaller steps with conditional logic. Create multiple specialized agents that work together. Add human approval steps for critical decisions. ## Troubleshooting ### Common Issues 1. **State Serialization Errors** * Ensure all state fields are serializable * Use simple data types when possible 2. **Graph Compilation Errors** * Check that all nodes are properly defined * Verify edge connections are correct 3. **Memory Issues** * Limit the number of messages in state * Implement state cleanup for long conversations ### Debug Tips ```python theme={null} # Add debugging to your workflows def debug_node(state: AgentState) -> AgentState: print(f"Debug: Current state = {state}") return state # Add debug node to your workflow workflow.add_node("debug", debug_node) ``` ## Next Steps Learn advanced LangGraph patterns and techniques Deploy your LangGraph agent to production Access your LangGraph agent from different languages Optimize your LangGraph workflows for production **🎉 Great job!** You've learned how to deploy LangGraph agents with RunAgent. LangGraph's powerful workflow capabilities combined with RunAgent's multi-language access make for a powerful combination! * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Letta Source: https://docs.run-agent.ai/how-to/frameworks/letta # Letta Integration Deploy Letta memory-enabled agents with RunAgent *** ## Prerequisites * Basic understanding of Letta * Completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial * Python 3.8 or higher *** ## Overview Letta is a framework for building conversational AI agents with persistent memory and context awareness. RunAgent makes it easy to deploy Letta agents and access them from any programming language while maintaining conversation state. *** ## Installation & Setup ### 1. Install Letta Server ```bash theme={null} pip install -U letta ``` ### 2. Set Environment Variables Letta requires API keys for LLM providers. Set them before starting the server: ```bash theme={null} export OPENAI_API_KEY=your_openai_api_key_here ``` ### 3. Start Letta Server The Letta server must be running before deploying RunAgent agents: ```bash theme={null} letta server ``` The server will start on `http://localhost:8283`. Keep this terminal window open. **Note**: If you need to use a different port, you can specify it with: ```bash theme={null} letta server --port 8284 ``` ### 4. Install Letta Client (Optional) For Python SDK usage, install the client package: ```bash theme={null} pip install letta-client ``` *** ## Quick Start with RunAgent ### 1. Create a Letta Agent Project ```bash theme={null} runagent init my-letta-agent --framework letta cd my-letta-agent ``` ### 2. Install Dependencies ```bash theme={null} pip install -r requirements.txt ``` The generated `requirements.txt` will include: ``` letta-client python-dotenv ``` ### 3. Configure Environment Create a `.env` file in your project directory: ```bash theme={null} OPENAI_API_KEY=your_openai_api_key_here LETTA_SERVER_URL=http://localhost:8283 ``` ### 4. Review Configuration The generated `runagent.config.json` will be pre-configured for Letta: ```json theme={null} { "agent_name": "my-letta-agent", "description": "Letta conversational agent with memory", "framework": "letta", "version": "1.0.0", "agent_architecture": { "entrypoints": [ { "file": "agent.py", "module": "letta_run", "tag": "chat" }, { "file": "agent.py", "module": "letta_run_stream", "tag": "chat_stream" } ] } } ``` *** ## Basic Letta Agent Here's a simple Letta agent demonstrating conversational capabilities: ```python theme={null} # agent.py import os from dotenv import load_dotenv from letta_client import CreateBlock, Letta # Load environment variables load_dotenv() def _extract_message_from_input(*input_args, **input_kwargs) -> str: """Extract message text from various input formats""" # Try direct message parameter if input_kwargs.get("message"): return str(input_kwargs["message"]) # Try messages list format if input_kwargs.get("messages"): messages = input_kwargs["messages"] if isinstance(messages, list) and messages: last_message = messages[-1] if isinstance(last_message, dict) and "content" in last_message: return last_message["content"] # Try first positional argument as string if input_args and isinstance(input_args[0], str): return input_args[0] # Try first positional argument as dict with messages if input_args and isinstance(input_args[0], dict): data = input_args[0] if "messages" in data: messages = data["messages"] if isinstance(messages, list) and messages: last_message = messages[-1] if isinstance(last_message, dict) and "content" in last_message: return last_message["content"] if "message" in data: return str(data["message"]) return "Hello" def letta_run(*input_args, **input_kwargs): """Main entrypoint for the Letta agent""" try: # Initialize Letta client letta_url = os.getenv("LETTA_SERVER_URL", "http://localhost:8283") client = Letta(base_url=letta_url) # Create memory blocks memory_blocks = [ CreateBlock( label="human", value="You are talking to a user through RunAgent framework", ), CreateBlock( label="persona", value="You are a helpful AI assistant. Be friendly and concise.", ), ] # Create agent agent = client.agents.create( name=f"runagent-letta-{os.getpid()}", memory_blocks=memory_blocks, system="You are a helpful AI assistant integrated with RunAgent. Respond naturally and helpfully.", model="openai/gpt-4o-mini", embedding="openai/text-embedding-ada-002", include_base_tools=True ) print(f"✅ Letta agent created with ID: {agent.id}") # Extract message from input message = _extract_message_from_input(*input_args, **input_kwargs) # Send message to Letta agent response = client.agents.messages.create( agent_id=agent.id, messages=[{ "role": "user", "content": message }] ) # Clean up agent after use try: client.agents.delete(agent.id) print(f"🗑️ Cleaned up agent: {agent.id}") except: pass return response except Exception as e: return {"error": f"Letta execution error: {str(e)}"} def letta_run_stream(*input_args, **input_kwargs): """Streaming entrypoint for the Letta agent""" try: # Initialize Letta client letta_url = os.getenv("LETTA_SERVER_URL", "http://localhost:8283") client = Letta(base_url=letta_url) # Create memory blocks memory_blocks = [ CreateBlock( label="human", value="You are talking to a user through RunAgent framework", ), CreateBlock( label="persona", value="You are a helpful AI assistant. Be friendly and concise.", ), ] # Create agent agent = client.agents.create( name=f"runagent-letta-stream-{os.getpid()}", memory_blocks=memory_blocks, system="You are a helpful AI assistant integrated with RunAgent. Respond naturally and helpfully.", model="openai/gpt-4o-mini", embedding="openai/text-embedding-ada-002", include_base_tools=True ) print(f"✅ Letta streaming agent created with ID: {agent.id}") # Extract message from input message = _extract_message_from_input(*input_args, **input_kwargs) # Create streaming response stream = client.agents.messages.create_stream( agent_id=agent.id, messages=[{ "role": "user", "content": message }], stream_tokens=True, ) # Yield chunks for chunk in stream: yield chunk # Clean up agent after streaming completes try: client.agents.delete(agent.id) print(f"🗑️ Cleaned up streaming agent: {agent.id}") except: pass except Exception as e: yield {"error": f"Letta streaming error: {str(e)}"} ``` *** ## Advanced: Letta Agent with Custom Tools Here's an example with custom tools (keyword extraction, RAG): ```python theme={null} # agent.py (Advanced with Tools) import os from typing import Dict from dotenv import load_dotenv from letta_client import CreateBlock, Letta # Load environment variables load_dotenv() def _register_tools(client: Letta) -> Dict[str, str]: """Register custom tools with Letta client""" from keyword_tool import extract_keywords from rag_tool import rag_tool tool_fns = [extract_keywords, rag_tool] tool_map: Dict[str, str] = {} for fn in tool_fns: try: print(f" 📝 Registering {fn.__name__}...") tool = client.tools.upsert_from_function(func=fn) tool_map[tool.name] = tool.id print(f" ✅ Successfully registered: {tool.name}") except Exception as e: print(f" ❌ Failed to register tool {fn.__name__}: {e}") return tool_map def letta_run(message: str): """Advanced Letta agent with custom tools""" try: # Initialize Letta client letta_url = os.getenv("LETTA_SERVER_URL", "http://localhost:8283") client = Letta(base_url=letta_url) # Register tools print("🔧 Registering tools...") tool_map = _register_tools(client) # Create memory blocks memory_blocks = [ CreateBlock( label="human", value="You are talking to a user through RunAgent framework", ), CreateBlock( label="persona", value="You are an expert assistant with access to research tools.", ), ] # Create agent with tools agent = client.agents.create( name=f"runagent-letta-tools-{os.getpid()}", memory_blocks=memory_blocks, system="You are an expert assistant with access to keyword extraction and RAG tools. When users ask for research or information, use the rag_tool. When they need keywords extracted, use extract_keywords.", model="openai/gpt-4o-mini", embedding="openai/text-embedding-ada-002", tool_ids=list(tool_map.values()), include_base_tools=True ) print(f"✅ Letta agent created with {len(tool_map)} tools") # Send message to Letta agent response = client.agents.messages.create( agent_id=agent.id, messages=[{ "role": "user", "content": message }] ) # Clean up try: client.agents.delete(agent.id) except: pass return response except Exception as e: return {"error": f"Letta execution error: {str(e)}"} ``` ### Custom Tool Example: Keyword Extraction ```python theme={null} # keyword_tool.py def extract_keywords(text: str, num_keywords: int = 5) -> dict: """ Extract keywords from input text. Args: text (str): The input text to extract keywords from num_keywords (int): Number of keywords to extract (default: 5) Returns: dict: Dictionary containing the extracted keywords """ from langchain_openai import ChatOpenAI from langchain.prompts import PromptTemplate try: # Initialize the language model llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0.2) # Create prompt template prompt_template = """ Extract exactly {num_keywords} relevant keywords from the following text. Return them as a comma-separated list without numbering or bullet points. Only include the keywords, no additional information or explanation. Text: {input_text} Keywords: """ prompt = PromptTemplate( input_variables=["input_text", "num_keywords"], template=prompt_template ) # Create chain chain = prompt | llm # Run the chain result = chain.invoke({"input_text": text, "num_keywords": num_keywords}) # Extract content content = result.content if hasattr(result, 'content') else str(result) keywords = [kw.strip() for kw in content.split(',')] return { "status": "success", "keywords": keywords, "message": f"Successfully extracted {len(keywords)} keywords." } except Exception as e: return { "status": "error", "keywords": [], "message": f"Error extracting keywords: {str(e)}" } ``` *** ## Testing Your Letta Agent ### Python Client ```python theme={null} # test_letta.py from runagent import RunAgentClient # Ensure Letta server is running on port 8283 client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="chat", local=True ) # Test basic conversation result = client.run(message="Hello, I'm interested in AI agents") print(f"Response: {result}") # Test with message dict format result2 = client.run({ "messages": [ {"role": "user", "content": "What can you help me with?"} ] }) print(f"Response 2: {result2}") ``` ### JavaScript Client ```javascript theme={null} // test_letta.js import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'chat', local: true }); await client.initialize(); // Test conversation const result = await client.run({ message: 'Tell me about Letta agents' }); console.log('Response:', result); ``` ### Streaming Example ```python theme={null} # test_letta_stream.py from runagent import RunAgentClient stream_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="chat_stream", local=True ) print("Streaming conversation:") for chunk in stream_client.run(message="Explain the benefits of AI memory"): print(chunk, end="", flush=True) ``` *** ## Project Structure ``` my-letta-agent/ ├── agent.py # Main agent code ├── keyword_tool.py # Optional: Custom keyword tool ├── rag_tool.py # Optional: Custom RAG tool ├── .env # Environment variables ├── requirements.txt # Python dependencies └── runagent.config.json # RunAgent configuration ``` *** ## Configuration Options ### Multiple Entrypoints You can expose multiple entrypoints for different use cases: ```json theme={null} { "agent_name": "advanced-letta-agent", "description": "Advanced Letta multi-entrypoint system", "framework": "letta", "agent_architecture": { "entrypoints": [ { "file": "agent.py", "module": "letta_run", "tag": "chat" }, { "file": "agent.py", "module": "letta_run_stream", "tag": "chat_stream" }, { "file": "agent.py", "module": "letta_run_with_tools", "tag": "research" } ] } } ``` *** ## Best Practices ### 1. **Memory Management** * Use appropriate memory blocks for context * Clean up agents after use to prevent memory leaks * Consider session-based memory for multi-user scenarios ### 2. **Tool Design** * Create focused, single-purpose tools * Provide clear docstrings for tool functions * Handle tool errors gracefully with try-catch blocks * Return structured dictionaries from tools ### 3. **Error Handling** * Always wrap Letta operations in try-catch blocks * Return meaningful error messages to users * Log errors for debugging purposes ### 4. **Server Management** * Ensure Letta server is running before deploying agents * Use environment variables for server URL configuration * Monitor server logs for debugging ### 5. **Agent Cleanup** * Delete temporary agents after use * Implement cleanup in both success and error paths * Use context managers for resource management *** ## Common Patterns ### Conversational Memory Use Letta's memory blocks to maintain context across interactions: ```python theme={null} memory_blocks = [ CreateBlock( label="human", value="User preferences: prefers technical explanations, interested in AI" ), CreateBlock( label="persona", value="You are a technical AI expert. Provide detailed, accurate information." ), ] ``` ### Tool Integration Register custom tools for specialized functionality: ```python theme={null} def _register_tools(client: Letta) -> Dict[str, str]: tool_fns = [search_tool, calculate_tool, analyze_tool] tool_map = {} for fn in tool_fns: tool = client.tools.upsert_from_function(func=fn) tool_map[tool.name] = tool.id return tool_map ``` ### Session Management For multi-user scenarios, create agents per session: ```python theme={null} def create_session_agent(user_id: str, session_id: str): agent = client.agents.create( name=f"user-{user_id}-session-{session_id}", memory_blocks=load_user_memory(user_id), # ... other configuration ) return agent ``` *** ## Troubleshooting ### Common Issues **1. Connection Error: "Cannot connect to Letta server"** * **Solution**: Ensure Letta server is running (`letta server`) * Check the server URL in your `.env` file * Verify the server is accessible at `http://localhost:8283` **2. API Key Error** * **Solution**: Set `OPENAI_API_KEY` in your environment * Verify the key is valid and has sufficient credits * Check that the key is loaded in the Letta server environment **3. Tool Registration Fails** * **Solution**: Ensure tool functions have proper docstrings * Check that tool function signatures are compatible with Letta * Verify all tool dependencies are installed **4. Memory Persistence Issues** * **Solution**: Agents are ephemeral by default in this setup * Implement custom session storage if needed * Use Letta's built-in persistence features for production **5. Streaming Not Working** * **Solution**: Ensure you're using `create_stream` method * Check that `stream_tokens=True` is set * Verify the entrypoint is correctly configured for streaming ### Debug Tips Enable verbose logging: ```python theme={null} import logging logging.basicConfig(level=logging.DEBUG) def letta_run(message: str): print(f"Debug: Processing message: {message}") # ... rest of code ``` Test Letta server connection: ```python theme={null} from letta_client import Letta try: client = Letta(base_url="http://localhost:8283") print("✅ Successfully connected to Letta server") except Exception as e: print(f"❌ Connection failed: {e}") ``` *** ## Performance Optimization ### 1. **Connection Pooling** Reuse Letta client connections when possible: ```python theme={null} # Initialize once _letta_client = None def get_letta_client(): global _letta_client if _letta_client is None: _letta_client = Letta(base_url=os.getenv("LETTA_SERVER_URL")) return _letta_client ``` ### 2. **Tool Caching** Register tools once and reuse: ```python theme={null} _tool_registry = None def get_tools(client: Letta): global _tool_registry if _tool_registry is None: _tool_registry = _register_tools(client) return _tool_registry ``` ### 3. **Memory Management** Clean up agents promptly: ```python theme={null} finally: try: client.agents.delete(agent.id) except: pass ``` *** ## Next Steps * **[Advanced Patterns](/how-to/advanced-tasks)** - Learn advanced Letta patterns * **[Production Deployment](/runagent-cloud/cloud-deployment)** - Deploy to production * **[Multi-Language Access](/tutorials/multi-language-wrapper)** - Access from different languages * **[Performance Tuning](/explanation/production-considerations)** - Optimize for production *** ## Additional Resources * [Letta Documentation](https://docs.letta.ai) * [Letta GitHub](https://github.com/letta-ai/letta) * [RunAgent Discord Community](https://discord.gg/Q9P9AdHVHz) * [RunAgent Documentation](https://docs.run-agent.ai) *** **🎉 Great work!** You've learned how to deploy Letta memory-enabled agents with RunAgent. Letta's conversational memory capabilities combined with RunAgent's multi-language access create powerful, context-aware AI systems! # Llamaindex Source: https://docs.run-agent.ai/how-to/frameworks/llamaindex # LlamaIndex Integration Deploy LlamaIndex agent workflows with RunAgent *** ## Prerequisites * Basic understanding of LlamaIndex * Completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial * Python 3.8 or higher *** ## Overview LlamaIndex is a data framework for building LLM applications with advanced indexing, retrieval, and agent workflows. RunAgent makes it easy to deploy LlamaIndex agents and access them from any programming language. *** ## Installation & Setup ### 1. Install LlamaIndex ```bash theme={null} pip install llama-index>=0.12.48 ``` ### 2. Set Environment Variables LlamaIndex requires API keys for LLM providers: ```bash theme={null} export OPENAI_API_KEY=your_openai_api_key_here ``` ### 3. Quick Start with RunAgent ```bash theme={null} runagent init my-llamaindex-agent --framework llamaindex cd my-llamaindex-agent ``` *** ## Quick Start ### 1. Project Structure After initialization: ``` my-llamaindex-agent/ ├── math_genius.py # Main agent code ├── .env # Environment variables ├── requirements.txt # Python dependencies └── runagent.config.json # RunAgent configuration ``` ### 2. Configuration The generated `runagent.config.json`: ```json theme={null} { "agent_name": "llamaindex-agent", "description": "LlamaIndex agent with tool capabilities", "framework": "llamaindex", "version": "1.0.0", "agent_architecture": { "entrypoints": [ { "file": "math_genius.py", "module": "do_multiply", "tag": "math_run" }, { "file": "math_genius.py", "module": "stream_multiply", "tag": "math_stream" } ] }, "env_vars": { "OPENAI_API_KEY": "" } } ``` ### 3. Create `.env` File ```bash theme={null} OPENAI_API_KEY=your_openai_api_key_here ``` *** ## Basic LlamaIndex Agent Here's a simple LlamaIndex agent with a calculator tool: ```python theme={null} # math_genius.py from llama_index.llms.openai import OpenAI from llama_index.core.agent.workflow import AgentStream, FunctionAgent # Define calculator tools def multiply(a: float, b: float) -> float: """Multiply two numbers together.""" return a * b def add(a: float, b: float) -> float: """Add two numbers together.""" return a + b def subtract(a: float, b: float) -> float: """Subtract b from a.""" return a - b def divide(a: float, b: float) -> float: """Divide a by b. Returns error if b is zero.""" if b == 0: raise ValueError("Cannot divide by zero") return a / b # Create an agent workflow with calculator tools agent = FunctionAgent( tools=[multiply, add, subtract, divide], llm=OpenAI(model="gpt-4o-mini"), system_prompt="You are a helpful mathematical assistant. Use the provided tools to perform calculations.", ) async def do_multiply(math_query: str): """ Non-streaming math agent. Args: math_query: The mathematical query or expression Returns: The calculation result """ try: result = await agent.run(math_query) return { "status": "success", "result": str(result), "query": math_query } except Exception as e: return { "status": "error", "error": str(e), "query": math_query } async def stream_multiply(math_query: str): """ Streaming math agent. Args: math_query: The mathematical query or expression Yields: Streaming events from the agent """ try: handler = agent.run(user_msg=math_query) async for event in handler.stream_events(): if isinstance(event, AgentStream): yield { "type": "agent_stream", "content": str(event), "query": math_query } else: yield { "type": "event", "data": str(event) } except Exception as e: yield { "type": "error", "error": str(e), "query": math_query } ``` *** ## Advanced LlamaIndex Patterns ### 1. RAG Agent with Document Indexing ```python theme={null} # rag_agent.py from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings from llama_index.llms.openai import OpenAI from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.agent import ReActAgent from llama_index.core.tools import QueryEngineTool, ToolMetadata # Configure global settings Settings.llm = OpenAI(model="gpt-4o-mini", temperature=0.1) Settings.embed_model = OpenAIEmbedding(model="text-embedding-ada-002") # Load and index documents def create_index(data_dir: str = "./data"): """Create vector index from documents.""" try: documents = SimpleDirectoryReader(data_dir).load_data() index = VectorStoreIndex.from_documents(documents) return index except Exception as e: print(f"Error creating index: {e}") return None # Create query engine tool def create_rag_tools(index): """Create RAG tools from index.""" query_engine = index.as_query_engine(similarity_top_k=3) query_tool = QueryEngineTool( query_engine=query_engine, metadata=ToolMetadata( name="document_search", description="Search through indexed documents to find relevant information. Use this for questions about the document content." ) ) return [query_tool] # Initialize index and agent index = create_index() if index: tools = create_rag_tools(index) rag_agent = ReActAgent.from_tools( tools=tools, llm=Settings.llm, verbose=True ) else: rag_agent = None async def rag_query(query: str): """ Query documents using RAG. Args: query: User question about documents Returns: Answer based on document content """ if rag_agent is None: return { "status": "error", "error": "RAG agent not initialized. Check if documents exist in ./data directory." } try: response = await rag_agent.achat(query) return { "status": "success", "response": str(response), "query": query } except Exception as e: return { "status": "error", "error": str(e), "query": query } async def rag_query_stream(query: str): """ Streaming RAG query. Args: query: User question about documents Yields: Streaming response chunks """ if rag_agent is None: yield { "status": "error", "error": "RAG agent not initialized" } return try: response = await rag_agent.astream_chat(query) async for chunk in response.async_response_gen(): yield { "type": "text", "content": chunk } except Exception as e: yield { "type": "error", "error": str(e) } ``` ### 2. Multi-Tool Agent ```python theme={null} # multi_tool_agent.py from llama_index.llms.openai import OpenAI from llama_index.core.agent import ReActAgent from llama_index.core.tools import FunctionTool from typing import Dict, Any import json # Define multiple tools def get_weather(city: str) -> str: """Get current weather for a city.""" # Mock weather data weather_data = { "new york": {"temp": 22, "condition": "Sunny"}, "london": {"temp": 15, "condition": "Rainy"}, "tokyo": {"temp": 18, "condition": "Cloudy"}, "paris": {"temp": 20, "condition": "Partly Cloudy"} } city_lower = city.lower() if city_lower in weather_data: data = weather_data[city_lower] return f"Weather in {city}: {data['temp']}°C, {data['condition']}" return f"Weather data not available for {city}" def calculate_tip(bill_amount: float, tip_percentage: float = 15.0) -> str: """Calculate tip amount and total bill.""" tip = bill_amount * (tip_percentage / 100) total = bill_amount + tip return f"Tip: ${tip:.2f}, Total: ${total:.2f}" def convert_currency(amount: float, from_curr: str, to_curr: str) -> str: """Convert between currencies.""" # Mock conversion rates rates = {"USD": 1.0, "EUR": 0.85, "GBP": 0.73, "JPY": 110.0} from_rate = rates.get(from_curr.upper(), 1.0) to_rate = rates.get(to_curr.upper(), 1.0) result = amount * (to_rate / from_rate) return f"{amount} {from_curr.upper()} = {result:.2f} {to_curr.upper()}" def search_definition(term: str) -> str: """Search for term definition.""" # Mock definitions definitions = { "ai": "Artificial Intelligence: The simulation of human intelligence by machines", "ml": "Machine Learning: A subset of AI that enables systems to learn from data", "llm": "Large Language Model: AI models trained on vast amounts of text data" } term_lower = term.lower() return definitions.get(term_lower, f"Definition for '{term}' not found. This is a mock search.") # Create function tools weather_tool = FunctionTool.from_defaults(fn=get_weather) tip_tool = FunctionTool.from_defaults(fn=calculate_tip) currency_tool = FunctionTool.from_defaults(fn=convert_currency) definition_tool = FunctionTool.from_defaults(fn=search_definition) # Create multi-tool agent multi_agent = ReActAgent.from_tools( tools=[weather_tool, tip_tool, currency_tool, definition_tool], llm=OpenAI(model="gpt-4o-mini"), verbose=True ) async def multi_tool_query(query: str): """ Query using multiple tools. Args: query: User query that may require one or more tools Returns: Response using appropriate tools """ try: response = await multi_agent.achat(query) return { "status": "success", "response": str(response), "query": query, "tools_available": ["weather", "tip_calculator", "currency_converter", "definition_search"] } except Exception as e: return { "status": "error", "error": str(e), "query": query } async def multi_tool_stream(query: str): """ Streaming query with multiple tools. Args: query: User query Yields: Streaming response chunks """ try: response = await multi_agent.astream_chat(query) async for chunk in response.async_response_gen(): yield { "type": "text", "content": chunk } except Exception as e: yield { "type": "error", "error": str(e) } ``` ### 3. Workflow-Based Agent ```python theme={null} # workflow_agent.py from llama_index.core.workflow import ( Workflow, StartEvent, StopEvent, step, Event, Context ) from llama_index.llms.openai import OpenAI from llama_index.core.agent import FunctionAgent from typing import Any # Define workflow events class QueryEvent(Event): query: str class AnalysisEvent(Event): analysis: str class ResponseEvent(Event): response: str # Create workflow class AgentWorkflow(Workflow): """Custom workflow for agent processing.""" def __init__(self): super().__init__() self.llm = OpenAI(model="gpt-4o-mini") @step async def process_query(self, ctx: Context, ev: StartEvent) -> QueryEvent: """Initial query processing step.""" query = ev.get("query", "") print(f"Step 1: Processing query: {query}") # Store in context await ctx.set("original_query", query) return QueryEvent(query=query) @step async def analyze_query(self, ctx: Context, ev: QueryEvent) -> AnalysisEvent: """Analyze query intent and requirements.""" print(f"Step 2: Analyzing query intent") analysis_prompt = f"Analyze this query and determine what tools or information are needed: {ev.query}" response = await self.llm.acomplete(analysis_prompt) analysis = str(response) await ctx.set("analysis", analysis) return AnalysisEvent(analysis=analysis) @step async def generate_response(self, ctx: Context, ev: AnalysisEvent) -> StopEvent: """Generate final response based on analysis.""" print(f"Step 3: Generating response") original_query = await ctx.get("original_query") response_prompt = f"Based on this analysis: {ev.analysis}\n\nAnswer this query: {original_query}" response = await self.llm.acomplete(response_prompt) return StopEvent(result={ "query": original_query, "analysis": ev.analysis, "response": str(response), "workflow": "completed" }) # Initialize workflow workflow = AgentWorkflow() async def workflow_query(query: str): """ Process query through custom workflow. Args: query: User query Returns: Workflow result """ try: result = await workflow.run(query=query) return { "status": "success", "result": result } except Exception as e: return { "status": "error", "error": str(e), "query": query } ``` ### 4. Agent with Memory ```python theme={null} # memory_agent.py from llama_index.llms.openai import OpenAI from llama_index.core.agent import ReActAgent from llama_index.core.memory import ChatMemoryBuffer from llama_index.core.tools import FunctionTool from typing import Dict # Memory storage (in production, use proper database) user_memories = {} def remember_fact(user_id: str, key: str, value: str) -> str: """Remember a fact about the user.""" if user_id not in user_memories: user_memories[user_id] = {} user_memories[user_id][key] = value return f"I'll remember that {key}: {value}" def recall_fact(user_id: str, key: str) -> str: """Recall a fact about the user.""" if user_id not in user_memories: return f"I don't have any information about {key}" value = user_memories[user_id].get(key) if value: return f"I remember that {key}: {value}" return f"I don't have information about {key}" def list_memories(user_id: str) -> str: """List all remembered facts for a user.""" if user_id not in user_memories or not user_memories[user_id]: return "I don't have any memories stored yet." memories = user_memories[user_id] return "Here's what I remember:\n" + "\n".join( f"- {k}: {v}" for k, v in memories.items() ) # Create memory tools remember_tool = FunctionTool.from_defaults(fn=remember_fact) recall_tool = FunctionTool.from_defaults(fn=recall_fact) list_tool = FunctionTool.from_defaults(fn=list_memories) def create_memory_agent(user_id: str): """Create an agent with memory for a specific user.""" # Create chat memory buffer memory = ChatMemoryBuffer.from_defaults(token_limit=3000) # Create agent with memory agent = ReActAgent.from_tools( tools=[remember_tool, recall_tool, list_tool], llm=OpenAI(model="gpt-4o-mini"), memory=memory, verbose=True, system_prompt=f"You are a helpful assistant with memory capabilities for user {user_id}. " f"You can remember and recall information about the user." ) return agent # Agent cache agent_cache = {} async def memory_chat(user_id: str, message: str): """ Chat with memory-enabled agent. Args: user_id: Unique user identifier message: User message Returns: Agent response with memory context """ try: # Get or create agent for user if user_id not in agent_cache: agent_cache[user_id] = create_memory_agent(user_id) agent = agent_cache[user_id] # Chat with agent response = await agent.achat(message) return { "status": "success", "response": str(response), "user_id": user_id, "has_memory": True } except Exception as e: return { "status": "error", "error": str(e), "user_id": user_id } async def memory_chat_stream(user_id: str, message: str): """ Streaming chat with memory. Args: user_id: Unique user identifier message: User message Yields: Streaming response chunks """ try: if user_id not in agent_cache: agent_cache[user_id] = create_memory_agent(user_id) agent = agent_cache[user_id] response = await agent.astream_chat(message) async for chunk in response.async_response_gen(): yield { "type": "text", "content": chunk, "user_id": user_id } except Exception as e: yield { "type": "error", "error": str(e), "user_id": user_id } ``` *** ## Testing Your LlamaIndex Agent ### Python Client ```python theme={null} # test_llamaindex.py from runagent import RunAgentClient import asyncio # Test basic math agent client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="math_run", local=True ) result = client.run(math_query="What is 25 * 4?") print(f"Math result: {result}") # Test streaming stream_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="math_stream", local=True ) print("\nStreaming calculation:") for chunk in stream_client.run(math_query="Calculate 100 + 250 - 50"): if chunk.get("content"): print(chunk["content"]) # Test RAG agent (if configured) rag_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="rag_query", local=True ) rag_result = rag_client.run(query="What does the document say about AI?") print(f"\nRAG result: {rag_result}") ``` ### JavaScript Client ```javascript theme={null} // test_llamaindex.js import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'math_run', local: true }); await client.initialize(); // Test calculation const result = await client.run({ math_query: 'What is 15 * 8?' }); console.log('Result:', result); // Test streaming const streamClient = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'math_stream', local: true }); await streamClient.initialize(); console.log('\nStreaming:'); for await (const chunk of streamClient.run({ math_query: 'Calculate the sum of 10, 20, and 30' })) { if (chunk.content) { process.stdout.write(chunk.content); } } ``` ### Go Client ```go theme={null} package main import ( "context" "fmt" "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { client, _ := client.New( "your_agent_id_here", "math_run", true, ) defer client.Close() ctx := context.Background() result, _ := client.Run(ctx, map[string]interface{}{ "math_query": "What is 2 * 2?", }) fmt.Printf("Result: %v\n", result) } ``` ### Rust Client ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { let client = RunAgentClient::new( "your_agent_id_here", "math_run", true ).await?; let result = client.run(&[ ("math_query", json!("What is 5 * 9?")) ]).await?; println!("Result: {}", result); Ok(()) } ``` *** ## Configuration Examples ### Basic Math Agent ```json theme={null} { "agent_name": "llamaindex-math", "framework": "llamaindex", "agent_architecture": { "entrypoints": [ { "file": "math_genius.py", "module": "do_multiply", "tag": "math_run" }, { "file": "math_genius.py", "module": "stream_multiply", "tag": "math_stream" } ] } } ``` ### Multi-Feature Agent ```json theme={null} { "agent_name": "llamaindex-advanced", "framework": "llamaindex", "agent_architecture": { "entrypoints": [ { "file": "math_genius.py", "module": "do_multiply", "tag": "math" }, { "file": "rag_agent.py", "module": "rag_query", "tag": "rag" }, { "file": "multi_tool_agent.py", "module": "multi_tool_query", "tag": "multi_tool" }, { "file": "memory_agent.py", "module": "memory_chat", "tag": "memory" } ] } } ``` *** ## Best Practices ### 1. **Tool Design** * Keep tools simple and focused * Provide clear docstrings for LLM understanding * Handle errors gracefully within tools * Use type hints for parameters ### 2. **Agent Configuration** * Choose appropriate LLM models for your use case * Set reasonable temperature values * Configure memory limits appropriately * Use verbose mode during development ### 3. **RAG Implementation** * Index documents efficiently * Choose appropriate chunk sizes * Use optimal similarity thresholds * Implement caching for repeated queries ### 4. **Memory Management** * Set appropriate token limits for memory * Clean up old agent instances * Implement user-based memory isolation * Persist important memories to database ### 5. **Error Handling** * Always wrap async operations in try-catch * Return structured error responses * Log errors for debugging * Provide helpful error messages *** ## Common Patterns ### Tool-Based Pattern Simple agents with specific capabilities: ```python theme={null} agent + [calculator, weather, search] → responses ``` ### RAG Pattern Knowledge-augmented responses: ```python theme={null} query → document_search → llm_synthesis → answer ``` ### Workflow Pattern Multi-step processing: ```python theme={null} query → analyze → process → generate → response ``` ### Memory Pattern Context-aware conversations: ```python theme={null} user_memory + current_query → contextual_response ``` *** ## Troubleshooting ### Common Issues **1. API Key Not Found** * **Solution**: Set `OPENAI_API_KEY` in environment * Verify key is valid and has credits * Check `.env` file is loaded properly **2. Import Errors** * **Solution**: Install correct LlamaIndex version * Check all required packages are installed * Verify virtual environment is activated **3. Agent Not Responding** * **Solution**: Check LLM configuration * Verify tools are properly registered * Review system prompts for clarity **4. RAG Returning Poor Results** * **Solution**: Adjust similarity thresholds * Review document chunking strategy * Check embedding model quality * Verify document indexing completed **5. Streaming Not Working** * **Solution**: Use `astream_chat` instead of `achat` * Check async implementation * Verify streaming is supported by the model ### Debug Tips Enable verbose logging: ```python theme={null} import logging logging.basicConfig(level=logging.DEBUG) # Enable LlamaIndex debug logging from llama_index.core import set_global_handler set_global_handler("simple") ``` Test agent locally: ```python theme={null} # test_local.py import asyncio from math_genius import do_multiply async def test(): result = await do_multiply("What is 5 * 3?") print(f"Result: {result}") asyncio.run(test()) ``` *** ## Performance Optimization ### 1. **Agent Caching** Cache agent instances: ```python theme={null} _agent_cache = {} def get_agent(agent_type: str): if agent_type not in _agent_cache: _agent_cache[agent_type] = create_agent(agent_type) return _agent_cache[agent_type] ``` ### 2. **Index Optimization** Optimize RAG indexing: ```python theme={null} # Use persistent storage from llama_index.core import StorageContext, load_index_from_storage def get_or_create_index(): try: storage_context = StorageContext.from_defaults(persist_dir="./storage") index = load_index_from_storage(storage_context) except: documents = SimpleDirectoryReader("./data").load_data() index = VectorStoreIndex.from_documents(documents) index.storage_context.persist() return index ``` ### 3. **Memory Management** Implement memory limits: ```python theme={null} from llama_index.core.memory import ChatMemoryBuffer memory = ChatMemoryBuffer.from_defaults( token_limit=2000, # Reasonable limit ttl=3600 # 1 hour TTL ) ``` ### 4. **Async Operations** Use async throughout: ```python theme={null} # Always use async methods response = await agent.achat(query) # Good # response = agent.chat(query) # Avoid blocking calls ``` *** ## Next Steps * **[Advanced Patterns](/how-to/advanced-tasks)** - Learn advanced LlamaIndex patterns * **[Production Deployment](/runagent-cloud/cloud-deployment)** - Deploy to production * **[Multi-Language Access](/tutorials/multi-language-wrapper)** - Access from different languages * **[Performance Tuning](/explanation/production-considerations)** - Optimize for production *** ## Additional Resources * [LlamaIndex Documentation](https://docs.llamaindex.ai) * [LlamaIndex GitHub](https://github.com/run-llama/llama_index) * [LlamaIndex Discord](https://discord.gg/llamaindex) * [RunAgent Discord Community](https://discord.gg/Q9P9AdHVHz) * [RunAgent Documentation](https://docs.run-agent.ai) *** **🎉 Great work!** You've learned how to deploy LlamaIndex agents with RunAgent. LlamaIndex's powerful data framework combined with RunAgent's multi-language access creates sophisticated, knowledge-augmented AI systems! # Parlant Source: https://docs.run-agent.ai/how-to/frameworks/parlant # Parlant Integration Deploy Parlant guideline-driven conversational agents with RunAgent *** ## Prerequisites * Basic understanding of Parlant * Completed [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial * Python 3.10 or higher *** ## Overview Parlant is a framework for building guideline-driven conversational AI agents with structured behavior management. RunAgent makes it easy to deploy Parlant agents and access them from any programming language. *** ## Installation & Setup ### 1. Install Parlant ```bash theme={null} pip install parlant ``` ### 2. Set Environment Variables Parlant requires API keys for LLM providers: ```bash theme={null} export OPENAI_API_KEY=your_openai_api_key_here export PARLANT_LOG_LEVEL=INFO # Optional ``` ### 3. Start Parlant Server The Parlant server must be running before deploying RunAgent agents: ```bash theme={null} parlant-server run ``` The server will start on `http://localhost:8800`. Keep this terminal window open. **Note**: If you need to use a different port: ```bash theme={null} parlant-server run --port 8801 ``` ### 4. Quick Start with RunAgent ```bash theme={null} runagent init my-parlant-agent --framework parlant cd my-parlant-agent ``` *** ## Quick Start ### 1. Project Structure After initialization: ``` my-parlant-agent/ ├── agent.py # Main agent code ├── .env # Environment variables ├── requirements.txt # Python dependencies └── runagent.config.json # RunAgent configuration ``` ### 2. Configuration The generated `runagent.config.json`: ```json theme={null} { "agent_name": "parlant-assistant", "description": "Parlant-based conversational AI assistant", "framework": "parlant", "version": "1.0.0", "agent_architecture": { "entrypoints": [ { "file": "agent.py", "module": "simple_chat", "tag": "parlant_simple" }, { "file": "agent.py", "module": "chat_stream", "tag": "parlant_stream" } ] }, "env_vars": { "OPENAI_API_KEY": "", "PARLANT_LOG_LEVEL": "INFO" } } ``` ### 3. Create `.env` File ```bash theme={null} OPENAI_API_KEY=your_openai_api_key_here PARLANT_LOG_LEVEL=INFO ``` *** ## Basic Parlant Agent Here's a complete Parlant agent with tools and guidelines: ```python theme={null} # agent.py import asyncio from parlant.client import AsyncParlantClient from typing import Dict, Any, AsyncGenerator import time # Global client and agent_id for reuse _parlant_client = None _agent_id = None async def get_parlant_client(): """Get or create the Parlant client instance.""" global _parlant_client if _parlant_client is None: _parlant_client = AsyncParlantClient(base_url="http://localhost:8800") # Test connection try: await _parlant_client.agents.list() except Exception as e: raise Exception( f"Failed to connect to Parlant server at http://localhost:8800. " f"Make sure it's running with 'parlant-server run'. Error: {e}" ) return _parlant_client async def create_agent_with_tools(client: AsyncParlantClient): """Create an agent with calculator, time, and weather tools.""" # Check if agent already exists agents = await client.agents.list() for agent in agents: if agent.name == "RunAgent Assistant": print(f"✅ Found existing agent: {agent.name}") return agent.id # Create new agent agent = await client.agents.create( name="RunAgent Assistant", description="A helpful assistant that can provide information, perform calculations, tell time, and check weather." ) print(f"✅ Created new agent: {agent.name}") # Add calculator tool await client.agents.tools.create( agent_id=agent.id, name="calculator", description="Calculate mathematical expressions. Supports +, -, *, /, **, sqrt(), sin(), cos(), etc.", parameters={ "type": "object", "properties": { "expression": { "type": "string", "description": "Mathematical expression to calculate" } }, "required": ["expression"] }, implementation=""" try: import math allowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith("__")} allowed_names.update({"abs": abs, "round": round, "min": min, "max": max, "sum": sum, "pow": pow}) expression = expression.replace("^", "**") result = eval(expression, {"__builtins__": {}}, allowed_names) return f"Result: {result}" except Exception as e: return f"Error calculating '{expression}': {str(e)}" """ ) # Add time tool await client.agents.tools.create( agent_id=agent.id, name="get_current_time", description="Get the current date and time", parameters={"type": "object", "properties": {}, "required": []}, implementation=""" from datetime import datetime current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") return f"Current time: {current_time}" """ ) # Add weather tool (mock implementation) await client.agents.tools.create( agent_id=agent.id, name="weather_info", description="Get weather information for a city", parameters={ "type": "object", "properties": { "city": { "type": "string", "description": "Name of the city to get weather for" } }, "required": ["city"] }, implementation=""" # Mock weather data weather_data = { "paris": "Partly cloudy, 18°C", "london": "Rainy, 12°C", "new york": "Sunny, 22°C", "tokyo": "Cloudy, 16°C", "berlin": "Overcast, 15°C", "sydney": "Clear, 25°C" } city_lower = city.lower() weather = weather_data.get(city_lower, f"Weather data not available for {city}") return f"Weather in {city}: {weather}" """ ) # Add guidelines guidelines = [ { "condition": "User asks for the current time or date", "action": "Get the current time and provide it in a friendly manner", "tools": ["get_current_time"] }, { "condition": "User asks to calculate something or provides a math expression", "action": "Use the calculator tool to solve the mathematical expression and explain the result", "tools": ["calculator"] }, { "condition": "User asks about weather", "action": "Get weather information using the weather_info tool and provide a helpful response", "tools": ["weather_info"] }, { "condition": "User greets or says hello", "action": "Respond with a warm greeting and explain what you can help with" }, { "condition": "User asks what you can do or for help", "action": "Explain that you can perform calculations, provide time, check weather, and answer questions" }, { "condition": "User says goodbye or thanks", "action": "Respond politely and invite them to ask if they need anything else" } ] for guideline in guidelines: await client.agents.guidelines.create( agent_id=agent.id, **guideline ) print(f"✅ Added {len(guidelines)} guidelines and 3 tools") return agent.id async def get_or_create_agent(): """Get or create the agent with full tools and guidelines setup.""" global _agent_id if _agent_id is not None: return _agent_id client = await get_parlant_client() _agent_id = await create_agent_with_tools(client) return _agent_id async def chat_with_agent(message: str, agent_id: str) -> str: """Send a message to the agent and get response.""" client = await get_parlant_client() try: # Create a chat session session = await client.sessions.create( agent_id=agent_id, allow_greeting=False ) # Send message event = await client.sessions.create_event( session_id=session.id, kind="message", source="customer", message=message, ) # Get response agent_messages = await client.sessions.list_events( session_id=session.id, min_offset=event.offset, source="ai_agent", kinds="message", wait_for_data=30, ) if agent_messages: response_data = agent_messages[0].model_dump() return response_data.get("data", {}).get("message", "No response received") else: return "No response from agent" except Exception as e: return f"Error processing message: {str(e)}" async def simple_chat(message: str) -> Dict[str, Any]: """ Simple chat function that processes messages through Parlant. Args: message: The user's message Returns: Dict containing the response and metadata """ try: # Ensure agent is available with full setup agent_id = await get_or_create_agent() # Get response from agent response = await chat_with_agent(message, agent_id) return { "content": response, "type": "parlant_response", "agent_id": agent_id, "message_received": message, "timestamp": time.time(), "framework": "parlant" } except Exception as e: return { "content": f"Error: {str(e)}", "type": "error", "error": str(e), "message_received": message, "framework": "parlant" } async def chat_stream(message: str) -> AsyncGenerator[Dict[str, Any], None]: """ Streaming chat function. Args: message: The user's message Yields: Dict containing streaming response chunks """ try: # Get the response first response = await simple_chat(message) if response["type"] == "error": yield response return # Simulate streaming by breaking up the response content = response["content"] words = content.split() for word in words: yield { "content": word + " " } await asyncio.sleep(0.05) # Final chunk yield { "content": "", "type": "completion", "agent_id": response.get("agent_id"), "is_final": True, "framework": "parlant" } except Exception as e: yield { "content": f"Error: {str(e)}", "type": "error", "error": str(e), "framework": "parlant" } ``` *** ## Advanced Patterns ### 1. Custom Guidelines System ```python theme={null} # advanced_guidelines.py from parlant.client import AsyncParlantClient from typing import List, Dict async def create_customer_support_agent(client: AsyncParlantClient): """Create a customer support agent with specialized guidelines.""" agent = await client.agents.create( name="Customer Support Assistant", description="Specialized customer support agent with escalation protocols" ) # Support tools await client.agents.tools.create( agent_id=agent.id, name="check_order_status", description="Check the status of an order", parameters={ "type": "object", "properties": { "order_id": {"type": "string", "description": "Order ID to check"} }, "required": ["order_id"] }, implementation=""" # Mock order status check order_statuses = { "ORD123": "Shipped - Arriving tomorrow", "ORD456": "Processing - Expected to ship today", "ORD789": "Delivered on 2025-01-15" } return order_statuses.get(order_id, f"Order {order_id} not found in system") """ ) await client.agents.tools.create( agent_id=agent.id, name="create_support_ticket", description="Create a support ticket for complex issues", parameters={ "type": "object", "properties": { "issue": {"type": "string", "description": "Description of the issue"}, "priority": {"type": "string", "enum": ["low", "medium", "high"]} }, "required": ["issue", "priority"] }, implementation=""" ticket_id = f"TKT{hash(issue) % 10000}" return f"Support ticket {ticket_id} created with {priority} priority. A team member will contact you within 24 hours." """ ) # Customer support guidelines support_guidelines = [ { "condition": "User asks about order status", "action": "Use check_order_status tool to get current status and provide helpful tracking information", "tools": ["check_order_status"] }, { "condition": "User reports a problem or complaint", "action": "Acknowledge the issue empathetically, gather details, and create a support ticket", "tools": ["create_support_ticket"] }, { "condition": "User asks about refund or return policy", "action": "Explain that refunds are available within 30 days and guide them through the process" }, { "condition": "User is frustrated or angry", "action": "Respond with empathy, apologize for inconvenience, and escalate by creating high-priority ticket" } ] for guideline in support_guidelines: await client.agents.guidelines.create(agent_id=agent.id, **guideline) return agent.id async def support_chat(message: str) -> Dict: """Customer support conversation handler.""" client = AsyncParlantClient(base_url="http://localhost:8800") agent_id = await create_customer_support_agent(client) # Create session and get response session = await client.sessions.create(agent_id=agent_id, allow_greeting=False) await client.sessions.create_event( session_id=session.id, kind="message", source="customer", message=message ) response = await client.sessions.list_events( session_id=session.id, source="ai_agent", kinds="message", wait_for_data=30 ) return { "response": response[0].data.get("message") if response else "No response", "agent_type": "customer_support" } ``` ### 2. Multi-Domain Agent ```python theme={null} # multi_domain_agent.py from parlant.client import AsyncParlantClient async def create_multi_domain_agent(client: AsyncParlantClient): """Create agent that handles multiple domains.""" agent = await client.agents.create( name="Multi-Domain Assistant", description="Assistant capable of handling finance, health, and travel queries" ) # Finance tools await client.agents.tools.create( agent_id=agent.id, name="currency_converter", description="Convert between currencies", parameters={ "type": "object", "properties": { "amount": {"type": "number"}, "from_currency": {"type": "string"}, "to_currency": {"type": "string"} }, "required": ["amount", "from_currency", "to_currency"] }, implementation=""" # Mock conversion rates rates = {"USD": 1.0, "EUR": 0.85, "GBP": 0.73, "JPY": 110.0} result = amount * (rates.get(to_currency, 1) / rates.get(from_currency, 1)) return f"{amount} {from_currency} = {result:.2f} {to_currency}" """ ) # Health tools await client.agents.tools.create( agent_id=agent.id, name="bmi_calculator", description="Calculate Body Mass Index", parameters={ "type": "object", "properties": { "weight_kg": {"type": "number"}, "height_m": {"type": "number"} }, "required": ["weight_kg", "height_m"] }, implementation=""" bmi = weight_kg / (height_m ** 2) category = "Underweight" if bmi < 18.5 else "Normal" if bmi < 25 else "Overweight" if bmi < 30 else "Obese" return f"BMI: {bmi:.1f} - Category: {category}" """ ) # Travel tools await client.agents.tools.create( agent_id=agent.id, name="flight_time", description="Get approximate flight duration between cities", parameters={ "type": "object", "properties": { "from_city": {"type": "string"}, "to_city": {"type": "string"} }, "required": ["from_city", "to_city"] }, implementation=""" # Mock flight times flights = { ("new york", "london"): "7 hours", ("paris", "tokyo"): "12 hours", ("sydney", "singapore"): "8 hours" } key = (from_city.lower(), to_city.lower()) return flights.get(key, "Flight time not available") """ ) # Domain-specific guidelines guidelines = [ { "condition": "User asks about currency conversion or exchange rates", "action": "Use currency_converter tool to provide accurate conversion", "tools": ["currency_converter"] }, { "condition": "User asks about BMI or body mass index", "action": "Use bmi_calculator to calculate and explain the result", "tools": ["bmi_calculator"] }, { "condition": "User asks about flight duration or travel time", "action": "Use flight_time tool to provide estimated duration", "tools": ["flight_time"] } ] for guideline in guidelines: await client.agents.guidelines.create(agent_id=agent.id, **guideline) return agent.id ``` ### 3. Contextual Conversation Agent ```python theme={null} # contextual_agent.py from parlant.client import AsyncParlantClient from typing import Dict, Optional class ContextualAgent: def __init__(self): self.client = None self.agent_id = None self.active_sessions = {} async def initialize(self): """Initialize the agent with context-aware capabilities.""" self.client = AsyncParlantClient(base_url="http://localhost:8800") agent = await self.client.agents.create( name="Contextual Assistant", description="Agent that maintains conversation context across interactions" ) self.agent_id = agent.id # Add memory tool await self.client.agents.tools.create( agent_id=self.agent_id, name="remember_preference", description="Remember user preferences", parameters={ "type": "object", "properties": { "key": {"type": "string"}, "value": {"type": "string"} }, "required": ["key", "value"] }, implementation=""" # In production, use proper database return f"Remembered: {key} = {value}" """ ) # Context-aware guidelines await self.client.agents.guidelines.create( agent_id=self.agent_id, condition="User mentions a preference or personal information", action="Use remember_preference to store it for future reference", tools=["remember_preference"] ) await self.client.agents.guidelines.create( agent_id=self.agent_id, condition="User refers to previous conversation ('as I said', 'earlier')", action="Acknowledge the reference and build upon the previous context" ) async def chat(self, user_id: str, message: str) -> str: """Chat with context awareness per user.""" # Get or create session for user if user_id not in self.active_sessions: session = await self.client.sessions.create( agent_id=self.agent_id, allow_greeting=True ) self.active_sessions[user_id] = session.id session_id = self.active_sessions[user_id] # Send message await self.client.sessions.create_event( session_id=session_id, kind="message", source="customer", message=message ) # Get response events = await self.client.sessions.list_events( session_id=session_id, source="ai_agent", kinds="message", wait_for_data=30 ) if events: return events[0].data.get("message", "No response") return "No response from agent" # Usage async def contextual_chat(user_id: str, message: str) -> Dict: """Handle contextual conversation.""" agent = ContextualAgent() await agent.initialize() response = await agent.chat(user_id, message) return { "response": response, "user_id": user_id, "has_context": True } ``` *** ## Testing Your Parlant Agent ### Python Client ```python theme={null} # test_parlant.py from runagent import RunAgentClient import asyncio # Ensure Parlant server is running on port 8800 # Test simple chat client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="parlant_simple", local=True ) result = client.run(message="What time is it?") print(f"Response: {result['content']}") # Test with calculation result2 = client.run(message="Calculate 25 * 4 + 10") print(f"Calculation result: {result2['content']}") # Test streaming stream_client = RunAgentClient( agent_id="your_agent_id_here", entrypoint_tag="parlant_stream", local=True ) print("\nStreaming conversation:") for chunk in stream_client.run(message="What's the weather in Tokyo?"): if chunk.get("content"): print(chunk["content"], end="", flush=True) ``` ### JavaScript Client ```javascript theme={null} // test_parlant.js import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'parlant_simple', local: true }); await client.initialize(); // Test conversation const result = await client.run({ message: 'Can you help me with a calculation?' }); console.log('Response:', result.content); // Test streaming const streamClient = new RunAgentClient({ agentId: 'your_agent_id_here', entrypointTag: 'parlant_stream', local: true }); await streamClient.initialize(); for await (const chunk of streamClient.run({ message: 'Tell me about the weather' })) { if (chunk.content) { process.stdout.write(chunk.content); } } ``` ### Rust Client ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use futures::StreamExt; #[tokio::main] async fn main() -> Result<(), Box> { // Non-streaming test let client = RunAgentClient::new( "your_agent_id_here", "parlant_simple", true ).await?; let result = client.run(&[ ("message", json!("What can you help me with?")) ]).await?; println!("Response: {}", result); // Streaming test let stream_client = RunAgentClient::new( "your_agent_id_here", "parlant_stream", true ).await?; let mut stream = stream_client.run_stream(&[ ("message", json!("Calculate 100 + 250")) ]).await?; while let Some(chunk) = stream.next().await { match chunk { Ok(data) => print!("{}", data), Err(e) => eprintln!("Error: {}", e) } } Ok(()) } ``` *** ## Best Practices ### 1. **Guideline Design** * Write clear, specific conditions * Define concrete actions for agents to take * Associate appropriate tools with guidelines * Test guidelines with various inputs ### 2. **Tool Implementation** * Keep tools focused and single-purpose * Handle errors gracefully within tool code * Use type-safe parameters * Provide clear descriptions for LLM understanding ### 3. **Session Management** * Create sessions per user for context * Clean up old sessions periodically * Handle session timeouts appropriately * Store session metadata when needed ### 4. **Error Handling** * Always wrap async operations in try-catch * Return structured error responses * Log errors for debugging * Provide helpful error messages to users ### 5. **Performance** * Reuse client connections * Cache agent IDs * Implement connection pooling for high traffic * Monitor API usage and latency *** ## Common Patterns ### Guideline-Driven Routing Route user requests based on guidelines: ```python theme={null} condition → action → tool_usage ``` ### Tool Composition Combine multiple tools for complex tasks: ```python theme={null} calculator + weather + time → comprehensive_response ``` ### Context Preservation Maintain conversation history: ```python theme={null} session_per_user → contextual_responses ``` ### Escalation Pattern Handle complex requests: ```python theme={null} simple_query → agent_response complex_query → escalation → support_ticket ``` *** ## Troubleshooting ### Common Issues **1. Server Connection Failed** * **Solution**: Ensure Parlant server is running with `parlant-server run` * Check server URL (default: `http://localhost:8800`) * Verify no firewall blocking port 8800 **2. Agent Not Found** * **Solution**: Agent is created on first run * Check agent creation logs * Verify client connection is successful **3. Tool Execution Fails** * **Solution**: Check tool implementation code * Verify parameter types match specification * Test tools independently before integration **4. Guidelines Not Triggering** * **Solution**: Make conditions more specific * Test with various phrasings * Review guideline condition matching **5. Session Timeout** * **Solution**: Increase `wait_for_data` timeout * Check server responsiveness * Monitor server logs for errors ### Debug Tips Enable debug logging: ```python theme={null} import logging logging.basicConfig(level=logging.DEBUG) async def simple_chat(message: str): print(f"Debug: Processing message: {message}") # ... rest of code ``` Test Parlant server connection: ```python theme={null} from parlant.client import AsyncParlantClient import asyncio async def test_connection(): try: client = AsyncParlantClient(base_url="http://localhost:8800") agents = await client.agents.list() print(f"✅ Connected! Found {len(agents)} agents") except Exception as e: print(f"❌ Connection failed: {e}") asyncio.run(test_connection()) ``` *** ## Performance Optimization ### 1. **Client Reuse** Reuse client connections: ```python theme={null} _global_client = None async def get_client(): global _global_client if _global_client is None: _global_client = AsyncParlantClient(base_url="http://localhost:8800") return _global_client ``` ### 2. **Agent Caching** Cache agent IDs: ```python theme={null} _agent_cache = {} async def get_or_create_agent(agent_type: str): if agent_type not in _agent_cache: client = await get_client() agent_id = await create_agent(client, agent_type) _agent_cache[agent_type] = agent_id return _agent_cache[agent_type] ``` ### 3. **Session Pooling** Manage session lifecycle: ```python theme={null} from collections import defaultdict from datetime import datetime, timedelta class SessionPool: def __init__(self, ttl_minutes=30): self.sessions = defaultdict(dict) self.ttl = timedelta(minutes=ttl_minutes) def get_session(self, user_id: str): session_data = self.sessions.get(user_id) if session_data and datetime.now() - session_data['created'] < self.ttl: return session_data['session_id'] return None def add_session(self, user_id: str, session_id: str): self.sessions[user_id] = { 'session_id': session_id, 'created': datetime.now() } ``` *** ## Next Steps * **[Advanced Patterns](/how-to/advanced-tasks)** - Learn advanced Parlant patterns * **[Production Deployment](/runagent-cloud/cloud-deployment)** - Deploy to production * **[Multi-Language Access](/tutorials/multi-language-wrapper)** - Access from different languages * **[Performance Tuning](/explanation/production-considerations)** - Optimize for production *** ## Additional Resources * [Parlant Documentation](https://docs.parlant.io) * [Parlant GitHub](https://github.com/emcie-co/parlant) * [Parlant Discord](https://discord.gg/parlant) * [RunAgent Discord Community](https://discord.gg/Q9P9AdHVHz) * [RunAgent Documentation](https://docs.run-agent.ai) *** **🎉 Great work!** You've learned how to deploy Parlant guideline-driven agents with RunAgent. Parlant's structured behavior system combined with RunAgent's multi-language access creates powerful, controllable conversational AI systems! # How-to Guides Overview Source: https://docs.run-agent.ai/how-to/overview Task-oriented recipes. Minimal theory, maximum copy-paste Pick a task and follow the steps. Each guide is 5–10 minutes. ## Frameworks ## Call from different languages ## Operations ## Advanced * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Reference Overview Source: https://docs.run-agent.ai/reference/overview Canonical specs for API, SDKs, CLI, config and errors If you need **exact parameters**, this is the source of truth. Base URL, auth, endpoints, streaming protocol, status codes. Python, JS, Go, Rust — with a parity matrix. Reference pages should be **exhaustive** and **de-duplicated**. Link here from tutorials/how-tos. * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Examples Source: https://docs.run-agent.ai/resources/examples Example agents and code snippets ## Quick Examples Ready-to-use examples for common agent patterns and use cases. ## Basic Examples ### Simple Q\&A Agent ```python theme={null} # agent.py import os from openai import OpenAI client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def invoke(input_data: dict) -> dict: query = input_data.get("query", "") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": query} ] ) return {"response": response.choices[0].message.content} ``` ### Streaming Chatbot ```python theme={null} # agent.py def stream(input_data: dict): query = input_data.get("query", "") stream = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": query}], stream=True ) for chunk in stream: if chunk.choices[0].delta.content: yield chunk.choices[0].delta.content ``` ## Framework Examples ### LangGraph Agent ```python theme={null} # langgraph_agent.py from langgraph.graph import StateGraph, END from typing import TypedDict, List class ConversationState(TypedDict): messages: List[str] context: dict response: str def understand_intent(state): # Analyze user intent return {"context": {"intent": "question"}} def generate_response(state): # Generate appropriate response return {"response": f"You asked: {state['messages'][-1]}"} # Build graph workflow = StateGraph(ConversationState) workflow.add_node("understand", understand_intent) workflow.add_node("respond", generate_response) workflow.add_edge("understand", "respond") workflow.add_edge("respond", END) workflow.set_entry_point("understand") app = workflow.compile() def invoke(input_data): result = app.invoke({"messages": [input_data["query"]]}) return {"response": result["response"]} ``` ### CrewAI Research Team ```python theme={null} # research_crew.py from crewai import Crew, Agent, Task researcher = Agent( role='Research Specialist', goal='Find accurate information', backstory='Expert researcher with access to vast knowledge' ) analyst = Agent( role='Data Analyst', goal='Analyze and synthesize findings', backstory='Skilled at finding patterns and insights' ) research_task = Task( description='Research {topic} thoroughly', agent=researcher ) analysis_task = Task( description='Analyze research findings and provide insights', agent=analyst ) crew = Crew( agents=[researcher, analyst], tasks=[research_task, analysis_task] ) def invoke(input_data): topic = input_data.get("topic", "AI trends") result = crew.kickoff({"topic": topic}) return {"research_results": result} ``` ## Use Case Examples ### Customer Support Agent ```python theme={null} # support_agent.py import json from datetime import datetime # Mock knowledge base KNOWLEDGE_BASE = { "shipping": "Standard shipping takes 5-7 business days...", "returns": "Items can be returned within 30 days...", "warranty": "All products come with a 1-year warranty..." } def find_relevant_info(query: str) -> str: query_lower = query.lower() for topic, info in KNOWLEDGE_BASE.items(): if topic in query_lower: return info return "I'll connect you with a human agent for this query." def invoke(input_data: dict) -> dict: query = input_data.get("query", "") user_id = input_data.get("user_id", "anonymous") # Log interaction log_entry = { "timestamp": datetime.utcnow().isoformat(), "user_id": user_id, "query": query } # Find relevant information response = find_relevant_info(query) # Check if escalation needed needs_human = "human agent" in response return { "response": response, "needs_escalation": needs_human, "log": log_entry } ``` ### Data Analysis Agent ```python theme={null} # data_analyst.py import pandas as pd import json from io import StringIO def analyze_csv_data(csv_content: str) -> dict: df = pd.read_csv(StringIO(csv_content)) analysis = { "rows": len(df), "columns": list(df.columns), "summary": df.describe().to_dict(), "missing_values": df.isnull().sum().to_dict() } return analysis def invoke(input_data: dict) -> dict: action = input_data.get("action", "analyze") if action == "analyze": csv_data = input_data.get("csv_data", "") if not csv_data: return {"error": "No CSV data provided"} try: analysis = analyze_csv_data(csv_data) return {"analysis": analysis} except Exception as e: return {"error": f"Analysis failed: {str(e)}"} return {"error": "Unknown action"} ``` ### Code Assistant ```python theme={null} # code_assistant.py import ast import black def analyze_python_code(code: str) -> dict: try: # Parse code tree = ast.parse(code) # Extract information functions = [node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)] classes = [node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)] # Format code try: formatted = black.format_str(code, mode=black.Mode()) except: formatted = code return { "valid": True, "functions": functions, "classes": classes, "formatted_code": formatted } except SyntaxError as e: return { "valid": False, "error": str(e), "line": e.lineno } def invoke(input_data: dict) -> dict: code = input_data.get("code", "") task = input_data.get("task", "analyze") if task == "analyze": return analyze_python_code(code) elif task == "improve": # Add suggestions for improvement analysis = analyze_python_code(code) if analysis["valid"]: analysis["suggestions"] = [ "Add type hints", "Include docstrings", "Consider error handling" ] return analysis return {"error": "Unknown task"} ``` ## Integration Examples ### Slack Bot Integration ```python theme={null} # slack_bot_agent.py import os import requests SLACK_WEBHOOK = os.getenv("SLACK_WEBHOOK_URL") def send_to_slack(message: str, channel: str = "#general"): payload = { "channel": channel, "text": message, "username": "RunAgent Bot" } requests.post(SLACK_WEBHOOK, json=payload) def invoke(input_data: dict) -> dict: command = input_data.get("command", "") user = input_data.get("user", "") if command.startswith("/ask"): question = command.replace("/ask", "").strip() # Process question answer = f"Answer to '{question}' coming soon!" send_to_slack(f"@{user} asked: {question}\nAnswer: {answer}") return {"response": answer} return {"response": "Unknown command"} ``` ### Database Query Agent ```python theme={null} # db_agent.py import os import psycopg2 from psycopg2.extras import RealDictCursor def get_db_connection(): return psycopg2.connect( os.getenv("DATABASE_URL"), cursor_factory=RealDictCursor ) def safe_query(query: str) -> list: # Basic SQL injection prevention forbidden = ["DROP", "DELETE", "UPDATE", "INSERT"] if any(word in query.upper() for word in forbidden): raise ValueError("Unsafe query detected") with get_db_connection() as conn: with conn.cursor() as cursor: cursor.execute(query) return cursor.fetchall() def invoke(input_data: dict) -> dict: query_type = input_data.get("type", "select") if query_type == "stats": # Get database statistics stats = { "users": safe_query("SELECT COUNT(*) FROM users")[0]["count"], "orders": safe_query("SELECT COUNT(*) FROM orders")[0]["count"], "revenue": safe_query("SELECT SUM(amount) FROM orders")[0]["sum"] } return {"stats": stats} elif query_type == "custom": query = input_data.get("query", "") try: results = safe_query(query) return {"results": results} except Exception as e: return {"error": str(e)} return {"error": "Unknown query type"} ``` ## Advanced Patterns ### Multi-Step Processing Pipeline ```python theme={null} # pipeline_agent.py from typing import Dict, Any import asyncio class ProcessingPipeline: def __init__(self): self.steps = [] def add_step(self, func, name): self.steps.append((func, name)) async def process(self, data: Dict[str, Any]) -> Dict[str, Any]: result = {"input": data, "steps": []} for func, name in self.steps: try: if asyncio.iscoroutinefunction(func): step_result = await func(result) else: step_result = func(result) result["steps"].append({ "name": name, "status": "success", "output": step_result }) result.update(step_result) except Exception as e: result["steps"].append({ "name": name, "status": "error", "error": str(e) }) break return result # Define pipeline steps def validate_input(data): if "text" not in data["input"]: raise ValueError("Missing 'text' field") return {"validated": True} async def analyze_sentiment(data): # Simulate async API call await asyncio.sleep(0.1) return {"sentiment": "positive", "score": 0.8} def generate_response(data): sentiment = data.get("sentiment", "neutral") responses = { "positive": "That's wonderful to hear!", "negative": "I understand your concerns.", "neutral": "Thank you for sharing." } return {"response": responses.get(sentiment, "Thanks!")} # Create pipeline pipeline = ProcessingPipeline() pipeline.add_step(validate_input, "validation") pipeline.add_step(analyze_sentiment, "sentiment_analysis") pipeline.add_step(generate_response, "response_generation") def invoke(input_data: dict) -> dict: # Run async pipeline in sync context loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) result = loop.run_until_complete(pipeline.process(input_data)) return result ``` ### Agent with Memory ```python theme={null} # memory_agent.py import json import os from datetime import datetime from typing import Dict, List class MemoryStore: def __init__(self, filepath="memory.json"): self.filepath = filepath self.memory = self._load_memory() def _load_memory(self) -> Dict: if os.path.exists(self.filepath): with open(self.filepath, 'r') as f: return json.load(f) return {"conversations": {}, "facts": {}} def save_memory(self): with open(self.filepath, 'w') as f: json.dump(self.memory, f) def remember_conversation(self, user_id: str, exchange: Dict): if user_id not in self.memory["conversations"]: self.memory["conversations"][user_id] = [] self.memory["conversations"][user_id].append({ "timestamp": datetime.utcnow().isoformat(), "exchange": exchange }) # Keep only last 10 exchanges self.memory["conversations"][user_id] = \ self.memory["conversations"][user_id][-10:] def get_conversation_history(self, user_id: str) -> List[Dict]: return self.memory["conversations"].get(user_id, []) def remember_fact(self, key: str, value: Any): self.memory["facts"][key] = { "value": value, "timestamp": datetime.utcnow().isoformat() } def recall_fact(self, key: str) -> Any: fact = self.memory["facts"].get(key, {}) return fact.get("value") # Initialize memory memory = MemoryStore() def invoke(input_data: dict) -> dict: user_id = input_data.get("user_id", "anonymous") query = input_data.get("query", "") # Get conversation history history = memory.get_conversation_history(user_id) # Check for memory-related queries if query.lower().startswith("remember that"): fact = query.replace("remember that", "").strip() memory.remember_fact(f"user_{user_id}_fact", fact) response = f"I'll remember that: {fact}" elif query.lower() == "what do you remember?": fact = memory.recall_fact(f"user_{user_id}_fact") if fact: response = f"I remember you told me: {fact}" else: response = "I don't have any specific memories yet." else: # Normal processing response = f"You said: {query}" if history: response += f"\n(We've had {len(history)} previous exchanges)" # Save exchange memory.remember_conversation(user_id, { "query": query, "response": response }) memory.save_memory() return { "response": response, "conversation_length": len(history) + 1 } ``` ## Testing Your Examples ### Unit Test Template ```python theme={null} # test_agent.py import pytest from agent import invoke, stream class TestAgent: def test_basic_invocation(self): result = invoke({"query": "Hello"}) assert "response" in result assert isinstance(result["response"], str) def test_streaming(self): chunks = list(stream({"query": "Tell a story"})) assert len(chunks) > 0 assert all(isinstance(chunk, str) for chunk in chunks) def test_error_handling(self): result = invoke({}) # Missing query assert "error" in result or "response" in result @pytest.mark.parametrize("input,expected_key", [ ({"query": "test"}, "response"), ({"action": "analyze"}, "analysis"), ({"command": "help"}, "help_text") ]) def test_various_inputs(self, input, expected_key): result = invoke(input) assert expected_key in result ``` ## Next Steps * Browse our [GitHub repository](https://github.com/runagent-dev/examples) for more examples * Join our [Discord community](https://discord.gg/runagent) to share your agents * Check out [templates](/cli/commands/template) for ready-to-use starting points ## Contributing Examples Have a great example? Share it with the community: 1. Fork the examples repository 2. Add your example with documentation 3. Include tests and requirements 4. Submit a pull request We feature the best community examples in our documentation! # Frequently Asked Questions Source: https://docs.run-agent.ai/resources/faq Common questions about RunAgent ## General Questions RunAgent is a platform for deploying AI agents to production. It provides: * Framework-agnostic deployment * Automatic scaling and monitoring * Simple CLI and SDK interfaces * Support for all major AI frameworks Think of it as "Vercel for AI agents" - deploy with one command and let us handle the infrastructure. Currently supported: * LangGraph * CrewAI * Agno * Letta * Custom Python frameworks Coming soon: * AutoGen * BabyAGI * AgentGPT You can use any Python-based framework with our custom framework option. **Local deployment**: Free forever **Cloud deployment** (coming soon): * Free tier: 1,000 requests/month * Pro: \$29/month for 50,000 requests * Enterprise: Custom pricing See [pricing page](https://run-agent.ai/pricing) for details. ## Getting Started Simply use pip: ```bash theme={null} pip install runagent ``` For development with all dependencies: ```bash theme={null} pip install "runagent[dev]" ``` No! RunAgent works with your existing code. Just: 1. Add a `runagent.config.json` file 2. Define your entrypoints 3. Deploy Your agent logic remains unchanged. Entrypoints are functions RunAgent calls to interact with your agent: ```python theme={null} # Standard entrypoint def invoke(input_data: dict) -> dict: return {"result": "processed"} # Streaming entrypoint def stream(input_data: dict): for chunk in process(): yield chunk ``` ## Technical Questions RunAgent supports Python 3.8 and above: * Python 3.8 * Python 3.9 * Python 3.10 * Python 3.11 * Python 3.12 Yes! Add any dependencies to your `requirements.txt`: ```txt theme={null} openai>=1.0.0 requests>=2.31.0 pandas>=2.0.0 your-custom-package>=1.0.0 ``` RunAgent will install them during deployment. **Local development**: Use `.env` files ```bash theme={null} OPENAI_API_KEY=sk-... DATABASE_URL=postgresql://... ``` **Production**: Set in deployment configuration ```bash theme={null} runagent deploy . --env OPENAI_API_KEY=$OPENAI_API_KEY ``` Secrets are encrypted at rest and never logged. **Default limits**: * Memory: 512MB (configurable up to 8GB) * Timeout: 30 seconds (configurable up to 900s) * Payload size: 10MB * Concurrent requests: Based on plan Configure in `runagent.config.json`: ```json theme={null} { "deployment": { "memory": "2GB", "timeout": 120 } } ``` ## Deployment Questions **Local deployment**: * Runs on your machine * Free forever * Good for development and testing * Requires your machine to be running **Cloud deployment**: * Runs on RunAgent infrastructure * Auto-scaling and high availability * Monitoring and logging included * Accessible from anywhere Simply deploy again with the same name: ```bash theme={null} # Updates existing deployment runagent deploy . --name my-agent ``` RunAgent handles: * Zero-downtime updates * Automatic rollback on failure * Version history Yes! Use different names or environments: ```bash theme={null} # Production version runagent deploy . --name agent-prod --env production # Staging version runagent deploy . --name agent-staging --env staging # Development version runagent deploy . --name agent-dev --env development ``` ## SDK Questions **Available now**: * Python **Coming soon**: * JavaScript/TypeScript (Q2 2024) * Rust (Q2 2024) * Go (Q3 2024) You can always use the REST API directly from any language. **Python SDK**: ```python theme={null} for chunk in client.run_generic_stream(input_data): print(chunk, end="", flush=True) ``` **Direct API**: Use Server-Sent Events (SSE) with appropriate client library. Yes, the SDK clients are thread-safe. You can: * Share a client instance across threads * Use in async contexts with AsyncRunAgentClient * Handle concurrent requests ## Troubleshooting Common causes: 1. **Missing environment variables** - Check all are set 2. **File path issues** - Use relative paths 3. **Dependency versions** - Pin specific versions 4. **Resource limits** - Increase memory/timeout Debug with: ```bash theme={null} runagent logs ``` 1. **Add logging** to identify slow operations 2. **Use profiling** to find bottlenecks 3. **Check logs** for errors or warnings 4. **Monitor metrics** (coming soon) ```python theme={null} import time start = time.time() # operation print(f"Took {time.time() - start}s") ``` ## Best Practices Recommended structure: ``` my-agent/ ├── agent.py # Main agent code ├── utils/ # Helper functions ├── prompts/ # Prompt templates ├── tests/ # Unit tests ├── runagent.config.json ├── requirements.txt ├── .env.example └── README.md ``` **Use sync when**: * Simple request/response * No concurrent operations * Easier to debug **Use async when**: * Multiple API calls * I/O intensive operations * Need better performance ## Community & Support 1. **Documentation**: [docs.run-agent.ai](https://docs.run-agent.ai) 2. **Discord**: [discord.gg/runagent](https://discord.gg/runagent) 3. **GitHub Issues**: For bugs and features 4. **Email**: [support@run-agent.ai](mailto:support@run-agent.ai) for critical issues Yes! We welcome contributions: * Code contributions via GitHub * Documentation improvements * Bug reports and feature requests * Community SDKs and templates See our [contributing guide](https://github.com/runagent-dev/runagent/CONTRIBUTING.md). The RunAgent CLI and SDKs are open source (MIT license). The deployment infrastructure is proprietary but offers a generous free tier. ## Still Have Questions? Get help from the community [Join Discord →](https://discord.gg/runagent) For account or billing questions [Email Us →](mailto:support@run-agent.ai) * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Resources Overview Source: https://docs.run-agent.ai/resources/overview Examples, troubleshooting, FAQs, and community links ## Quick links * Open a GitHub issue → Issues * Join our chat → Discord - Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) - Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) - Follow us on [X](https://x.com/run_agent) - New here? [Sign up](https://run-agent.ai/dashboard) # Troubleshooting Guide Source: https://docs.run-agent.ai/resources/troubleshooting Common issues and solutions for RunAgent ## Installation Issues **Solution**: Install with user flag or use virtual environment ```bash theme={null} # User installation pip install --user runagent # Or use virtual environment (recommended) python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install runagent ``` **Solution**: Add Python scripts to PATH or use python -m ```bash theme={null} # Check where it's installed pip show runagent # Use python module directly python -m runagent --help # Add to PATH (Linux/Mac) export PATH="$PATH:$HOME/.local/bin" # Add to PATH (Windows) set PATH=%PATH%;%APPDATA%\Python\Scripts ``` **Solution**: Update certificates or use trusted host ```bash theme={null} # Update certificates pip install --upgrade certifi # Or temporarily bypass (not recommended for production) pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org runagent ``` ## Configuration Issues **Common causes and solutions**: 1. **JSON syntax error** ```bash theme={null} # Validate JSON python -m json.tool runagent.config.json ``` 2. **Missing required fields** ```json theme={null} { "agent_name": "required", "framework": "required", "version": "required", "agent_architecture": { "entrypoints": [...] // required } } ``` 3. **Invalid entrypoint path** ```bash theme={null} # Test import manually python -c "from agents import app; print(app.invoke)" ``` **Solution**: Check .env file and loading mechanism ```bash theme={null} # Ensure .env exists ls -la .env # Check format (no spaces around =) OPENAI_API_KEY=sk-... NOT: OPENAI_API_KEY = sk-... # Load manually in Python from dotenv import load_dotenv load_dotenv() ``` ## Local Development Issues **Solution**: Find and kill process or use different port ```bash theme={null} # Find process (Linux/Mac) lsof -i :8000 kill -9 # Find process (Windows) netstat -ano | findstr :8000 taskkill /PID /F # Or use different port runagent serve . --port 8080 ``` **Solution**: Check dependencies and Python path ```bash theme={null} # Install all dependencies pip install -r requirements.txt # Check Python path python -c "import sys; print(sys.path)" # Add current directory to PYTHONPATH export PYTHONPATH="${PYTHONPATH}:." ``` **Solution**: Check file watchers and restart manually ```bash theme={null} # Check if reload is enabled runagent serve . --reload # Touch file to trigger reload touch agent.py # Check system file watchers limit (Linux) cat /proc/sys/fs/inotify/max_user_watches # Increase if needed echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf ``` ## Runtime Errors **Solution**: Increase timeout or optimize agent code ```python theme={null} # In runagent.config.json { "deployment": { "timeout": 60 // Increase from default 30s } } # Optimize agent code # - Cache expensive operations # - Use async where possible # - Reduce external API calls ``` **Solution**: Increase memory limit or reduce usage ```json theme={null} { "deployment": { "memory": "1GB" // Increase from default 512MB } } ``` Tips for reducing memory: * Load models once, not per request * Use generators for large datasets * Clear unused variables * Profile memory usage **Common issues**: 1. **Key not found** ```bash theme={null} # Check environment echo $OPENAI_API_KEY # Set in .env file OPENAI_API_KEY=sk-... ``` 2. **Invalid key format** * OpenAI keys start with `sk-` * No extra spaces or quotes * Check expiration 3. **Rate limits** * Implement retry logic * Use different keys for dev/prod * Monitor usage ## Deployment Issues **Solution**: Run validation locally first ```bash theme={null} # Validate configuration runagent validate . # Test imports runagent test-import . # Check file sizes find . -size +10M -type f ``` **Debugging steps**: ```bash theme={null} # Check status runagent status # View logs runagent logs --tail 100 # Test health endpoint curl https://api.run-agent.ai/v1/agents//health # Restart if needed runagent restart ``` ## SDK Issues **Solution**: Check API key configuration ```python theme={null} # Debug authentication import os print(f"API Key present: {'RUNAGENT_API_KEY' in os.environ}") # Explicit configuration from runagent import RunAgentClient client = RunAgentClient( agent_id="...", api_key="your-key-here", debug=True # Enable debug logging ) ``` **Common causes**: 1. **Buffering issues** ```python theme={null} # Force unbuffered output for chunk in client.run_generic_stream(input_data): print(chunk, end="", flush=True) ``` 2. **Proxy interference** * Check if behind corporate proxy * Test with direct connection * Use appropriate proxy settings ## Performance Issues **Optimization strategies**: 1. **Profile your code** ```python theme={null} import time start = time.time() # Your operation print(f"Operation took: {time.time() - start}s") ``` 2. **Cache expensive operations** ```python theme={null} from functools import lru_cache @lru_cache(maxsize=100) def expensive_operation(input): # Cache results return result ``` 3. **Use connection pooling** ```python theme={null} # Reuse HTTP sessions import requests session = requests.Session() ``` **Memory optimization**: ```python theme={null} # Use generators instead of lists def process_large_data(): for item in data: yield process(item) # Not return all at once # Clear unused objects del large_object import gc gc.collect() # Monitor memory import psutil print(f"Memory: {psutil.Process().memory_info().rss / 1024 / 1024} MB") ``` ## Debugging Tools ### Enable Debug Logging ```python theme={null} # In your agent import logging logging.basicConfig(level=logging.DEBUG) # For RunAgent CLI runagent serve . --log-level debug # For SDK client = RunAgentClient(agent_id="...", debug=True) ``` ### Health Checks ```python theme={null} # Add health check endpoint def health_check(): checks = { "status": "healthy", "database": check_database(), "api_keys": check_api_keys(), "memory": check_memory() } return checks ``` ### Performance Monitoring ```python theme={null} # Simple performance decorator import time from functools import wraps def measure_time(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f"{func.__name__} took {time.time() - start:.2f}s") return result return wrapper @measure_time def slow_operation(): # Your code pass ``` ## Getting Help If you're still experiencing issues: Get help from the community [Join Discord →](https://discord.gg/runagent) Report bugs or request features [Open Issue →](https://github.com/runagent-dev/runagent/issues) For critical issues [support@run-agent.ai](mailto:support@run-agent.ai) Check system status [View Status →](https://status.run-agent.ai) ## Diagnostic Commands Quick commands for diagnosing issues: ```bash theme={null} # System check runagent doctor # Validate project runagent validate . --verbose # Test connectivity runagent ping # Export debug info runagent debug-info > debug.txt ``` # Cloud Deployment Source: https://docs.run-agent.ai/runagent-cloud/cloud-deployment Deploy agents to RunAgent cloud infrastructure Deploy agents to RunAgent cloud infrastructure for production use with automatic scaling, monitoring, and global availability. ## Prerequisites Before deploying to the cloud, you need: 1. **RunAgent Account** - Sign up at [run-agent.ai](https://run-agent.ai) 2. **API Key** - Get your API key from the dashboard 3. **Configured CLI** - Authenticate your CLI with your API key ## Authentication Setup Configure your CLI with your API key: ```bash theme={null} # Setup authentication runagent setup --api-key # Verify configuration runagent setup --api-key ``` The setup command will: * Validate your API key with the RunAgent middleware * Store credentials securely in `~/.runagent/config.json` * Display your account information and tier * Show middleware sync status ### Teardown Configuration Remove stored credentials: ```bash theme={null} runagent teardown ``` ## Deployment Methods ### Method 1: Quick Deploy (Upload + Start) Deploy your agent in a single command: ```bash theme={null} # Deploy to cloud (combines upload + start) runagent deploy --folder # Example runagent deploy --folder ./my-agent ``` This command will: 1. Validate your agent configuration 2. Upload agent code and metadata to the cloud 3. Start the agent automatically 4. Return the deployment endpoint **Output:** ``` ✅ Full deployment successful! 🆔 Agent ID: abc-123-def-456 🌐 Endpoint: https://api.run-agent.ai/api/v1/agents/abc-123-def-456 ``` ### Method 2: Two-Step Deploy (Upload Then Start) For more control, upload and start separately: #### Step 1: Upload Agent ```bash theme={null} # Upload agent to cloud runagent upload --folder # Specify framework explicitly (optional) runagent upload --folder --framework langgraph ``` **Upload Process:** 1. Agent validation (checks for required files) 2. Fingerprint generation (for duplicate detection) 3. Metadata upload (config + entrypoints) 4. Source code packaging and upload 5. Local database tracking **Output:** ``` 📤 Uploading agent from: ./my-agent 🔍 Validating agent... ✅ Agent validation passed 📋 Agent config loaded successfully 🔍 Agent fingerprint: a1b2c3d4... 📦 Uploading to: https://api.run-agent.ai/api/v1 🌐 Uploading agent metadata... Metadata uploaded successfully 📦 Creating upload package... Created upload package: agent_abc12345.zip Uploading agent_abc12345.zip (1,234,567 bytes)... Processing upload... Upload completed! ✅ Upload successful! 🆔 Agent ID: abc-123-def-456 🌐 Server: https://api.run-agent.ai/api/v1 🔍 Fingerprint: a1b2c3d4... 💡 Next step: runagent start --id abc-123-def-456 ``` #### Step 2: Start Agent ```bash theme={null} # Start uploaded agent runagent start --id # With custom configuration runagent start --id --config '{"env": "production"}' ``` **Output:** ``` Starting agent: abc-123-def-456 ✅ Agent started successfully! 🆔 Agent ID: abc-123-def-456 🌐 Endpoint: https://api.run-agent.ai/api/v1/agents/abc-123-def-456/execute ``` ## Agent Configuration ### Agent ID and Entrypoints When you initialize a new agent with `runagent init`, it automatically: 1. **Generates a unique agent ID** and adds it to `runagent.config.json` 2. **Creates a basic configuration** with framework and template settings **Important:** You must add your entrypoints to the configuration file before deploying. #### Using `runagent init` (Recommended) ```bash theme={null} # Initialize a new agent runagent init my-agent --framework langgraph # This creates runagent.config.json with: # - Generated agent_id # - Framework configuration # - Empty entrypoints array (you need to add these) ``` **Example `runagent.config.json` after init:** ```json theme={null} { "agent_name": "my-agent", "agent_id": "abc-123-def-456", "version": "1.0.0", "framework": "langgraph", "agent_architecture": { "entrypoints": [] // ← You need to add entrypoints here } } ``` **Add your entrypoints:** ```json theme={null} { "agent_name": "my-agent", "agent_id": "abc-123-def-456", "version": "1.0.0", "framework": "langgraph", "agent_architecture": { "entrypoints": [ { "tag": "chat", "file": "main.py", "module": "chat_agent" }, { "tag": "chat_stream", "file": "main.py", "module": "chat_agent_stream" } ] } } ``` #### Manually Editing Agent ID If you manually edit the `agent_id` in `runagent.config.json`, you **must register** the agent: ```bash theme={null} # Register the agent after manually editing agent_id runagent register . # Or use the config command runagent config --register-agent . ``` **Important:** If you manually change the `agent_id` in your config file, RunAgent won't recognize it until you register it. Always run `runagent register .` after manually editing the agent ID. ## Agent Validation Before upload, RunAgent validates your agent: ### Required Files * `runagent.config.json` - Agent configuration with valid `agent_id` and `entrypoints` * `main.py` or `agent.py` - Entry point file * `requirements.txt` - Python dependencies (optional) ### Validation Checks * ✅ Configuration file exists and is valid JSON * ✅ Agent ID exists in configuration * ✅ Agent ID is registered (if manually edited) * ✅ Entry point file exists * ✅ Entrypoints are properly defined * ✅ Framework is supported * ✅ No syntax errors in configuration **Example Valid Configuration:** ```json theme={null} { "agent_name": "my-agent", "agent_id": "abc-123-def-456", "version": "1.0.0", "framework": "langgraph", "agent_architecture": { "entrypoints": [ { "tag": "chat", "file": "main.py", "module": "agent.chat" } ] } } ``` ## Duplicate Detection RunAgent uses fingerprinting to detect duplicate agents: ### How It Works 1. **Fingerprint Generation**: Creates a unique hash of your agent's content 2. **Duplicate Check**: Compares with existing agents in your account 3. **User Prompt**: If duplicate found, asks whether to overwrite or create new **Example Scenarios:** **Scenario 1: Identical Content** ``` ⚠️ Agent with identical content already exists! 🆔 Existing Agent ID: abc-123-def-456 📊 Status: deployed 📍 Type: Remote Do you want to overwrite the existing agent? [y/N]: ``` **Scenario 2: Modified Content** ``` ⚠️ Agent content has changed! 🆔 Existing Agent ID: abc-123-def-456 📊 Status: deployed 📍 Type: Remote 🔍 Content fingerprint changed (modified files detected) What would you like to do? [overwrite] - Overwrite existing agent (coming soon) [new] - Create new agent [cancel] - Cancel upload ``` ## Running Cloud Agents Execute your deployed agents: ### Basic Execution ```bash theme={null} # Run with entrypoint tag runagent run --id --tag --param1=value1 --param2=value2 # Examples runagent run --id abc-123 --tag chat --message="Hello" runagent run --id abc-123 --tag process --data='{"key": "value"}' ``` ### Using Input Files ```bash theme={null} # Run with JSON input file runagent run --id --tag --input config.json ``` **Example input.json:** ```json theme={null} { "message": "Hello, world!", "config": { "temperature": 0.7, "max_tokens": 100 } } ``` ### Streaming Execution For streaming entrypoints (must end with `_stream`): ```bash theme={null} # Run streaming endpoint using run-stream command runagent run-stream --id --tag chat_stream --message="Tell me a story" # Or with local agent runagent run-stream --id --tag chat_stream --local --message="Tell me a story" ``` **Important:** Use `runagent run-stream` (not `runagent run`) for streaming execution. The `run-stream` command uses WebSocket connections for real-time streaming. ## Cloud vs Local Deployment | Feature | Local | Cloud | | ------------------ | ---------------- | ------------------------- | | **Setup** | `runagent serve` | `runagent deploy` | | **Infrastructure** | Your machine | RunAgent cloud | | **Scaling** | Manual | Automatic | | **Uptime** | While running | 24/7 | | **Monitoring** | Local logs only | Full monitoring dashboard | | **URL** | localhost:port | Global endpoint | | **Authentication** | None | API key required | | **Cost** | Free | Usage-based pricing | ## Deployment Workflow ### Complete Example ```bash theme={null} # 1. Create and test agent locally runagent init my-agent --framework langgraph --template default cd my-agent # 2. Add entrypoints to runagent.config.json # Edit the file and add your entrypoints to agent_architecture.entrypoints # 3. If you manually edited agent_id, register it runagent register . # 4. Test locally runagent serve # 5. Authenticate (if not already done) runagent setup --api-key # 6. Deploy to cloud runagent deploy --folder . # 7. Test cloud deployment runagent run --id --tag chat --message="Hello" ``` ### CI/CD Integration #### GitHub Actions ```yaml theme={null} name: Deploy to RunAgent Cloud on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v4 with: python-version: '3.9' - name: Install RunAgent run: pip install runagent - name: Deploy Agent env: RUNAGENT_API_KEY: ${{ secrets.RUNAGENT_API_KEY }} run: | runagent setup --api-key $RUNAGENT_API_KEY runagent deploy --folder . ``` #### GitLab CI ```yaml theme={null} deploy: stage: deploy image: python:3.9 script: - pip install runagent - runagent setup --api-key $RUNAGENT_API_KEY - runagent deploy --folder . only: - main ``` ## Monitoring and Management ### View Agent Status ```bash theme={null} # Check if agent is running runagent start --id ``` ### Local Deployment Info Deployment information is saved locally in `.deployments/`: ```json theme={null} { "agent_id": "abc-123-def-456", "remote": true, "base_url": "https://api.run-agent.ai/api/v1", "fingerprint": "a1b2c3d4...", "source_folder": "/path/to/my-agent", "saved_at": "2025-01-15 10:30:00", "client_version": "1.0" } ``` ## Troubleshooting ### Authentication Errors **Error:** `Not authenticated. Run 'runagent setup --api-key ' first` **Solution:** ```bash theme={null} # Setup authentication runagent setup --api-key # Verify setup worked runagent setup --api-key ``` ### Upload Failures **Error:** `Agent validation failed` **Solution:** 1. Check that `runagent.config.json` exists and is valid 2. Verify entry point file exists (`main.py` or `agent.py`) 3. Ensure all required dependencies are in `requirements.txt` 4. Run `runagent serve` locally to test first **Error:** `Failed to upload agent: HTTP 413` **Solution:** Your agent folder is too large. Remove unnecessary files: * Remove `__pycache__` directories * Remove `.pyc` files * Remove large data files (use cloud storage instead) * Add `.gitignore` patterns to exclude files ### Deployment Fails But Upload Succeeds **Error:** `Upload succeeded but start failed` **Solution:** ```bash theme={null} # Agent is uploaded, just needs to be started runagent start --id ``` ### Connection Issues **Error:** `Cannot connect to middleware server` **Solution:** 1. Check your internet connection 2. Verify the base URL is correct 3. Check if middleware server is accessible 4. Try with explicit base URL: `runagent setup --api-key --base-url https://api.run-agent.ai` ## Best Practices ### 1. Test Locally First Always test your agent locally before deploying: ```bash theme={null} # Test locally runagent serve runagent run --id --tag chat --local --message="test" # Deploy after successful local testing runagent deploy --folder . ``` ### 2. Version Control Include deployment info in version control: ```bash theme={null} # Add to .gitignore .deployments/*.json .runagent/ # But track your agent code git add runagent.config.json main.py requirements.txt git commit -m "feat: add chat agent" ``` ### 3. Environment Variables Use environment variables for sensitive data: ```json theme={null} { "env_vars": { "OPENAI_API_KEY": "${OPENAI_API_KEY}", "DATABASE_URL": "${DATABASE_URL}" } } ``` Set them before deploying: ```bash theme={null} export OPENAI_API_KEY="sk-..." runagent deploy --folder . ``` ### 4. Incremental Updates For agent updates: ```bash theme={null} # Upload new version runagent upload --folder . # Test before switching runagent run --id --tag chat --message="test" # If good, can use new agent ID ``` ### 5. Monitor Performance After deployment: * Test all entrypoints * Check response times * Verify outputs are correct * Monitor error rates ## Security ### API Key Management **Best Practices:** * ✅ Store API keys in environment variables * ✅ Use different keys for development and production * ✅ Rotate keys regularly * ✅ Never commit API keys to version control * ❌ Don't share API keys * ❌ Don't hardcode keys in agent code ### Secure Deployment ```bash theme={null} # Use environment variables export RUNAGENT_API_KEY="your-key" runagent deploy --folder . # Or use secure config file runagent setup --api-key $RUNAGENT_API_KEY ``` ## Limits and Quotas ### Free Tier * 5 local agents * Cloud deployment available * Standard execution limits ### Enhanced Limits Contact sales for: * Unlimited local agents * Higher execution limits * Priority support * Custom SLAs Check your current limits: ```bash theme={null} runagent db status --capacity ``` ## Next Steps * [RunAgent Cloud Overview](/runagent-cloud/overview) - Learn about RunAgent Cloud infrastructure * [Local Development](/deployment/local-development) - Test agents locally * [SDK Overview](/sdk/overview) - Use Python SDK for deployment * [API Reference](/api-reference) - Direct API access * [Monitoring Guide](/explanation/production-considerations) - Track agent performance ## Support Need help with cloud deployment? * 📖 [Documentation](https://docs.run-agent.ai) * 💬 [Discord Community](https://discord.gg/runagent) * 📧 [Email Support](mailto:support@run-agent.ai) * 🐛 [Report Issues](https://github.com/runagent/runagent/issues) # RunAgent Cloud Overview Source: https://docs.run-agent.ai/runagent-cloud/overview Serverless infrastructure for deploying and running AI agents at scale > RunAgent Cloud provides a fully managed, serverless infrastructure for deploying and running your AI agents. No infrastructure management, automatic scaling, and global availability. ## What is RunAgent Cloud? RunAgent Cloud is a serverless platform designed specifically for AI agents. It handles all the infrastructure complexity so you can focus on building great agents. ### Key Benefits Fully managed infrastructure with zero configuration. Deploy and scale automatically. Scale from zero to thousands of requests without manual intervention. Deploy once, access from anywhere with low-latency global distribution. Automatic image selection based on your agent's requirements and dependencies. ## Serverless Infrastructure RunAgent Cloud operates on a serverless model where: * **No servers to manage** - Infrastructure is fully managed by RunAgent * **Pay per use** - Only pay for actual agent execution time * **Automatic scaling** - Handles traffic spikes without configuration * **Zero maintenance** - Updates, patches, and security handled automatically * **High availability** - Built-in redundancy and failover ### How It Works 1. **Deploy your agent** - Upload your agent code with a single command 2. **Automatic provisioning** - RunAgent Cloud selects the optimal VM image 3. **On-demand execution** - Agents start when needed, scale automatically 4. **Global distribution** - Requests routed to nearest available instance ## VM Image Management RunAgent Cloud supports multiple VM images optimized for different use cases and dependencies. ### Automatic Image Selection The platform automatically selects the appropriate VM image based on: * **Framework requirements** - LangGraph, CrewAI, custom frameworks * **Dependencies** - Python packages, system libraries * **Resource needs** - CPU, memory, GPU requirements * **Optimization** - Best performance for your specific agent You don't need to specify which image to use - RunAgent Cloud handles this automatically. ### Deployment Time Initial deployment time varies based on the selected VM image: * **Standard images**: Typically ready in 30-60 seconds * **Specialized images**: May take up to 2 minutes for first deployment * **Subsequent requests**: Cached images start in seconds The platform optimizes for your agent's specific needs, which may require pulling specialized images on first deployment. ### Image Availability RunAgent Cloud currently supports multiple VM images optimized for: * Python-based agents with various framework requirements * Different dependency sets and system library needs * Performance-optimized configurations **More VM images coming soon** - We're continuously expanding image support to cover additional frameworks, languages, and use cases. ## Getting Started ### Quick Start ```bash theme={null} # 1. Authenticate with RunAgent Cloud runagent setup --api-key # 2. Deploy your agent runagent deploy --folder ./my-agent # 3. Your agent is live and accessible globally ``` ### Next Steps Complete guide to deploying agents to RunAgent Cloud Test agents locally before deploying to cloud Set up API keys and authentication Monitor and manage your deployed agents ## Architecture RunAgent Cloud provides: * **Isolated execution environments** - Each agent runs in its own secure container * **Load balancing** - Automatic request distribution across instances * **Health monitoring** - Continuous health checks and automatic recovery * **Logging and metrics** - Comprehensive observability for all agents * **API gateway** - Unified interface for all agent interactions ## Pricing Model RunAgent Cloud uses a usage-based pricing model: * **No upfront costs** - Pay only for what you use * **Per-execution pricing** - Based on actual agent runtime * **Transparent billing** - Clear visibility into usage and costs * **Free tier available** - Get started with free credits ## Security RunAgent Cloud includes enterprise-grade security: * **Isolated execution** - Complete isolation between agents * **Encrypted connections** - All traffic encrypted in transit * **API key authentication** - Secure access control * **Audit logging** - Complete activity tracking * **Compliance ready** - Built with security best practices ## Comparison: Local vs Cloud | Feature | Local Development | RunAgent Cloud | | ---------------- | -------------------------- | ------------------ | | **Setup** | Manual configuration | Zero configuration | | **Scaling** | Manual | Automatic | | **Availability** | When your machine is on | 24/7 global | | **Maintenance** | You manage | Fully managed | | **Cost** | Free (your infrastructure) | Pay per use | | **Best for** | Development, testing | Production | ## Support and Resources * **Documentation** - Comprehensive guides and references * **Dashboard** - Web interface for managing agents * **Community** - Discord community for support * **Status page** - Real-time platform status ## Next Steps Ready to deploy to RunAgent Cloud? Start with the [Cloud Deployment Guide](/runagent-cloud/cloud-deployment) to learn how to deploy your first agent. * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Getting Started with Go SDK Source: https://docs.run-agent.ai/sdk/go/getting-started Start using the RunAgent Go SDK The RunAgent Go SDK provides a simple and powerful interface for interacting with your deployed agents. It supports both synchronous and asynchronous operations, with built-in streaming capabilities. ## Installation Install the SDK using go get: ```bash theme={null} go get github.com/runagent-dev/runagent-go/pkg/client ``` The SDK is available as a Go module. Make sure you have Go 1.18 or later installed. ## Quick Start ### Basic Usage ```go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent-go/pkg/client" ) func main() { // Initialize the client agentClient, err := client.NewWithAddress( "your-agent-id", "minimal", true, "localhost", 8450, ) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer agentClient.Close() // Create context with timeout ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() // Simple invocation result, err := agentClient.Run(ctx, map[string]interface{}{ "role": "user", "message": "What's the capital of France?", }) if err != nil { log.Fatalf("Failed to run agent: %v", err) } fmt.Printf("Result: %v\n", result) } ``` ### With Custom Configuration ```go theme={null} // Local development setup agentClient, err := client.NewWithAddress( "you_agent_id", // Agent ID "minimal", // Entrypoint tag true, // Local flag "localhost", // Host 8450, // Port ) ``` ## Authentication The SDK supports multiple authentication methods: ```bash theme={null} export RUNAGENT_API_KEY="your-api-key" export RUNAGENT_HOST="localhost" export RUNAGENT_PORT="8450" ``` ```go theme={null} // SDK will automatically use the environment variables agentClient, err := client.NewWithAddress( "your-agent-id", "minimal", true, "localhost", 8450, ) ``` ```go theme={null} // For production use agentClient, err := client.NewWithAddress( "your-agent-id", "production", false, // Not local "api.run-agent.ai", // Production host 443, // HTTPS port ) ``` ```go theme={null} // Local development setup agentClient, err := client.NewWithAddress( "your-agent-id", "minimal", true, // Local flag "localhost", 8450, ) ``` ## Response Formats ### Standard Response ```go theme={null} result, err := agentClient.Run(ctx, map[string]interface{}{ "role": "user", "message": "Explain quantum computing", }) if err != nil { log.Fatalf("Failed to run agent: %v", err) } ``` ### Streaming Response ```go theme={null} // Stream responses for real-time output stream, err := agentClient.RunStream(ctx, map[string]interface{}{ "role": "user", "message": "Write a story about AI", }) if err != nil { log.Fatalf("Failed to start stream: %v", err) } defer stream.Close() // Read from stream for { data, hasMore, err := stream.Next(ctx) if err != nil { log.Printf("Stream error: %v", err) break } if !hasMore { fmt.Println("Stream completed") break } fmt.Printf("%v", data) } ``` # JavaScript SDK Getting Started Source: https://docs.run-agent.ai/sdk/javascript/getting-started Get started with the RunAgent JavaScript SDK # JavaScript SDK Getting Started The RunAgent JavaScript SDK provides a native-feeling interface for calling your deployed agents from JavaScript and TypeScript applications. ## Installation ```bash npm theme={null} npm install runagent ``` ```bash yarn theme={null} yarn add runagent ``` ```bash pnpm theme={null} pnpm add runagent ``` ```bash bun theme={null} bun add runagent ``` ## Basic Usage ### Initialize the Client ```javascript theme={null} import { RunAgentClient } from 'runagent'; const client = new RunAgentClient({ agentId: 'your-agent-id', entrypointTag: 'your-tag', local: true // Set to false for production }); ``` ### Call Your Agent ```javascript theme={null} // Non-streaming call const result = await client.run({ message: "Hello, world!", role: "user" }); console.log(result); ``` ### Streaming Response ```javascript theme={null} // Streaming call const stream = await client.runStream({ message: "Tell me a story", role: "user" }); for await (const chunk of stream) { process.stdout.write(chunk); } ``` ## TypeScript Support The SDK comes with full TypeScript support: ```typescript theme={null} import { RunAgentClient, RunAgentConfig } from 'runagent'; const config: RunAgentConfig = { agentId: 'your-agent-id', entrypointTag: 'your-tag', local: true }; const client = new RunAgentClient(config); ``` ## Error Handling ```javascript theme={null} try { const result = await client.run({ message: "Hello" }); console.log(result); } catch (error) { if (error.code === 'AGENT_NOT_FOUND') { console.error('Agent not found'); } else if (error.code === 'TIMEOUT') { console.error('Request timed out'); } else { console.error('Unexpected error:', error.message); } } ``` ## Next Steps * [API Reference](/sdk/python/api-reference) - Complete API documentation * [Streaming Guide](/sdk/python/streaming) - Advanced streaming patterns * [Examples](/resources/examples) - Real-world usage examples # SDK Overview Source: https://docs.run-agent.ai/sdk/overview Native SDKs for multiple programming languages ## Introduction RunAgent provides native SDKs for multiple programming languages, making it easy to integrate deployed agents into your applications. All SDKs follow consistent patterns while respecting language-specific conventions. ## Available SDKs ### Python Full-featured SDK with sync/async support ```bash theme={null} pip install runagent ``` ### Rust High-performance SDK with zero-cost abstractions ```bash theme={null} cargo add runagent tokio ``` ### JavaScript Coming Soon - Node.js and browser support ```bash theme={null} npm install @runagent/sdk ``` ### Go Coming Soon - Idiomatic Go client ```bash theme={null} go get github.com/runagent-dev/runagent-go ``` ## Common Features All SDKs provide: * **Authentication**: API key and token management * **Synchronous Calls**: Request/response pattern * **Asynchronous Support**: Non-blocking operations * **Streaming**: Real-time response streaming * **Error Handling**: Consistent error types * **Retry Logic**: Automatic retry with backoff * **Type Safety**: Language-appropriate typing ## Quick Comparison | Feature | Python | Rust | JavaScript | Go | | ------------- | ------ | ---- | ---------- | -- | | Sync Support | ✅ | ✅ | ✅ | ✅ | | Async Support | ✅ | ✅ | ✅ | ✅ | | Streaming | ✅ | ✅ | 🚧 | 🚧 | | Type Safety | ✅ | ✅ | ✅ (TS) | ✅ | | Published | ✅ | ✅ | 🚧 | 🚧 | ## Basic Usage Pattern All SDKs follow a similar pattern: ### Python ```python theme={null} from runagent import RunAgentClient client = RunAgentClient(agent_id="agent-123") result = client.run_generic({"query": "Hello"}) ``` ### Rust ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; let client = RunAgentClient::new("agent-123", "generic", true).await?; let result = client.run(&[("query", json!("Hello"))]).await?; ``` ### JavaScript ```javascript theme={null} import { RunAgentClient } from '@runagent/sdk'; const client = new RunAgentClient({ agentId: 'agent-123' }); const result = await client.runGeneric({ query: 'Hello' }); ``` ### Go ```go theme={null} import "github.com/runagent-dev/runagent-go" client := runagent.NewClient("agent-123") result, err := client.RunGeneric(map[string]interface{}{ "query": "Hello", }) ``` ## Authentication SDKs support multiple authentication methods: ### Environment Variable Set `RUNAGENT_API_KEY` and SDKs will use it automatically: ```bash theme={null} export RUNAGENT_API_KEY="your-api-key" ``` ### Direct Configuration Pass API key during initialization: ```python theme={null} client = RunAgentClient( agent_id="agent-123", api_key="your-api-key" ) ``` ### Configuration File SDKs can read from `~/.runagent/config.json`: ```json theme={null} { "api_key": "your-api-key", "api_url": "https://api.run-agent.ai" } ``` ## Error Handling All SDKs provide consistent error types: | Error Type | Description | | --------------------- | ------------------------------ | | `AuthenticationError` | Invalid or missing credentials | | `AgentNotFoundError` | Agent doesn't exist | | `ValidationError` | Invalid input data | | `RateLimitError` | Too many requests | | `TimeoutError` | Request timed out | | `NetworkError` | Connection issues | ## Advanced Features ### Streaming Responses For real-time applications: ```python theme={null} for chunk in client.run_generic_stream({"query": "Tell a story"}): print(chunk, end="") ``` ### Batch Processing Process multiple requests efficiently: ```python theme={null} results = client.batch_run([ {"query": "Question 1"}, {"query": "Question 2"}, {"query": "Question 3"} ]) ``` ### Custom Headers Add custom headers for tracking: ```python theme={null} client = RunAgentClient( agent_id="agent-123", headers={ "X-Request-ID": "unique-id", "X-User-ID": "user-123" } ) ``` ## SDK Selection Guide Choose your SDK based on: ### Python SDK Best for: * Data science and ML applications * Backend services * Scripts and automation * Jupyter notebooks ### Rust SDK Best for: * High-performance applications * Systems programming * WebAssembly targets * Memory-efficient applications * Concurrent processing ### JavaScript SDK Best for: * Web applications * Node.js backends * React/Vue/Angular apps * Serverless functions ### Go SDK Best for: * Microservices * Cloud-native applications * CLI tools * Concurrent processing ## Performance Considerations | SDK | Startup Time | Memory Usage | Throughput | Type Safety | | ---------- | ------------ | ------------ | ---------- | ------------- | | Python | Medium | Medium | Good | Runtime | | Rust | Fast | Very Low | Excellent | Compile-time | | JavaScript | Fast | Low | Good | Optional (TS) | | Go | Fast | Low | Excellent | Compile-time | ## Migration Guide Moving between SDKs? The concepts remain the same: 1. **Client initialization** - Same parameters 2. **Method names** - Consistent across languages 3. **Response format** - JSON-compatible structures 4. **Error handling** - Similar error types ## Getting Help * **Documentation**: Language-specific guides * **Examples**: GitHub repositories with samples * **Community**: Discord channels for each SDK * **Support**: [support@run-agent.ai](mailto:support@run-agent.ai) ## Next Steps Start with our most mature SDK High-performance native SDK Understand the underlying API * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Python SDK API Reference Source: https://docs.run-agent.ai/sdk/python/api-reference Complete API reference for RunAgent Python SDK ## RunAgentClient Synchronous client for interacting with RunAgent. ### Constructor ```python theme={null} RunAgentClient( agent_id: str, api_key: Optional[str] = None, base_url: str = "https://api.run-agent.ai", timeout: int = 30, max_retries: int = 3, headers: Optional[Dict[str, str]] = None ) ``` #### Parameters * `agent_id` (str): The ID of your deployed agent * `api_key` (str, optional): API key for authentication * `base_url` (str): Base URL for API endpoints * `timeout` (int): Request timeout in seconds * `max_retries` (int): Maximum number of retry attempts * `headers` (dict, optional): Additional headers ### Methods #### run\_generic ```python theme={null} run_generic( input_data: Dict[str, Any], timeout: Optional[int] = None, headers: Optional[Dict[str, str]] = None ) -> Dict[str, Any] ``` Run agent with generic input/output. **Parameters:** * `input_data`: Dictionary containing input for the agent * `timeout`: Override default timeout * `headers`: Additional headers for this request **Returns:** Dictionary with agent response #### run\_generic\_stream ```python theme={null} run_generic_stream( input_data: Dict[str, Any], timeout: Optional[int] = None, headers: Optional[Dict[str, str]] = None ) -> Generator[str, None, None] ``` Stream agent responses in real-time. **Parameters:** * `input_data`: Dictionary containing input for the agent * `timeout`: Override default timeout * `headers`: Additional headers for this request **Returns:** Generator yielding response chunks ## AsyncRunAgentClient Asynchronous client for interacting with RunAgent. ### Constructor ```python theme={null} AsyncRunAgentClient( agent_id: str, api_key: Optional[str] = None, base_url: str = "https://api.run-agent.ai", timeout: int = 30, max_retries: int = 3, headers: Optional[Dict[str, str]] = None ) ``` Parameters are the same as `RunAgentClient`. ### Methods #### run\_generic ```python theme={null} async run_generic( input_data: Dict[str, Any], timeout: Optional[int] = None, headers: Optional[Dict[str, str]] = None ) -> Dict[str, Any] ``` Async version of run\_generic. #### run\_generic\_stream ```python theme={null} async run_generic_stream( input_data: Dict[str, Any], timeout: Optional[int] = None, headers: Optional[Dict[str, str]] = None ) -> AsyncGenerator[str, None] ``` Async generator for streaming responses. ## Exceptions ### RunAgentError Base exception for all RunAgent errors. ```python theme={null} class RunAgentError(Exception): def __init__(self, message: str, code: Optional[str] = None, details: Optional[Dict] = None): self.message = message self.code = code self.details = details ``` ### Specific Exceptions * `AuthenticationError`: Invalid or missing API key * `AgentNotFoundError`: Agent ID doesn't exist * `ValidationError`: Invalid input data * `RateLimitError`: Too many requests * `TimeoutError`: Request timed out * `NetworkError`: Network-related errors ## Type Definitions ```python theme={null} from typing import Dict, Any, Optional, Generator, AsyncGenerator # Input/Output types InputData = Dict[str, Any] OutputData = Dict[str, Any] # Stream types StreamChunk = str StreamGenerator = Generator[StreamChunk, None, None] AsyncStreamGenerator = AsyncGenerator[StreamChunk, None] ``` ## Configuration ### Environment Variables * `RUNAGENT_API_KEY`: Default API key * `RUNAGENT_API_URL`: Override base URL * `RUNAGENT_TIMEOUT`: Default timeout * `RUNAGENT_LOG_LEVEL`: Logging level ### Configuration File Location: `~/.runagent/config.json` ```json theme={null} { "api_key": "your-api-key", "api_url": "https://api.run-agent.ai", "timeout": 30, "retry_config": { "max_retries": 3, "retry_delay": 1.0, "retry_backoff": 2.0 } } ``` ## Complete Example ```python theme={null} from runagent import RunAgentClient, RunAgentError import asyncio # Synchronous example def sync_example(): client = RunAgentClient(agent_id="agent-123") try: # Simple request result = client.run_generic({"query": "Hello"}) print(f"Response: {result}") # Streaming for chunk in client.run_generic_stream({"query": "Tell a story"}): print(chunk, end="") except RunAgentError as e: print(f"Error: {e.message}") # Asynchronous example async def async_example(): from runagent import AsyncRunAgentClient client = AsyncRunAgentClient(agent_id="agent-123") # Concurrent requests tasks = [ client.run_generic({"query": f"Question {i}"}) for i in range(5) ] results = await asyncio.gather(*tasks) # Streaming async for chunk in client.run_generic_stream({"query": "Stream test"}): print(chunk, end="") # Run examples sync_example() asyncio.run(async_example()) ``` ## See Also * [Getting Started](/sdk/python/getting-started) - Introduction to the SDK * [Examples](/resources/examples) - More code examples * [API Introduction](/api-reference/introduction) - REST API documentation # Asynchronous Client Source: https://docs.run-agent.ai/sdk/python/async-client Using the RunAgent Python SDK asynchronously ## Overview The asynchronous client enables non-blocking operations, perfect for high-performance applications, concurrent requests, and modern async Python applications. ## Initialization ```python theme={null} from runagent import AsyncRunAgentClient import asyncio # Basic initialization client = AsyncRunAgentClient(agent_id="your-agent-id") # With all options client = AsyncRunAgentClient( agent_id="your-agent-id", api_key="your-api-key", base_url="https://api.run-agent.ai", timeout=30, max_retries=3 ) ``` ## Basic Usage ### Simple Async Request ```python theme={null} async def main(): client = AsyncRunAgentClient(agent_id="your-agent-id") result = await client.run_generic({ "query": "What's the weather like?", "location": "Tokyo" }) print(result) # Run the async function asyncio.run(main()) ``` ### Multiple Concurrent Requests ```python theme={null} async def process_multiple(): client = AsyncRunAgentClient(agent_id="your-agent-id") # Create multiple tasks tasks = [ client.run_generic({"query": "Question 1"}), client.run_generic({"query": "Question 2"}), client.run_generic({"query": "Question 3"}) ] # Run concurrently results = await asyncio.gather(*tasks) for i, result in enumerate(results): print(f"Result {i+1}: {result}") asyncio.run(process_multiple()) ``` ## Async Context Manager ```python theme={null} async def main(): async with AsyncRunAgentClient(agent_id="your-agent-id") as client: result = await client.run_generic({"query": "Hello"}) print(result) # Client automatically cleaned up asyncio.run(main()) ``` ## Error Handling ```python theme={null} async def safe_run(): client = AsyncRunAgentClient(agent_id="your-agent-id") try: result = await client.run_generic({"query": "Test"}) return result except asyncio.TimeoutError: print("Request timed out") except RunAgentError as e: print(f"Agent error: {e}") except Exception as e: print(f"Unexpected error: {e}") asyncio.run(safe_run()) ``` ## Advanced Patterns ### Rate Limited Concurrent Processing ```python theme={null} async def process_with_limit(items, max_concurrent=5): client = AsyncRunAgentClient(agent_id="your-agent-id") semaphore = asyncio.Semaphore(max_concurrent) async def process_item(item): async with semaphore: return await client.run_generic(item) tasks = [process_item(item) for item in items] return await asyncio.gather(*tasks) # Process 100 items, max 5 at a time items = [{"query": f"Item {i}"} for i in range(100)] results = asyncio.run(process_with_limit(items)) ``` ### Async Queue Processing ```python theme={null} async def queue_processor(): client = AsyncRunAgentClient(agent_id="your-agent-id") queue = asyncio.Queue() # Producer async def producer(): for i in range(10): await queue.put({"query": f"Task {i}"}) await asyncio.sleep(0.1) # Consumer async def consumer(): while True: try: item = await asyncio.wait_for(queue.get(), timeout=1.0) result = await client.run_generic(item) print(f"Processed: {result}") except asyncio.TimeoutError: break # Run producer and consumer concurrently await asyncio.gather(producer(), consumer()) asyncio.run(queue_processor()) ``` ### Timeout Handling ```python theme={null} async def with_timeout(): client = AsyncRunAgentClient(agent_id="your-agent-id") try: # Set a 5-second timeout result = await asyncio.wait_for( client.run_generic({"query": "Complex task"}), timeout=5.0 ) print(result) except asyncio.TimeoutError: print("Operation timed out after 5 seconds") asyncio.run(with_timeout()) ``` ## Integration with Web Frameworks ### FastAPI Example ```python theme={null} from fastapi import FastAPI, HTTPException from runagent import AsyncRunAgentClient app = FastAPI() client = AsyncRunAgentClient(agent_id="your-agent-id") @app.post("/process") async def process_request(data: dict): try: result = await client.run_generic(data) return {"status": "success", "result": result} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) ``` ### aiohttp Example ```python theme={null} from aiohttp import web from runagent import AsyncRunAgentClient client = AsyncRunAgentClient(agent_id="your-agent-id") async def handle_request(request): data = await request.json() result = await client.run_generic(data) return web.json_response(result) app = web.Application() app.router.add_post('/process', handle_request) ``` ## Performance Tips 1. **Reuse Client Instance** ```python theme={null} # Good - single client for all requests client = AsyncRunAgentClient(agent_id="...") async def process_many(items): tasks = [client.run_generic(item) for item in items] return await asyncio.gather(*tasks) ``` 2. **Use Connection Pooling** ```python theme={null} client = AsyncRunAgentClient( agent_id="...", connection_pool_size=20 # Adjust based on load ) ``` 3. **Batch When Possible** ```python theme={null} # Instead of many small requests # results = [await client.run_generic(item) for item in items] # Batch them result = await client.run_generic({ "batch": items, "process": "parallel" }) ``` ## See Also * [Sync Client](/sdk/python/sync-client) - For simpler use cases * [Streaming](/sdk/python/streaming) - For real-time responses * [API Reference](/sdk/python/api-reference) - Complete method documentation # Getting Started with Python SDK Source: https://docs.run-agent.ai/sdk/python/getting-started Start using the RunAgent Python SDK The RunAgent Python SDK provides a simple and powerful interface for interacting with your deployed agents. It supports both synchronous and asynchronous operations, with built-in streaming capabilities. ## Installation Install the SDK using pip: ```bash theme={null} pip install runagent ``` The SDK is included with the main `runagent` package. No separate installation needed. ## Quick Start ### Basic Usage ```python theme={null} from runagent import RunAgentClient # Initialize the client client = RunAgentClient(agent_id="your-agent-id") # Simple invocation result = client.run_generic({ "query": "What's the capital of France?", "context": "Geography question" }) print(result) ``` ### With API Key ```python theme={null} from runagent import RunAgentClient # Initialize with API key client = RunAgentClient( agent_id="your-agent-id", api_key="your-api-key" # Optional if set in environment ) ``` ## Authentication The SDK supports multiple authentication methods: ```bash theme={null} export RUNAGENT_API_KEY="your-api-key" ``` ```python theme={null} # SDK will automatically use the environment variable client = RunAgentClient(agent_id="your-agent-id") ``` ```python theme={null} client = RunAgentClient( agent_id="your-agent-id", api_key="your-api-key" ) ``` ```python theme={null} # Uses ~/.runagent/config.json by default client = RunAgentClient(agent_id="your-agent-id") ``` ## Response Formats ### Standard Response ```python theme={null} result = client.run_generic({ "query": "Explain quantum computing", "max_length": 200 }) # Result is a dictionary print(result["answer"]) print(result["confidence"]) print(result["sources"]) ``` ### Streaming Response ```python theme={null} # Stream responses for real-time output for chunk in client.run_generic_stream({ "query": "Write a story about AI" }): print(chunk, end="", flush=True) ``` ## Error Handling The SDK provides comprehensive error handling: ```python theme={null} from runagent import RunAgentClient, RunAgentError client = RunAgentClient(agent_id="your-agent-id") try: result = client.run_generic({"query": "Hello"}) except RunAgentError as e: print(f"RunAgent error: {e}") print(f"Error code: {e.code}") print(f"Error details: {e.details}") except Exception as e: print(f"Unexpected error: {e}") ``` ### Common Error Types | Error | Description | | --------------------- | -------------------------- | | `AuthenticationError` | Invalid or missing API key | | `AgentNotFoundError` | Agent ID doesn't exist | | `ValidationError` | Invalid input data | | `TimeoutError` | Request timed out | | `RateLimitError` | Too many requests | ## Configuration Options ```python theme={null} from runagent import RunAgentClient client = RunAgentClient( agent_id="your-agent-id", api_key="your-api-key", base_url="https://api.run-agent.ai", # Custom API endpoint timeout=30, # Request timeout in seconds max_retries=3, # Number of retry attempts verify_ssl=True # SSL certificate verification ) ``` ## Input Validation The SDK validates inputs before sending requests: ```python theme={null} # This will raise ValidationError if required fields are missing try: result = client.run_generic({}) # Missing required 'query' field except ValidationError as e: print(f"Validation failed: {e}") ``` ## Logging Enable logging for debugging: ```python theme={null} import logging # Enable debug logging logging.basicConfig(level=logging.DEBUG) # Now SDK operations will print debug information client = RunAgentClient(agent_id="your-agent-id") result = client.run_generic({"query": "Test"}) ``` ## Complete Examples ### Question-Answering Bot ```python theme={null} from runagent import RunAgentClient def ask_agent(question): client = RunAgentClient(agent_id="qa-bot-agent") try: result = client.run_generic({ "query": question, "max_tokens": 500, "temperature": 0.7 }) return result.get("answer", "No answer available") except Exception as e: return f"Error: {str(e)}" # Usage answer = ask_agent("What is machine learning?") print(answer) ``` ### Interactive Chat ```python theme={null} from runagent import RunAgentClient def chat_with_agent(): client = RunAgentClient(agent_id="chat-agent") print("Chat started. Type 'quit' to exit.") while True: user_input = input("\nYou: ") if user_input.lower() == 'quit': break print("\nAgent: ", end="") for chunk in client.run_generic_stream({ "query": user_input, "conversation_id": "session-123" }): print(chunk, end="", flush=True) print() # New line after response # Start chat chat_with_agent() ``` ### Batch Processing ```python theme={null} from runagent import RunAgentClient import json def process_batch(items): client = RunAgentClient(agent_id="processor-agent") results = [] for item in items: try: result = client.run_generic({ "data": item, "operation": "analyze" }) results.append({ "input": item, "output": result, "status": "success" }) except Exception as e: results.append({ "input": item, "output": None, "status": "error", "error": str(e) }) return results # Process multiple items items = ["data1", "data2", "data3"] results = process_batch(items) print(json.dumps(results, indent=2)) ``` ## Best Practices Create client instances once and reuse them for multiple requests Always implement proper error handling for production use Use streaming for long responses to improve user experience Configure appropriate timeouts based on your agent's complexity ## Next Steps Deep dive into synchronous operations Learn about async/await support Master real-time streaming Complete API documentation # Streaming Responses Source: https://docs.run-agent.ai/sdk/python/streaming Real-time streaming with RunAgent Python SDK ## Overview Streaming allows you to receive agent responses in real-time as they're generated, perfect for chatbots, live updates, and improving perceived performance. ## Basic Streaming ### Synchronous Streaming ```python theme={null} from runagent import RunAgentClient client = RunAgentClient(agent_id="your-agent-id") # Stream responses for chunk in client.run_generic_stream({ "query": "Tell me a long story about space exploration" }): print(chunk, end="", flush=True) ``` ### Asynchronous Streaming ```python theme={null} from runagent import AsyncRunAgentClient import asyncio async def stream_response(): client = AsyncRunAgentClient(agent_id="your-agent-id") async for chunk in client.run_generic_stream({ "query": "Explain quantum computing in detail" }): print(chunk, end="", flush=True) asyncio.run(stream_response()) ``` ## Stream Processing ### Collecting Chunks ```python theme={null} def get_complete_response(client, query): chunks = [] for chunk in client.run_generic_stream({"query": query}): chunks.append(chunk) # Optionally process each chunk print(chunk, end="", flush=True) # Return complete response return "".join(chunks) client = RunAgentClient(agent_id="your-agent-id") full_response = get_complete_response(client, "Your question here") ``` ### Processing Stream Data ```python theme={null} def process_stream(client, query): word_count = 0 for chunk in client.run_generic_stream({"query": query}): # Process each chunk words = chunk.split() word_count += len(words) # Could do other processing like sentiment analysis yield { "chunk": chunk, "words_so_far": word_count } ``` ## Advanced Streaming Patterns ### Stream with Timeout ```python theme={null} import time def stream_with_timeout(client, query, timeout=30): start_time = time.time() for chunk in client.run_generic_stream({"query": query}): if time.time() - start_time > timeout: yield "\n[Response truncated due to timeout]" break yield chunk ``` ### Buffered Streaming ```python theme={null} def buffered_stream(client, query, buffer_size=10): buffer = [] for chunk in client.run_generic_stream({"query": query}): buffer.append(chunk) if len(buffer) >= buffer_size: # Process buffer yield "".join(buffer) buffer = [] # Don't forget remaining data if buffer: yield "".join(buffer) ``` ### Stream with Progress ```python theme={null} def stream_with_progress(client, query): chunks_received = 0 for chunk in client.run_generic_stream({"query": query}): chunks_received += 1 # Update progress (could be a callback, progress bar, etc.) progress = { "chunk": chunk, "chunks_received": chunks_received, "timestamp": time.time() } yield progress ``` ## Web Integration ### Flask SSE Example ```python theme={null} from flask import Flask, Response, request from runagent import RunAgentClient app = Flask(__name__) client = RunAgentClient(agent_id="your-agent-id") @app.route('/stream') def stream(): query = request.args.get('query', 'Hello') def generate(): for chunk in client.run_generic_stream({"query": query}): yield f"data: {chunk}\n\n" return Response( generate(), mimetype="text/event-stream", headers={ "Cache-Control": "no-cache", "X-Accel-Buffering": "no" } ) ``` ### WebSocket Streaming ```python theme={null} import asyncio import websockets from runagent import AsyncRunAgentClient async def handle_websocket(websocket, path): client = AsyncRunAgentClient(agent_id="your-agent-id") async for message in websocket: data = json.loads(message) async for chunk in client.run_generic_stream(data): await websocket.send(chunk) start_server = websockets.serve(handle_websocket, "localhost", 8765) asyncio.run(start_server) ``` ## Error Handling in Streams ```python theme={null} def safe_stream(client, query): try: for chunk in client.run_generic_stream({"query": query}): yield chunk except StreamError as e: yield f"\n[Stream error: {e}]" except Exception as e: yield f"\n[Unexpected error: {e}]" ``` ## Stream Transformation ### Format Conversion ```python theme={null} def stream_as_json(client, query): """Convert stream to JSON events""" for i, chunk in enumerate(client.run_generic_stream({"query": query})): yield json.dumps({ "index": i, "content": chunk, "timestamp": time.time() }) + "\n" ``` ### Markdown Processing ````python theme={null} def stream_markdown(client, query): """Process markdown in real-time""" buffer = "" for chunk in client.run_generic_stream({"query": query}): buffer += chunk # Check for complete markdown elements if "```" in buffer: # Process code blocks yield process_code_block(buffer) buffer = "" else: yield chunk ```` ## Performance Considerations 1. **Don't Block the Stream** ```python theme={null} # Good - process asynchronously async def process_stream(client, query): async for chunk in client.run_generic_stream(query): # Non-blocking processing asyncio.create_task(process_chunk(chunk)) yield chunk ``` 2. **Handle Backpressure** ```python theme={null} def controlled_stream(client, query, max_buffer=1000): buffer_size = 0 for chunk in client.run_generic_stream({"query": query}): buffer_size += len(chunk) if buffer_size > max_buffer: # Pause or slow down time.sleep(0.1) buffer_size = 0 yield chunk ``` ## See Also * [Sync Client](/sdk/python/sync-client) - Non-streaming operations * [Async Client](/sdk/python/async-client) - Async streaming patterns * [API Reference](/sdk/python/api-reference) - Complete streaming API # Synchronous Client Source: https://docs.run-agent.ai/sdk/python/sync-client Using the RunAgent Python SDK synchronously ## Overview The synchronous client provides blocking operations for interacting with RunAgent. Perfect for scripts, simple applications, and when you don't need concurrent operations. ## Initialization ```python theme={null} from runagent import RunAgentClient # Basic initialization client = RunAgentClient(agent_id="your-agent-id") # With all options client = RunAgentClient( agent_id="your-agent-id", api_key="your-api-key", base_url="https://api.run-agent.ai", timeout=30, max_retries=3 ) ``` ## Basic Usage ### Simple Request ```python theme={null} result = client.run_generic({ "query": "What's the weather like?", "location": "San Francisco" }) print(result) # {'weather': 'sunny', 'temperature': 72, 'unit': 'fahrenheit'} ``` ### With Error Handling ```python theme={null} try: result = client.run_generic({"query": "Hello"}) print(f"Success: {result}") except RunAgentError as e: print(f"Error: {e.message}") print(f"Code: {e.code}") except Exception as e: print(f"Unexpected error: {e}") ``` ## Request Options ### Timeout Control ```python theme={null} # Short timeout for quick operations result = client.run_generic( {"query": "Quick question"}, timeout=5 # 5 seconds ) # Longer timeout for complex operations result = client.run_generic( {"query": "Analyze this dataset", "data": large_data}, timeout=120 # 2 minutes ) ``` ### Custom Headers ```python theme={null} result = client.run_generic( {"query": "Test"}, headers={ "X-Request-ID": "unique-123", "X-User-ID": "user-456" } ) ``` ## Response Handling ### Accessing Response Metadata ```python theme={null} response = client.run_generic_with_metadata({"query": "Test"}) # Access result and metadata print(response.result) # Actual agent response print(response.execution_time) # Time taken print(response.tokens_used) # Token usage print(response.agent_version) # Agent version ``` ### Parsing Complex Responses ```python theme={null} result = client.run_generic({ "action": "analyze", "data": {"sales": [100, 200, 300]} }) # Handle structured response if result.get("status") == "success": analysis = result["analysis"] print(f"Total: {analysis['total']}") print(f"Average: {analysis['average']}") ``` ## Advanced Features ### Batch Processing ```python theme={null} # Process multiple requests requests = [ {"query": "Question 1"}, {"query": "Question 2"}, {"query": "Question 3"} ] results = [] for request in requests: try: result = client.run_generic(request) results.append({"input": request, "output": result}) except Exception as e: results.append({"input": request, "error": str(e)}) ``` ### Session Management ```python theme={null} # Maintain conversation context session_id = "conv-123" # First message response1 = client.run_generic({ "query": "My name is Alice", "session_id": session_id }) # Follow-up message response2 = client.run_generic({ "query": "What's my name?", "session_id": session_id }) # Should remember "Alice" ``` ### Retry Configuration ```python theme={null} # Custom retry logic client = RunAgentClient( agent_id="your-agent-id", max_retries=5, retry_delay=1.0, # Start with 1 second retry_backoff=2.0 # Double each retry ) ``` ## Best Practices 1. **Reuse Client Instances** ```python theme={null} # Good - create once client = RunAgentClient(agent_id="...") for item in items: client.run_generic(item) # Bad - create every time for item in items: client = RunAgentClient(agent_id="...") client.run_generic(item) ``` 2. **Handle Timeouts** ```python theme={null} try: result = client.run_generic(data, timeout=10) except TimeoutError: # Handle timeout appropriately result = {"error": "Request timed out"} ``` 3. **Log Requests** ```python theme={null} import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def run_with_logging(client, data): logger.info(f"Request: {data}") try: result = client.run_generic(data) logger.info(f"Response: {result}") return result except Exception as e: logger.error(f"Error: {e}") raise ``` ## See Also * [Async Client](/sdk/python/async-client) - For concurrent operations * [Streaming](/sdk/python/streaming) - For real-time responses * [API Reference](/sdk/python/api-reference) - Complete method documentation # Rust SDK Getting Started Source: https://docs.run-agent.ai/sdk/rust/getting-started Get started with the RunAgent Rust SDK The RunAgent Rust SDK provides a high-performance interface for interacting with your deployed agents. It supports both synchronous and asynchronous operations with built-in streaming capabilities. ## Installation Add the SDK to your `Cargo.toml`: ```toml theme={null} [dependencies] runagent = "0.1.3" tokio = { version = "1.0", features = ["full"] } serde_json = "1.0" ``` ## Quick Start ### Basic Usage ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize the client let client = RunAgentClient::new( "your-agent-id", "generic", true // local = true ).await?; // Simple invocation let response = client.run(&[ ("message", json!("What's the capital of France?")), ("temperature", json!(0.7)) ]).await?; println!("Response: {}", response); Ok(()) } ``` ### With Specific Address ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to specific host and port let client = RunAgentClient::with_address( "your-agent-id", "generic", true, Some("localhost"), Some(8450) ).await?; let response = client.run(&[ ("query", json!("Hello from Rust SDK")) ]).await?; println!("{}", serde_json::to_string_pretty(&response)?); Ok(()) } ``` ## Authentication The SDK automatically uses configuration from the environment or database: ```bash theme={null} export RUNAGENT_API_KEY="your-api-key" export RUNAGENT_BASE_URL="https://api.run-agent.ai" ``` ## Response Handling ### Standard Response ```rust theme={null} let response = client.run(&[ ("query", json!("Explain quantum computing")), ("max_length", json!(200)) ]).await?; // Response is a serde_json::Value if let Some(answer) = response.get("answer") { println!("Answer: {}", answer); } ``` ### Streaming Response ```rust theme={null} use futures::StreamExt; let mut stream = client.run_stream(&[ ("query", json!("Write a story about AI")) ]).await?; while let Some(chunk_result) = stream.next().await { match chunk_result { Ok(chunk) => print!("{}", chunk), Err(e) => { println!("Error: {}", e); break; } } } ``` ## Error Handling The SDK provides comprehensive error handling: ```rust theme={null} use runagent::types::{RunAgentError, RunAgentResult}; match client.run(&[("query", json!("Hello"))]).await { Ok(response) => println!("Success: {}", response), Err(RunAgentError::Authentication { message }) => { println!("Auth error: {}", message); } Err(RunAgentError::Connection { message }) => { println!("Connection error: {}", message); } Err(e) => println!("Other error: {}", e), } ``` ### Common Error Types | Error | Description | | ---------------- | -------------------------- | | `Authentication` | Invalid or missing API key | | `Validation` | Invalid input data | | `Connection` | Network-related errors | | `Server` | Server-side errors | | `Database` | Local database errors | ## Configuration Options ```rust theme={null} use runagent::RunAgentConfig; let config = RunAgentConfig::new() .with_api_key("your-api-key") .with_base_url("https://api.run-agent.ai") .with_logging() .build(); ``` ## Framework Examples ### LangChain Integration ```rust theme={null} let client = RunAgentClient::new("langchain-agent", "generic", true).await?; let response = client.run(&[ ("messages", json!([ {"role": "user", "content": "What is the weather like?"} ])) ]).await?; ``` ### AutoGen Integration ```rust theme={null} let client = RunAgentClient::new("autogen-agent", "autogen_invoke", true).await?; let response = client.run(&[ ("task", json!("What is AutoGen?")) ]).await?; ``` ### CrewAI Integration ```rust theme={null} let client = RunAgentClient::new("crewai-agent", "research_crew", true).await?; let response = client.run(&[ ("topic", json!("AI Agent Deployment")) ]).await?; ``` ## Best Practices * Reuse client instances for multiple requests * Handle errors appropriately for production use * Use streaming for long responses * Configure timeouts based on agent complexity * Use structured logging for debugging ## Next Steps * [Sync and Async Operations](/sdk/rust/async-operations) * [Streaming Responses](/sdk/rust/streaming) * [Local Server Setup](/sdk/rust/local-server) * [API Reference](/sdk/rust/api-reference) ``` ``` # Deploy Your First Agent Source: https://docs.run-agent.ai/tutorials/deploy-your-first-agent Deploy your first AI agent in under 5 minutes and see the magic happen **Prerequisites**: Python 3.8+ and pip installed on your system ## The Magic You're About to Experience In the next 5 minutes, you'll: 1. **Deploy a Python agent** that responds intelligently to questions 2. **Call it from multiple languages** like it's a native function 3. **Stream responses in real-time** across language boundaries 4. **Understand why** this changes everything for AI development Ready? Let's make some magic happen ✨ ## Installation: Your Gateway to Multi-Language AI Install RunAgent CLI (includes Python SDK): ```bash theme={null} pip install runagent ``` Verify the installation: ```bash theme={null} runagent --version ``` **What just happened?** You now have both a powerful CLI for deploying agents AND a Python SDK for accessing them. Two tools, one install! ## Create Your First Agent: From Zero to Intelligence Let's create a simple but intelligent agent that demonstrates RunAgent's core superpower: ```bash theme={null} runagent init my_agent cd my_agent ``` **What RunAgent just created for you:** ``` my_agent/ ├── main.py # Your agent's brain (two smart functions) ├── email_agent.py # Mock AI client (no API keys needed!) ├── runagent.config.json # The bridge to other languages └── __init__.py # Python package magic ``` **Pro insight**: This isn't just boilerplate. Each file serves a specific purpose in making your Python agent accessible from any programming language. Your agent has two functions that will become universally accessible APIs: ```python Non-streaming Intelligence theme={null} def mock_response(message, role="user"): """Your agent's instant-response mode""" client = MockOpenAIClient() prompt = [{"role": role, "content": message}] response = client.create(model="gpt-4", messages=prompt) print(f"Tokens used: {response.usage_tokens}") print(f"Response time: {response.response_time:.2f}s") return response.content # Complete response, all at once ``` ```python Streaming Intelligence theme={null} def mock_response_stream(message, role="user") -> Iterator[str]: """Your agent's real-time streaming mode""" client = MockOpenAIClient() prompt = [{"role": role, "content": message}] for chunk in client.create(model="gpt-4", messages=prompt, stream=True): if not chunk.finished: yield chunk.delta # Stream words as they're "generated" else: yield "\n[STREAM COMPLETE]" ``` **The "Aha!" Moment**: These Python functions accept `message` and `role` parameters. That's exactly what you'll pass from JavaScript, Rust, or any other language—RunAgent handles the translation! Open `runagent.config.json` to see how Python functions become universal APIs: ```json theme={null} { "agent_name": "my-agent", "description": "A simple placeholder agent", "framework": "default", "agent_architecture": { "entrypoints": [ { "file": "main.py", "module": "mock_response", "tag": "minimal" }, { "file": "main.py", "module": "mock_response_stream", "tag": "minimal_stream" } ] } } ``` **What this means**: * Your `mock_response` function becomes accessible via the `minimal` tag * Your streaming function gets the `minimal_stream` tag (note the `_stream` suffix!) * Any language can now call these functions by their tags Launch your agent into the RunAgent universe: ```bash theme={null} runagent serve . ``` **You'll see magic happen:** ``` 🚀 Agent Starting... 📦 Agent ID: agent_abc123 🌐 Server running at: http://localhost:8000 ✅ Agent ready for multi-language access! ``` **Critical insight**: That `agent_id` is your agent's universal address. Any programming language can now connect to your Python intelligence using this ID! ## The Multi-Language Magic: Same Agent, Every Language Now comes the mind-blowing part. Your Python agent is now accessible from any supported language as if it were written natively in that language. ### Standard Responses: Get Complete Intelligence The fastest way to prove the magic works: ```bash theme={null} runagent run --id agent_abc123 --local --tag minimal \ --message "Explain why the sky is blue" \ --role user ``` **Live output:** ``` 🚀 RunAgent Configuration: Agent ID: agent_abc123 Tag: minimal Local: Yes 🔍 Auto-resolved address: 127.0.0.1:8000 🤖 Executing agent: agent_abc123 ✅ Agent execution completed! The sky appears blue due to a phenomenon called Rayleigh scattering... ``` **What just happened?** You called your Python function from the command line with zero setup! ```python theme={null} from runagent import RunAgentClient # Connect to your agent (replace with your actual agent_id) ra = RunAgentClient( agent_id="agent_abc123", entrypoint_tag="minimal", local=True ) # Call your agent like it's a local function result = ra.run( message="Analyze the benefits of remote work for software teams", role="user" ) print(result) ``` **The magic**: This feels like calling a local Python function, but it's actually making network calls to your deployed agent! First, install in your JS project: ```bash theme={null} npm install runagent ``` Then use your Python agent from JavaScript: ```javascript theme={null} import { RunAgentClient } from 'runagent'; const ra = new RunAgentClient({ agentId: "agent_abc123", entrypointTag: "minimal", local: true }); await ra.initialize(); const result = await ra.run({ message: 'What makes a great engineering team?', role: 'user' }); console.log(result); ``` **Mind-bending reality**: JavaScript developers are now calling your Python AI agent as if it were native JavaScript code! You can connect using the server URL instead of agent\_id: ```python theme={null} from runagent import RunAgentClient ra = RunAgentClient( host="localhost", port=8000, entrypoint_tag="minimal", local=True ) result = ra.run(message="Hello from any language!") print(result) ``` **Why this matters**: You can deploy to any server and connect from anywhere! ### Streaming Intelligence: Real-Time AI Responses Watch your Python agent stream responses in real-time to any language: Experience real-time AI streaming in your terminal: ```bash theme={null} runagent run --id agent_abc123 --local --tag minimal_stream \ --message "Write a creative story about AI agents" ``` **Live streaming output:** ``` 🚀 RunAgent Configuration: Agent ID: agent_abc123 Tag: minimal_stream Local: Yes 🔍 Auto-resolved address: 127.0.0.1:8000 Once upon a time, in a digital realm far beyond the clouds... [STREAM COMPLETE] ``` **What's happening**: Your Python generator function is streaming across the network in real-time! ```python theme={null} from runagent import RunAgentClient # Connect to streaming entrypoint (note the '_stream' tag) ra = RunAgentClient( agent_id="agent_abc123", entrypoint_tag="minimal_stream", local=True ) # Stream responses as they generate for chunk in ra.run( message="Explain quantum computing step by step" ): print(chunk, end="", flush=True) ``` **The beauty**: This looks like a normal Python iterator, but chunks are streaming from your deployed agent in real-time! ```javascript theme={null} import { RunAgentClient } from 'runagent'; const ra = new RunAgentClient({ agentId: "agent_abc123", entrypointTag: "minimal_stream", // The magic '_stream' suffix local: true }); await ra.initialize(); const stream = await ra.run({ message: 'Write a poem about coding' }); // Modern JavaScript async iteration for await (const chunk of stream) { process.stdout.write(chunk); } ``` **Mind-blown moment**: JavaScript developers are consuming real-time streams from your Python agent using native async iterators! ```rust theme={null} use runagent::client::RunAgentClient; use serde_json::json; use futures::StreamExt; #[tokio::main] async fn main() -> Result<(), Box> { let client = RunAgentClient::new("agent_abc123", "minimal_stream", true).await?; let mut stream = client.run_stream(&[ ("message", json!("Explain machine learning concepts")) ]).await?; while let Some(chunk) = stream.next().await { print!("{}", chunk?); } Ok(()) } ``` **Performance revelation**: Rust developers get zero-copy streaming from your Python agent with full type safety! ```go theme={null} package main import ( "context" "fmt" "log" "time" "github.com/runagent-dev/runagent/runagent-go/runagent/pkg/client" ) func main() { c, err := client.NewWithAddress("841debad-7433-46ae-a0ec-0540d0df7314", "minimal_stream", true, "localhost", 8450) if err != nil { log.Fatal(err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() s, err := c.RunStream(ctx, map[string]interface{}{"role": "user", "message": "Analyze the benefits of remote work for software teams"}) if err != nil { log.Fatal(err) } defer s.Close() for { data, hasMore, err := s.Next(ctx) if err != nil { log.Fatal(err) } if !hasMore { break } fmt.Printf("Received: %v\n", data) } } ``` ## Level Up: Real AI Frameworks Ready to move beyond mock responses? RunAgent works with any Python AI framework: ```bash theme={null} runagent init my_langgraph_agent --langgraph cd my_langgraph_agent # Add your AI power echo "OPENAI_API_KEY=your-key-here" > .env # Install and activate pip install -r requirements.txt runagent serve . ``` **What you get**: Multi-step reasoning agents with state management, accessible from any language! ```bash theme={null} runagent init my_crew_agent --crewai cd my_crew_agent # Configure your AI crew echo "OPENAI_API_KEY=your-key-here" > .env pip install -r requirements.txt runagent serve . ``` **What you get**: Coordinated AI agent teams working together, controllable from JavaScript, Rust, Go, or Python! ```bash theme={null} runagent init my_custom_agent cd my_custom_agent # Edit main.py with your framework # Update runagent.config.json with your entrypoints runagent serve . ``` **What you get**: Total freedom to use any Python AI library while maintaining multi-language access! ## Understanding the Universal Entrypoint System This is the core concept that makes RunAgent revolutionary: ### How Function Signatures Become Universal APIs ```mermaid theme={null} graph TD FUNC[Python Function
def my_agent query mode] CONFIG[runagent.config.json
Maps function to tag] ROUTER[RunAgent Router
Universal API Gateway] PY[Python SDK
client.run query mode] JS[JavaScript SDK
client.run object] RS[Rust SDK
client.run array] FUNC --> CONFIG CONFIG --> ROUTER ROUTER --> PY ROUTER --> JS ROUTER --> RS ``` **The Revolutionary Insight**: Your Python function signature automatically defines the API contract for all programming languages. Change the Python function, and all language SDKs automatically adapt! ### Streaming: The Real-Time Superpower When you use `Iterator[str]` in Python, RunAgent automatically: * 🔄 **Establishes WebSocket connections** for real-time data flow * 📡 **Streams chunks immediately** as your function yields them * 🌐 **Provides native iteration patterns** in each target language * ✅ **Handles connection lifecycle** and error recovery ```python theme={null} # Your Python generator def generate_report(topic: str) -> Iterator[str]: yield "# Report: " + topic + "\n\n" yield "## Introduction\n" # ... more yields # Becomes JavaScript async iterator for await (const chunk of stream) { document.body.innerHTML += chunk; } # Becomes Rust futures stream while let Some(chunk) = stream.next().await { println!("{}", chunk?); } ``` ## What Just Happened? The Full Picture In these 5 minutes, you've experienced something revolutionary: Your Python AI agent is now callable from any programming language with native-feeling APIs Streaming responses work seamlessly across language boundaries with zero setup No REST APIs to build, no WebSocket handling, no deployment complexity The same code and SDKs will work in production with automatic scaling ## The Path Forward: Your RunAgent Journey Understand the architecture that makes this magic possible Master the native patterns for each supported language See production-ready agents built with popular frameworks Scale your agents to serve millions of requests ## Common Questions from New Users **Most common fix**: Make sure your agent is still running: ```bash theme={null} runagent serve . # Keep this running in one terminal ``` Then use the SDK in another terminal or Python script. The agent needs to stay active to receive requests! **Check your configuration**: The tag in your SDK call must exactly match what's in `runagent.config.json`: ```bash theme={null} cat runagent.config.json | grep -A 5 "entrypoints" ``` Remember: streaming tags must end with `_stream`! **Install the dependencies**: Framework templates come with requirements: ```bash theme={null} pip install -r requirements.txt # For LangGraph, CrewAI, etc. ``` **Use a different port**: ```bash theme={null} runagent serve . --port 8080 ``` Then connect using `port=8080` in your SDK calls. **🎉 Congratulations!** You've just experienced the future of AI development. Your Python agents can now be accessed from any programming language with the same ease as calling local functions. This is just the beginning—imagine what you'll build next! **Ready to go deeper?** Join our [Discord community](https://discord.gg/runagent) to see what other developers are creating with RunAgent! * Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) * Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) * Follow us on [X](https://x.com/run_agent) * New here? [Sign up](https://run-agent.ai/dashboard) # Tutorials Overview Source: https://docs.run-agent.ai/tutorials/overview Guided, end-to-end projects that get you from zero to shipped New to RunAgent? Start with the **5-minute** path, then pick a real use-case. ## Start here Install, init, serve, and call your agent — includes streaming. Outcomes and expectations before you begin. Quick fixes for common setup and networking issues. ## Real use-cases ## After a tutorial * Compare SDK patterns in **Reference → SDK**. * Read **Core Concepts** if you want the "why". * Ship to prod via **How-to → Cloud Deployment**. - Join our [Discord Community](https://discord.gg/Q9P9AdHVHz) - Email us: [hi@run-agent.ai](mailto:hi@run-agent.ai) - Follow us on [X](https://x.com/run_agent) - New here? [Sign up](https://run-agent.ai/dashboard)