agents-client


Nameagents-client JSON
Version 0.1.23 PyPI version JSON
download
home_pagehttps://github.com/Levangie-Laboratories/agents-client
SummaryA client library for interacting with the Agents API
upload_time2024-11-20 21:39:48
maintainerNone
docs_urlNone
authorLevangie Laboratories
requires_python>=3.8
licenseNone
keywords agents api client chatbot ai
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Agents Client Library

## Overview
The Agents Client Library provides a simple interface for interacting with the Agents API. It handles authentication, request management, and provides convenient methods for managing chatbots and agents.

## Installation

### From PyPI
```bash
pip install agents-client
```

### From Source
```bash
git clone https://github.com/Levangie-Laboratories/agents-client.git
cd agents-client
pip install -r requirements.txt
```

## Configuration
The client library uses a `config.json` file for API settings. You can either use the default configuration or provide your own:

```python
from agents.client import AgentClient

# Using default configuration
client = AgentClient()

# Using custom configuration file
client = AgentClient(config_path='path/to/config.json')

# Override configuration programmatically
client = AgentClient(base_url='https://api.example.com', api_version='v2')
```

### Configuration Options
- `base_url`: API base URL
- `version`: API version
- `timeout`: Request timeout in seconds
- `retry_attempts`: Number of retry attempts
- `retry_delay`: Delay between retries in seconds

See `config.json` for all available options.

## Quick Start

### Basic Usage
```python
from client import ChatbotClient
from client.base_client import ApiError, AuthenticationError

# Initialize client
base_url = "http://localhost:8000"
chatbot = ChatbotClient(base_url)

# Set API key
api_key = "your-api-key"
chatbot.set_api_key(api_key)

try:
    # Create a chatbot instance
    config = {
        "temperature": 0.7,
        "max_tokens": 4000,
        "behavior": "A helpful assistant that provides clear and concise answers."
    }

    # Create the chatbot
    response = chatbot.create_chatbot(
        name="BasicChat",
        model="gpt-4o-mini",
        config=config
    )

    # Store chatbot ID
    chatbot_id = response.get('id')
    print(f"Created chatbot with ID: {chatbot_id}\n")

    # Example conversation
    message = "Hello! How are you?"
    chat_response = chatbot.chat(chatbot_id, message)
    print(f"Chatbot: {chat_response.get('response', 'No response')}\n")

except AuthenticationError as e:
    print(f"Authentication error: {str(e)}")
except ApiError as e:
    print(f"API error: {str(e)}")
```

### Async Streaming Example
```python
from agents.client import AgentClient
import asyncio

async def main():
    # Initialize client with async context manager
    async with AgentClient("http://localhost:8000") as client:
        client.set_api_key("your-api-key")

        # Create an agent with API execution mode
        config = {
            "behavior": "task-focused",
            "model": "gpt-4o-mini",
            "api_mode": True  # Enable API execution mode
        }
        agent = await client.create_agent_with_tools(
            name="FileManager",
            model="gpt-4o-mini",
            tools=FileTools(),  # Your tool class instance
            config=config
        )

        # Stream interactions with the agent
        async for event in client.process_agent_request(agent["id"], "Update debug mode in config.json"):
            if event["type"] == "function_call":
                print(f"Executing function: {event['data']['function']}")
                # Function is automatically executed by the client
            elif event["type"] == "execution_status":
                print(f"Execution result: {event['data']}")
            elif event["type"] == "completion":
                print(f"Task completed: {event['data']}")
            elif event["type"] == "error":
                print(f"Error: {event['data']}")

# Run the async client
asyncio.run(main())
```

### State Management Example
```python
async with AgentClient("http://localhost:8000") as client:
    # State is automatically synchronized
    async for event in client.process_agent_request(agent_id, message):
        if event["type"] == "state_update":
            print(f"Agent state updated: {event['data']}")
        elif event["type"] == "function_call":
            # State is preserved across function calls
            result = await client.execute_function(event["data"])
            # State is automatically updated with function results
            await client.submit_result(agent_id, event["data"]["sequence_id"], result)
```

## Chatbot Operations

### Creating a Chatbot
```python
from client import ChatbotClient
from client.base_client import ApiError, AuthenticationError

# Initialize client
base_url = "http://localhost:8000"
chatbot_client = ChatbotClient(base_url)

# Set API key
api_key = "your-api-key"
chatbot_client.set_api_key(api_key)

try:
    # Define configuration
    config = {
        "temperature": 0.7,
        "max_tokens": 4000,
        "behavior": "A helpful assistant that provides clear and concise answers."
    }

    # Create the chatbot
    response = chatbot_client.create_chatbot(
        name="BasicChat",
        model="gpt-4o-mini",
        config=config
    )

    # Store chatbot ID
    chatbot_id = response.get('id')
    print(f"Created chatbot with ID: {chatbot_id}\n")

except AuthenticationError as e:
    print(f"Authentication error: {str(e)}")
except ApiError as e:
    print(f"API error: {str(e)}")
```

### Listing Chatbots
```python
chatbots = client.list_chatbots()
for bot in chatbots:
    print(f"Bot: {bot['name']} (ID: {bot['id']})")
```

### Chatbot Interaction
```python
try:
    # Example conversation
    print("=== Chatbot Interaction ===\n")
    chat_response = chatbot_client.chat(
        chatbot_id,
        "What's the weather like today?"
    )
    print(f"Chatbot: {chat_response['data']['response']}\n")

    # Get chatbot history
    print("=== Chatbot History ===\n")
    history = chatbot_client.get_history(chatbot_id)
    print(f"Chat history: {history}\n")

except ApiError as e:
    print(f"API Error: {str(e)}\n")
```

### Updating Chatbots
```python
updated_config = {
    "temperature": 0.8,
    "max_tokens": 1000
}

updated_bot = client.update_chatbot(
    chatbot_id=123,
    name="UpdatedBot",
    model="gpt-4o-mini",
    config=updated_config
)
```

### Deleting Chatbots
```python
result = client.delete_chatbot(chatbot_id=123)
```

## Agent Operations

### Creating an Agent
```python
from client import AgentClient
from client.base_client import ApiError, AuthenticationError

# Initialize client
base_url = "http://localhost:8000"
agent_client = AgentClient(base_url)

# Set API key
api_key = "your-api-key"
agent_client.set_api_key(api_key)

try:
    # Define agent tools and configuration
    agent_tools = {
        "general": {
            "search": {
                "name": "search",
                "description": "Search for information",
                "parameters": {}
            }
        }
    }

    agent_config = {
        "model": "gpt-4o-mini",
        "temperature": 0.7,
        "max_tokens": 4000
    }

    # Create the agent
    agent = agent_client.create_agent(
        name="ResearchAgent",
        agent_type="research",
        behavior="A research agent that helps find and analyze information.",
        tools=agent_tools,
        config=agent_config
    )
    print(f"Created agent with ID: {agent['id']}\n")

except AuthenticationError as e:
    print(f"Authentication error: {str(e)}")
except ApiError as e:
    print(f"API error: {str(e)}")
```

### Listing Agents
```python
agents = client.list_agents()
for agent in agents:
    print(f"Agent: {agent['name']} (ID: {agent['id']})")
```

### Agent Interaction
```python
try:
    # Demonstrate agent interaction
    print("=== Agent Interaction ===\n")
    agent_response = agent_client.interact(
        agent['id'],
        "Find information about Python programming."
    )
    print(f"Agent response: {agent_response['data']['response']}\n")

    # Get agent state
    print("=== Agent State ===\n")
    state = agent_client.get_state(agent['id'])
    print(f"Agent state: {state}\n")

    # Demonstrate error handling
    print("=== Error Handling ===\n")
    try:
        # Try to interact with non-existent agent
        agent_client.interact("invalid-id", "Hello!")
    except ApiError as e:
        print(f"Handled API error: {str(e)}\n")

except AuthenticationError as e:
    print(f"Authentication error: {str(e)}")
except ApiError as e:
    print(f"API error: {str(e)}")
except Exception as e:
    print(f"Unexpected error: {str(e)}")
```

The new system simplifies command execution by:
```

Key features of the new command system:
- Automatic command execution and result handling
- Built-in command validation and safety checks
- Simplified tool registration using decorators
- Automatic result mapping in responses
- Support for both synchronous and asynchronous operations
- Comprehensive error handling and reporting

### Supported Commands
The client can execute various commands locally:

```python
# File operations
commands = [
    {"view_file": {"file_path": "config.json"}},
    {"smart_replace": {
        "file_path": "config.json",
        "old_text": "debug: false",
        "new_text": "debug: true"
    }},
    {"create_file": {
        "file_path": "new_file.txt",
        "content": "Hello, world!"
    }}
]

# Execute commands with safety checks
results = client.execute_commands(commands, context={})
```

### Command Execution Safety
- File path validation
- Comprehensive error handling
- Safe text replacement
- Automatic retries for network issues

```python
# Example with error handling
try:
    results = client.execute_commands(commands, context={})
    if any(r["status"] == "error" for r in results["command_results"]):
        print("Some commands failed to execute")
        for result in results["command_results"]:
            if result["status"] == "error":
                print(f"Error: {result['error']}")
except Exception as e:
    print(f"Execution failed: {str(e)}")
```

## Streaming Operations

### Basic Streaming
```python
async with AgentClient("http://localhost:8000") as client:
    # Stream responses from agent
    async for event in client.interact_stream(agent_id, message):
        if event["type"] == "function_call":
            # Handle function execution
            result = await client.execute_function(event["data"])
            await client.submit_result(agent_id, event["data"]["sequence_id"], result)
        elif event["type"] == "completion":
            print(f"Completed: {event['data']}")
```

### Concurrent Command Execution
```python
async def process_commands(client, commands, instance_id):
    # Commands are executed concurrently
    results = await client.execute_commands(commands, instance_id)
    return results
```

## Error Handling
The client includes comprehensive error handling with streaming support:

### Streaming Error Handling
```python
async with AgentClient("http://localhost:8000") as client:
    try:
        async for event in client.interact_stream(agent_id, message):
            if event["type"] == "error":
                print(f"Error occurred: {event['data']}")
                break
            elif event["type"] == "function_call":
                try:
                    result = await client.execute_function(event["data"])
                    await client.submit_result(
                        agent_id,
                        event["data"]["sequence_id"],
                        result
                    )
                except Exception as e:
                    print(f"Function execution error: {e}")
    except Exception as e:
        print(f"Stream error: {e}")
```

### Command Execution Errors
```python
try:
    results = client.execute_commands(commands, context)
    for result in results['command_results']:
        if result['status'] == 'error':
            print(f"Command {result['command']} failed: {result['error']}")
except client.CommandExecutionError as e:
    print(f"Execution error: {str(e)}")
```

### API Errors
```python
try:
    chatbot = client.get_chatbot(999)
except Exception as e:
    print(f"API error: {str(e)}")
```

## Best Practices
1. Always handle API errors in production code
2. Store API keys securely
3. Use appropriate timeouts for API calls
4. Monitor rate limits
5. Implement proper error handling
6. Validate file paths before operations
7. Use context information for better error tracking
8. Implement proper retry strategies

### Error Handling Best Practices
```python
# Comprehensive error handling example
try:
    # Initial interaction
    response = client.interact_with_agent(agent_id, message)
    
    if response['status'] == 'pending_execution':
        try:
            # Execute commands with safety checks
            results = client.execute_commands(
                response['commands'],
                response.get('context', {})
            )
            
            # Check individual command results
            failed_commands = [
                r for r in results['command_results']
                if r['status'] == 'error'
            ]
            
            if failed_commands:
                print("Some commands failed:")
                for cmd in failed_commands:
                    print(f"- {cmd['command']}: {cmd['error']}")
            
            # Continue interaction with results
            final_response = client.interact_with_agent(
                agent_id,
                message,
                execution_results=results
            )
            
        except client.CommandExecutionError as e:
            print(f"Command execution failed: {e}")
            # Handle command execution failure
            
except Exception as e:
    print(f"Interaction failed: {e}")
    # Handle interaction failure
```

## Advanced Usage

### Custom Headers
```python
client = AgentClient(
    base_url="http://localhost:8000",
    headers={"Custom-Header": "value"}
)
```

### Batch Operations
```python
# Create multiple chatbots
configs = [
    {"name": "Bot1", "model": "gpt-4o-mini", "config": {...}},
    {"name": "Bot2", "model": "gpt-4o-mini", "config": {...}}
]

chatbots = []
for config in configs:
    bot = client.create_chatbot(**config)
    chatbots.append(bot)
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Levangie-Laboratories/agents-client",
    "name": "agents-client",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "agents, api, client, chatbot, ai",
    "author": "Levangie Laboratories",
    "author_email": "brayden@levangielaboratories.com",
    "download_url": "https://files.pythonhosted.org/packages/8d/3f/8e4943c8f8e10a7ae4b229d933472c259c682b2f5762de228a644723aa9b/agents_client-0.1.23.tar.gz",
    "platform": null,
    "description": "# Agents Client Library\n\n## Overview\nThe Agents Client Library provides a simple interface for interacting with the Agents API. It handles authentication, request management, and provides convenient methods for managing chatbots and agents.\n\n## Installation\n\n### From PyPI\n```bash\npip install agents-client\n```\n\n### From Source\n```bash\ngit clone https://github.com/Levangie-Laboratories/agents-client.git\ncd agents-client\npip install -r requirements.txt\n```\n\n## Configuration\nThe client library uses a `config.json` file for API settings. You can either use the default configuration or provide your own:\n\n```python\nfrom agents.client import AgentClient\n\n# Using default configuration\nclient = AgentClient()\n\n# Using custom configuration file\nclient = AgentClient(config_path='path/to/config.json')\n\n# Override configuration programmatically\nclient = AgentClient(base_url='https://api.example.com', api_version='v2')\n```\n\n### Configuration Options\n- `base_url`: API base URL\n- `version`: API version\n- `timeout`: Request timeout in seconds\n- `retry_attempts`: Number of retry attempts\n- `retry_delay`: Delay between retries in seconds\n\nSee `config.json` for all available options.\n\n## Quick Start\n\n### Basic Usage\n```python\nfrom client import ChatbotClient\nfrom client.base_client import ApiError, AuthenticationError\n\n# Initialize client\nbase_url = \"http://localhost:8000\"\nchatbot = ChatbotClient(base_url)\n\n# Set API key\napi_key = \"your-api-key\"\nchatbot.set_api_key(api_key)\n\ntry:\n    # Create a chatbot instance\n    config = {\n        \"temperature\": 0.7,\n        \"max_tokens\": 4000,\n        \"behavior\": \"A helpful assistant that provides clear and concise answers.\"\n    }\n\n    # Create the chatbot\n    response = chatbot.create_chatbot(\n        name=\"BasicChat\",\n        model=\"gpt-4o-mini\",\n        config=config\n    )\n\n    # Store chatbot ID\n    chatbot_id = response.get('id')\n    print(f\"Created chatbot with ID: {chatbot_id}\\n\")\n\n    # Example conversation\n    message = \"Hello! How are you?\"\n    chat_response = chatbot.chat(chatbot_id, message)\n    print(f\"Chatbot: {chat_response.get('response', 'No response')}\\n\")\n\nexcept AuthenticationError as e:\n    print(f\"Authentication error: {str(e)}\")\nexcept ApiError as e:\n    print(f\"API error: {str(e)}\")\n```\n\n### Async Streaming Example\n```python\nfrom agents.client import AgentClient\nimport asyncio\n\nasync def main():\n    # Initialize client with async context manager\n    async with AgentClient(\"http://localhost:8000\") as client:\n        client.set_api_key(\"your-api-key\")\n\n        # Create an agent with API execution mode\n        config = {\n            \"behavior\": \"task-focused\",\n            \"model\": \"gpt-4o-mini\",\n            \"api_mode\": True  # Enable API execution mode\n        }\n        agent = await client.create_agent_with_tools(\n            name=\"FileManager\",\n            model=\"gpt-4o-mini\",\n            tools=FileTools(),  # Your tool class instance\n            config=config\n        )\n\n        # Stream interactions with the agent\n        async for event in client.process_agent_request(agent[\"id\"], \"Update debug mode in config.json\"):\n            if event[\"type\"] == \"function_call\":\n                print(f\"Executing function: {event['data']['function']}\")\n                # Function is automatically executed by the client\n            elif event[\"type\"] == \"execution_status\":\n                print(f\"Execution result: {event['data']}\")\n            elif event[\"type\"] == \"completion\":\n                print(f\"Task completed: {event['data']}\")\n            elif event[\"type\"] == \"error\":\n                print(f\"Error: {event['data']}\")\n\n# Run the async client\nasyncio.run(main())\n```\n\n### State Management Example\n```python\nasync with AgentClient(\"http://localhost:8000\") as client:\n    # State is automatically synchronized\n    async for event in client.process_agent_request(agent_id, message):\n        if event[\"type\"] == \"state_update\":\n            print(f\"Agent state updated: {event['data']}\")\n        elif event[\"type\"] == \"function_call\":\n            # State is preserved across function calls\n            result = await client.execute_function(event[\"data\"])\n            # State is automatically updated with function results\n            await client.submit_result(agent_id, event[\"data\"][\"sequence_id\"], result)\n```\n\n## Chatbot Operations\n\n### Creating a Chatbot\n```python\nfrom client import ChatbotClient\nfrom client.base_client import ApiError, AuthenticationError\n\n# Initialize client\nbase_url = \"http://localhost:8000\"\nchatbot_client = ChatbotClient(base_url)\n\n# Set API key\napi_key = \"your-api-key\"\nchatbot_client.set_api_key(api_key)\n\ntry:\n    # Define configuration\n    config = {\n        \"temperature\": 0.7,\n        \"max_tokens\": 4000,\n        \"behavior\": \"A helpful assistant that provides clear and concise answers.\"\n    }\n\n    # Create the chatbot\n    response = chatbot_client.create_chatbot(\n        name=\"BasicChat\",\n        model=\"gpt-4o-mini\",\n        config=config\n    )\n\n    # Store chatbot ID\n    chatbot_id = response.get('id')\n    print(f\"Created chatbot with ID: {chatbot_id}\\n\")\n\nexcept AuthenticationError as e:\n    print(f\"Authentication error: {str(e)}\")\nexcept ApiError as e:\n    print(f\"API error: {str(e)}\")\n```\n\n### Listing Chatbots\n```python\nchatbots = client.list_chatbots()\nfor bot in chatbots:\n    print(f\"Bot: {bot['name']} (ID: {bot['id']})\")\n```\n\n### Chatbot Interaction\n```python\ntry:\n    # Example conversation\n    print(\"=== Chatbot Interaction ===\\n\")\n    chat_response = chatbot_client.chat(\n        chatbot_id,\n        \"What's the weather like today?\"\n    )\n    print(f\"Chatbot: {chat_response['data']['response']}\\n\")\n\n    # Get chatbot history\n    print(\"=== Chatbot History ===\\n\")\n    history = chatbot_client.get_history(chatbot_id)\n    print(f\"Chat history: {history}\\n\")\n\nexcept ApiError as e:\n    print(f\"API Error: {str(e)}\\n\")\n```\n\n### Updating Chatbots\n```python\nupdated_config = {\n    \"temperature\": 0.8,\n    \"max_tokens\": 1000\n}\n\nupdated_bot = client.update_chatbot(\n    chatbot_id=123,\n    name=\"UpdatedBot\",\n    model=\"gpt-4o-mini\",\n    config=updated_config\n)\n```\n\n### Deleting Chatbots\n```python\nresult = client.delete_chatbot(chatbot_id=123)\n```\n\n## Agent Operations\n\n### Creating an Agent\n```python\nfrom client import AgentClient\nfrom client.base_client import ApiError, AuthenticationError\n\n# Initialize client\nbase_url = \"http://localhost:8000\"\nagent_client = AgentClient(base_url)\n\n# Set API key\napi_key = \"your-api-key\"\nagent_client.set_api_key(api_key)\n\ntry:\n    # Define agent tools and configuration\n    agent_tools = {\n        \"general\": {\n            \"search\": {\n                \"name\": \"search\",\n                \"description\": \"Search for information\",\n                \"parameters\": {}\n            }\n        }\n    }\n\n    agent_config = {\n        \"model\": \"gpt-4o-mini\",\n        \"temperature\": 0.7,\n        \"max_tokens\": 4000\n    }\n\n    # Create the agent\n    agent = agent_client.create_agent(\n        name=\"ResearchAgent\",\n        agent_type=\"research\",\n        behavior=\"A research agent that helps find and analyze information.\",\n        tools=agent_tools,\n        config=agent_config\n    )\n    print(f\"Created agent with ID: {agent['id']}\\n\")\n\nexcept AuthenticationError as e:\n    print(f\"Authentication error: {str(e)}\")\nexcept ApiError as e:\n    print(f\"API error: {str(e)}\")\n```\n\n### Listing Agents\n```python\nagents = client.list_agents()\nfor agent in agents:\n    print(f\"Agent: {agent['name']} (ID: {agent['id']})\")\n```\n\n### Agent Interaction\n```python\ntry:\n    # Demonstrate agent interaction\n    print(\"=== Agent Interaction ===\\n\")\n    agent_response = agent_client.interact(\n        agent['id'],\n        \"Find information about Python programming.\"\n    )\n    print(f\"Agent response: {agent_response['data']['response']}\\n\")\n\n    # Get agent state\n    print(\"=== Agent State ===\\n\")\n    state = agent_client.get_state(agent['id'])\n    print(f\"Agent state: {state}\\n\")\n\n    # Demonstrate error handling\n    print(\"=== Error Handling ===\\n\")\n    try:\n        # Try to interact with non-existent agent\n        agent_client.interact(\"invalid-id\", \"Hello!\")\n    except ApiError as e:\n        print(f\"Handled API error: {str(e)}\\n\")\n\nexcept AuthenticationError as e:\n    print(f\"Authentication error: {str(e)}\")\nexcept ApiError as e:\n    print(f\"API error: {str(e)}\")\nexcept Exception as e:\n    print(f\"Unexpected error: {str(e)}\")\n```\n\nThe new system simplifies command execution by:\n```\n\nKey features of the new command system:\n- Automatic command execution and result handling\n- Built-in command validation and safety checks\n- Simplified tool registration using decorators\n- Automatic result mapping in responses\n- Support for both synchronous and asynchronous operations\n- Comprehensive error handling and reporting\n\n### Supported Commands\nThe client can execute various commands locally:\n\n```python\n# File operations\ncommands = [\n    {\"view_file\": {\"file_path\": \"config.json\"}},\n    {\"smart_replace\": {\n        \"file_path\": \"config.json\",\n        \"old_text\": \"debug: false\",\n        \"new_text\": \"debug: true\"\n    }},\n    {\"create_file\": {\n        \"file_path\": \"new_file.txt\",\n        \"content\": \"Hello, world!\"\n    }}\n]\n\n# Execute commands with safety checks\nresults = client.execute_commands(commands, context={})\n```\n\n### Command Execution Safety\n- File path validation\n- Comprehensive error handling\n- Safe text replacement\n- Automatic retries for network issues\n\n```python\n# Example with error handling\ntry:\n    results = client.execute_commands(commands, context={})\n    if any(r[\"status\"] == \"error\" for r in results[\"command_results\"]):\n        print(\"Some commands failed to execute\")\n        for result in results[\"command_results\"]:\n            if result[\"status\"] == \"error\":\n                print(f\"Error: {result['error']}\")\nexcept Exception as e:\n    print(f\"Execution failed: {str(e)}\")\n```\n\n## Streaming Operations\n\n### Basic Streaming\n```python\nasync with AgentClient(\"http://localhost:8000\") as client:\n    # Stream responses from agent\n    async for event in client.interact_stream(agent_id, message):\n        if event[\"type\"] == \"function_call\":\n            # Handle function execution\n            result = await client.execute_function(event[\"data\"])\n            await client.submit_result(agent_id, event[\"data\"][\"sequence_id\"], result)\n        elif event[\"type\"] == \"completion\":\n            print(f\"Completed: {event['data']}\")\n```\n\n### Concurrent Command Execution\n```python\nasync def process_commands(client, commands, instance_id):\n    # Commands are executed concurrently\n    results = await client.execute_commands(commands, instance_id)\n    return results\n```\n\n## Error Handling\nThe client includes comprehensive error handling with streaming support:\n\n### Streaming Error Handling\n```python\nasync with AgentClient(\"http://localhost:8000\") as client:\n    try:\n        async for event in client.interact_stream(agent_id, message):\n            if event[\"type\"] == \"error\":\n                print(f\"Error occurred: {event['data']}\")\n                break\n            elif event[\"type\"] == \"function_call\":\n                try:\n                    result = await client.execute_function(event[\"data\"])\n                    await client.submit_result(\n                        agent_id,\n                        event[\"data\"][\"sequence_id\"],\n                        result\n                    )\n                except Exception as e:\n                    print(f\"Function execution error: {e}\")\n    except Exception as e:\n        print(f\"Stream error: {e}\")\n```\n\n### Command Execution Errors\n```python\ntry:\n    results = client.execute_commands(commands, context)\n    for result in results['command_results']:\n        if result['status'] == 'error':\n            print(f\"Command {result['command']} failed: {result['error']}\")\nexcept client.CommandExecutionError as e:\n    print(f\"Execution error: {str(e)}\")\n```\n\n### API Errors\n```python\ntry:\n    chatbot = client.get_chatbot(999)\nexcept Exception as e:\n    print(f\"API error: {str(e)}\")\n```\n\n## Best Practices\n1. Always handle API errors in production code\n2. Store API keys securely\n3. Use appropriate timeouts for API calls\n4. Monitor rate limits\n5. Implement proper error handling\n6. Validate file paths before operations\n7. Use context information for better error tracking\n8. Implement proper retry strategies\n\n### Error Handling Best Practices\n```python\n# Comprehensive error handling example\ntry:\n    # Initial interaction\n    response = client.interact_with_agent(agent_id, message)\n    \n    if response['status'] == 'pending_execution':\n        try:\n            # Execute commands with safety checks\n            results = client.execute_commands(\n                response['commands'],\n                response.get('context', {})\n            )\n            \n            # Check individual command results\n            failed_commands = [\n                r for r in results['command_results']\n                if r['status'] == 'error'\n            ]\n            \n            if failed_commands:\n                print(\"Some commands failed:\")\n                for cmd in failed_commands:\n                    print(f\"- {cmd['command']}: {cmd['error']}\")\n            \n            # Continue interaction with results\n            final_response = client.interact_with_agent(\n                agent_id,\n                message,\n                execution_results=results\n            )\n            \n        except client.CommandExecutionError as e:\n            print(f\"Command execution failed: {e}\")\n            # Handle command execution failure\n            \nexcept Exception as e:\n    print(f\"Interaction failed: {e}\")\n    # Handle interaction failure\n```\n\n## Advanced Usage\n\n### Custom Headers\n```python\nclient = AgentClient(\n    base_url=\"http://localhost:8000\",\n    headers={\"Custom-Header\": \"value\"}\n)\n```\n\n### Batch Operations\n```python\n# Create multiple chatbots\nconfigs = [\n    {\"name\": \"Bot1\", \"model\": \"gpt-4o-mini\", \"config\": {...}},\n    {\"name\": \"Bot2\", \"model\": \"gpt-4o-mini\", \"config\": {...}}\n]\n\nchatbots = []\nfor config in configs:\n    bot = client.create_chatbot(**config)\n    chatbots.append(bot)\n```\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A client library for interacting with the Agents API",
    "version": "0.1.23",
    "project_urls": {
        "Homepage": "https://github.com/Levangie-Laboratories/agents-client"
    },
    "split_keywords": [
        "agents",
        " api",
        " client",
        " chatbot",
        " ai"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "69422230b1206aff0538d3da63c4ca7869f7b6dff8f1030fc2a7f6d03d246ea7",
                "md5": "d0b423763ef303431cb4d6e9c186a7a6",
                "sha256": "b35a23484f8c8e9fb8bf3b741bbefca50309bc94252a4c0f8e1ad7f046e9ee10"
            },
            "downloads": -1,
            "filename": "agents_client-0.1.23-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d0b423763ef303431cb4d6e9c186a7a6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 12275,
            "upload_time": "2024-11-20T21:39:47",
            "upload_time_iso_8601": "2024-11-20T21:39:47.377800Z",
            "url": "https://files.pythonhosted.org/packages/69/42/2230b1206aff0538d3da63c4ca7869f7b6dff8f1030fc2a7f6d03d246ea7/agents_client-0.1.23-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8d3f8e4943c8f8e10a7ae4b229d933472c259c682b2f5762de228a644723aa9b",
                "md5": "631a0274149427ca75c5c82cfdc7ba62",
                "sha256": "27dbca3a62e7efcecfe157bdbfb58c89f94c0ed3b7a7fd608638809a01d9a272"
            },
            "downloads": -1,
            "filename": "agents_client-0.1.23.tar.gz",
            "has_sig": false,
            "md5_digest": "631a0274149427ca75c5c82cfdc7ba62",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 11998,
            "upload_time": "2024-11-20T21:39:48",
            "upload_time_iso_8601": "2024-11-20T21:39:48.435984Z",
            "url": "https://files.pythonhosted.org/packages/8d/3f/8e4943c8f8e10a7ae4b229d933472c259c682b2f5762de228a644723aa9b/agents_client-0.1.23.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-20 21:39:48",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Levangie-Laboratories",
    "github_project": "agents-client",
    "github_not_found": true,
    "lcname": "agents-client"
}
        
Elapsed time: 0.46726s