Installation

Install the Nomos Python SDK using pip:
pip install nomos
Or if you’re using the repository version:
git clone https://github.com/dowhiledev/nomos.git
cd nomos
pip install -e .

Quick Start

Here’s a simple example to get you started:
import asyncio
from nomos.client import AuthConfig, NomosClient

async def main():
    # Create client with JWT authentication
    auth = AuthConfig(auth_type="jwt", token="your-jwt-token")

    async with NomosClient("http://localhost:8000", auth=auth) as client:
        # Check server health
        health = await client.health_check()
        print(f"Server status: {health['status']}")

        # Simple stateless chat
        response = await client.chat.next("Hello! How can you help me?")
        print(f"Agent: {response.response}")

if __name__ == "__main__":
    asyncio.run(main())

Authentication

The SDK supports multiple authentication methods:

No Authentication

client = NomosClient("http://localhost:8000")

JWT Authentication

auth = AuthConfig(auth_type="jwt", token="your-jwt-token")
client = NomosClient("http://localhost:8000", auth=auth)

API Key Authentication

auth = AuthConfig(auth_type="api_key", token="your-api-key")
client = NomosClient("http://localhost:8000", auth=auth)

Usage Patterns

Stateless Chat

Stateless chat allows you to maintain conversation state on the client side:
async with NomosClient("http://localhost:8000", auth=auth) as client:
    # Start a conversation
    response = await client.chat.next("Hello!")
    session_data = response.session_data

    # Continue the conversation
    response = await client.chat.next(
        "Tell me more about your capabilities",
        session_data
    )
    session_data = response.session_data  # Update state

    print(f"Agent: {response.response}")
    print(f"Session ID: {session_data.session_id}")

Session Management

Session management allows the server to handle conversation state:
async with NomosClient("http://localhost:8000", auth=auth) as client:
    # Create a new session
    session = await client.session.init(initiate=True)
    print(f"Session created: {session.session_id}")

    # Send messages to the session
    response = await client.session.next(session.session_id, "Hello!")
    print(f"Agent: {response.message}")

    # Get conversation history
    history = await client.session.get_history(session.session_id)
    print(f"History: {len(history['history'])} messages")

    # End the session
    await client.session.end(session.session_id)

API Reference

NomosClient

Main async client class for interacting with Nomos agents.

Constructor

NomosClient(
    base_url: str = "http://localhost:8000",
    auth: Optional[AuthConfig] = None,
    timeout: float = 30.0,
    headers: Optional[Dict[str, str]] = None
)
Parameters:
  • base_url: URL of the Nomos API server
  • auth: Authentication configuration
  • timeout: Request timeout in seconds
  • headers: Additional headers for requests

Methods

health_check()
Check the health status of the API server.
health = await client.health_check()
# Returns: {"status": "healthy", "timestamp": 1234567890}
chat.next(query, session_data=None)
Send a chat message with optional session data for stateless chat.
response = await client.chat.next("Hello!", session_data)
# Returns: ChatResponse object
session.init(initiate=False)
Create a new session.
session = await client.session.init(initiate=True)
# Returns: SessionResponse object
session.next(session_id, query)
Send a message to an existing session.
response = await client.session.next(session_id, "Hello!")
# Returns: SessionResponse object
session.get_history(session_id)
Get conversation history for a session.
history = await client.session.get_history(session_id)
# Returns: Dict with session_id and history
session.end(session_id)
End a session.
await client.session.end(session_id)
# Returns: Dict with confirmation message

NomosClientSync

Synchronous version of the client for non-async contexts:
from nomos.client import NomosClientSync

with NomosClientSync("http://localhost:8000", auth=auth) as client:
    health = client.health_check()
    response = client.chat.next("Hello!")

AuthConfig

Authentication configuration model.
class AuthConfig(BaseModel):
    auth_type: str = "none"  # "none", "jwt", or "api_key"
    token: Optional[str] = None

Response Models

ChatResponse

class ChatResponse(BaseModel):
    response: dict  # Agent's response
    tool_output: Optional[str]  # Tool execution output
    session_data: State  # Updated session state

SessionResponse

class SessionResponse(BaseModel):
    session_id: str  # Session identifier
    message: dict  # Agent's message

Error Handling

The SDK provides specific exception types for different error scenarios:
from nomos.client import (
    NomosClientError,
    AuthenticationError,
    APIError
)

try:
    async with NomosClient("http://localhost:8000", auth=auth) as client:
        response = await client.chat.next("Hello!")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except APIError as e:
    print(f"API error: {e} (Status: {e.status_code})")
except NomosClientError as e:
    print(f"Client error: {e}")

Advanced Usage

Custom Headers

custom_headers = {
    "X-Client-Version": "1.0.0",
    "X-User-Agent": "MyApp/1.0"
}

client = NomosClient(
    "http://localhost:8000",
    auth=auth,
    headers=custom_headers
)

Timeout Configuration

client = NomosClient(
    "http://localhost:8000",
    timeout=60.0  # 60 seconds
)

Context Manager Usage

Always use the client as a context manager to ensure proper cleanup:
# Async client
async with NomosClient("http://localhost:8000") as client:
    # Your code here
    pass

# Sync client
with NomosClientSync("http://localhost:8000") as client:
    # Your code here
    pass

Examples

Interactive Chat Bot

import asyncio
from nomos.client import AuthConfig, NomosClient

async def interactive_chat():
    auth = AuthConfig(auth_type="jwt", token="your-token")

    async with NomosClient("http://localhost:8000", auth=auth) as client:
        # Start conversation
        response = await client.chat.next("Hello!")
        session_data = response.session_data
        print(f"Agent: {response.response}")

        while True:
            user_input = input("You: ").strip()
            if user_input.lower() in ['quit', 'exit']:
                break

            response = await client.chat.next(user_input, session_data)
            session_data = response.session_data
            print(f"Agent: {response.response}")

if __name__ == "__main__":
    asyncio.run(interactive_chat())

Session-Based Customer Service Bot

import asyncio
from nomos.client import AuthConfig, NomosClient

async def customer_service_session():
    auth = AuthConfig(auth_type="api_key", token="your-api-key")

    async with NomosClient("http://localhost:8000", auth=auth) as client:
        # Create session with greeting
        session = await client.session.init(initiate=True)
        print(f"Session: {session.session_id}")
        print(f"Agent: {session.message}")

        # Handle customer queries
        queries = [
            "I need help with my order",
            "Can you check my account status?",
            "Thank you for your help!"
        ]

        for query in queries:
            print(f"Customer: {query}")
            response = await client.session.next(session.session_id, query)
            print(f"Agent: {response.message}")

        # End session
        await client.session.end(session.session_id)
        print("Session ended")

if __name__ == "__main__":
    asyncio.run(customer_service_session())

Best Practices

  1. Always use context managers to ensure proper resource cleanup
  2. Handle exceptions appropriately for production applications
  3. Use stateless chat for simple interactions, sessions for complex conversations
  4. Set appropriate timeouts based on your use case
  5. Use environment variables for sensitive tokens and configurations
  6. Implement retry logic for production applications
  7. Monitor your API usage and implement rate limiting if needed

Troubleshooting

Common Issues

Connection Errors
# Check if the server is running and accessible
try:
    health = await client.health_check()
    print("Server is accessible")
except NomosClientError as e:
    print(f"Cannot connect to server: {e}")
Authentication Errors
# Verify your token and auth type
auth = AuthConfig(auth_type="jwt", token="your-token")
try:
    response = await client.chat.next("test")
except AuthenticationError:
    print("Check your authentication credentials")
Session Not Found
# Ensure session exists before sending messages
try:
    response = await client.session.next(session_id, "test")
except APIError as e:
    if e.status_code == 404:
        print("Session not found, create a new one")

Contributing

We welcome contributions to the Nomos Python SDK! Please see our contributing guide for more information.

Support

For questions and support: