Skip to main content

AIRUN Python SDK

Python SDK for Hamonize AIRUN API - AI-powered document generation and management platform.

Features

  • Chat API: AI conversations with streaming support
  • Code Generation: Generate code with AI
  • Code Execution: Execute Python code safely
  • RAG (Retrieval-Augmented Generation): Document search and upload
  • Web Search: Integrated web search capabilities
  • Report Generation: Automated document creation
  • Session Management: Manage conversation sessions
  • User Management: System prompts and user settings

Installation

pip install airun-sdk

Quick Start

from airun import AIRUN

# Initialize client
client = AIRUN(
    server_url="http://localhost:5500",
    api_key="your-api-key-here"
)

# Simple chat - uses default model and provider
response = client.chat.create_sync(
    prompt="Hello, what can you do?"
)

print(response["data"]["response"])

Usage Examples

from airun import AIRUN

client = AIRUN(
    server_url="http://localhost:5500",
    api_key="your-api-key"
)

# Chat with web search enabled
response = client.chat.create_sync(
    prompt="What are the latest AI trends?",
    options={"web": True}
)

print(response["data"]["response"])
# Chat with RAG search enabled
response = client.chat.create_sync(
    prompt="Search my documents and summarize",
    options={"rag": True}
)

print(response["data"]["response"])

WebSocket Streaming

from airun import AIRUN

client = AIRUN(
    server_url="http://localhost:5500",
    api_key="your-api-key"
)

# Method 1: Callback-based streaming
def on_content(chunk):
    print(chunk, end='', flush=True)

def on_complete(data):
    print(f"\nSession: {data.get('sessionId')}")

client.chat.stream_chat(
    prompt="Tell me a short story",
    on_content=on_content,
    on_complete=on_complete
)
# Method 2: Generator-based streaming
for message in client.chat.stream_chat_generator("Explain AI"):
    if message['type'] == 'content':
        print(message['data'], end='', flush=True)
    elif message['type'] == 'complete':
        print(f"\nSession: {message['data'].get('sessionId')}")
# Method 3: Async streaming
import asyncio

async def stream_example():
    response = await client.chat.stream_chat_async(
        prompt="Write a haiku about coding",
        on_content=lambda chunk: print(chunk, end='', flush=True)
    )
    print(f"\nSession: {response['sessionId']}")

asyncio.run(stream_example())

More Examples

# Generate code
response = client.code.create_sync(
    prompt="Create a function to calculate fibonacci numbers",
    options={
        "language": "python",
        "include_docs": True,
        "include_tests": True
    }
)

print(response["data"]["code"])

Code Execution

# Execute Python code
code = """
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(f"fibonacci(10) = {fibonacci(10)}")
"""

response = client.code.execute(python_code=code)
print(response["data"]["output"])

RAG Document Upload

# Upload a document to RAG
response = client.rag.upload(
    file_path="/path/to/document.pdf",
    file_type="document",
    user_id="user123"
)

print(f"Uploaded: {response.get('imageUrl', 'Success')}")

# Search documents
response = client.rag.search_sync(
    query="machine learning algorithms",
    rag_search_scope="personal"
)

for result in response["data"].get("results", []):
    print(f"- {result.get('title', 'N/A')}: {result.get('snippet', '')[:100]}")
# Search the web
response = client.web.search_sync(
    query="Python 3.12 new features",
    engine="auto",
    max_results=5
)

for result in response["data"]:
    print(f"Title: {result.get('title')}")
    print(f"URL: {result.get('link')}")
    print(f"Snippet: {result.get('snippet', '')[:100]}\n")

Report Generation

# Generate a report
response = client.report.create(
    prompt="Generate a market analysis report for AI industry",
    format="pdf",
    template="simple"
)

job_id = response["data"]["job_id"]

# Check job status
status = client.report.get_status(job_id)
print(f"Status: {status['data']['status']}")

# Get report templates
templates = client.report.get_simple_templates()
for template in templates["data"]:
    print(f"- {template['name']}")

Session Management

# Create a new session
session = client.sessions.create(
    type="chat",
    title="My Conversation"
)

session_id = session["data"]["sessionId"]

# List all sessions
sessions = client.sessions.get_sessions()
for s in sessions["data"]["sessions"]:
    print(f"{s['sessionId']}: {s['title']}")

# Update session
client.sessions.update_session(
    session_id,
    title="Updated Title"
)

# Delete session
client.sessions.delete_session(session_id)

User System Prompt

# Get user's system prompt
prompt = client.user.get_system_prompt()

# Update system prompt
client.user.update_system_prompt(
    content="You are a helpful AI assistant specialized in Python programming."
)

Configuration

The SDK can be configured via environment variables:

export AIRUN_SERVER_URL="http://localhost:5500"
export AIRUN_API_KEY="your-api-key"

Then initialize without parameters:

client = AIRUN()

Or using a .env file:

AIRUN_SERVER_URL=http://localhost:5500
AIRUN_API_KEY=your-api-key

API Reference

Client Methods

Method Description
chat.create_sync() Synchronous chat completion
chat.stream_chat() Stream chat with callbacks
chat.stream_chat_generator() Generator-based streaming
chat.stream_chat_async() Async streaming
code.create_sync() Generate code
code.execute() Execute Python code
rag.search_sync() Search RAG documents
rag.upload() Upload document to RAG
rag.add() Add documents by path/URL
rag.delete() Delete RAG documents
web.search_sync() Web search
report.create() Generate report
report.get_status() Get report job status
report.download_report() Download report file
sessions.create() Create session
sessions.get_sessions() List sessions
user.get_system_prompt() Get system prompt
user.update_system_prompt() Update system prompt
validate_key() Validate API key
get_status() Get API status

ChatOptions Parameters

Parameter Type Default Description
model str - Model name
provider str - AI provider (openai, anthropic, etc.)
temperature float 0.0 Sampling temperature (0-2)
max_tokens int 8000 Maximum tokens to generate
rag bool false Enable RAG search
web bool false Enable web search
rag_search_scope str "personal" RAG search scope (personal/shared/all)
session_id str - Session ID for continuity
history list - Conversation history
reasoning_level str "medium" Reasoning depth (low/medium/high)
image str - Image path for vision analysis

Error Handling

from airun import AIRUN
from airun.exceptions import (
    APIError,
    AuthenticationError,
    RateLimitError,
    ValidationError,
    NetworkError
)

client = AIRUN(api_key="your-api-key")

try:
    response = client.chat.create_sync("Hello!")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ValidationError as e:
    print(f"Validation error: {e}")
except APIError as e:
    print(f"API error: {e}")
except NetworkError as e:
    print(f"Network error: {e}")

Requirements

  • Python 3.8+
  • requests >= 2.28.0
  • python-dotenv >= 1.0.0
  • pydantic >= 2.0.0
  • websocket-client >= 1.6.0
  • websockets >= 12.0

Development

# Clone repository
git clone https://github.com/hamonikr/airun.git
cd airun/sdk/python-sdk

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black src tests
isort src tests

# Type checking
mypy src

License

MIT License - see LICENSE file for details.

Metadata

Release files for airun-sdk 1.0.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for airun-sdk 1.0.6
File Size Uploaded Provenance Actions
airun_sdk-1.0.6.tar.gz 21.9 kB Without provenance Details for airun_sdk-1.0.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for airun-sdk 1.0.6
File Interpreter ABI Platform Actions
airun_sdk-1.0.6-py3-none-any.whl Python 3 none any Details for airun_sdk-1.0.6-py3-none-any.whl

Total release size: 44.8 kB

Release files / airun_sdk-1.0.6.tar.gz

Download URL airun_sdk-1.0.6.tar.gz
Size 21.9 kB
Tags Source
SHA-256 checksum
How to use checksums
d0382f64dc8097db2b98ae3db18f2b4b4d1215fef7847cdd30ec941a89d08e6b
BLAKE2b-256 checksum
How to use checksums
4449e53097e2ced1bcc976a110701da9f42a3d110547c2f2b9a47aa0bd065a14
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Release files / airun_sdk-1.0.6-py3-none-any.whl

Download URL airun_sdk-1.0.6-py3-none-any.whl
Size 22.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a8a670360354c5d8228ee4ce1adc49a95ab4693c776b0d76cb802c30104d6beb
BLAKE2b-256 checksum
How to use checksums
c05f77a3970d80f59ce7a7495c1d1c9f47e4dccfcc8d740d30bb6a02f5e12efc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Security for airun-sdk 1.0.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page