# Dialetica AI - Python SDK

> The orchestration layer for multi-agent intelligence

Dialetica AI is a Python SDK that enables you to build multi-agent conversational AI applications. Create AI agents, orchestrate conversations between them, and leverage knowledge management for context-aware interactions.

## 🚀 Features

- **Multi-Agent Conversations**: Create contexts with multiple AI agents that can collaborate and debate
- **Agent Management**: Create, manage, and configure AI agents with different personalities and models
- **Knowledge Management**: Store and retrieve knowledge with semantic search capabilities
- **Scheduled Tasks**: Create and manage cron jobs for automated agent interactions
- **Tool Integration**: Configure and use external tools with your agents
- **Usage Tracking**: Monitor API usage and token consumption
- **Type-Safe**: Full Pydantic models with validation and IDE support

## 📦 Installation

```bash
pip install dialetica
```

## 🔑 Getting Started

### 1. Get Your API Key

Sign up at [dialetica.ai](https://dialetica.ai) to get your API key.

### 2. Initialize the Client

```python
from dialetica import Dialetica, AgentRequest, ContextRequest, MessageRequest

# Using environment variable (recommended)
import os
os.environ["DIALETICA_AI_API_KEY"] = "dai_your_api_key_here"
client = Dialetica()

# Or pass API key directly
client = Dialetica(api_key="dai_your_api_key_here")

# Custom base URL for self-hosted instances
client = Dialetica(
    api_key="dai_your_api_key_here",
    base_url="https://your-api-server.com"
)
```

## 📖 Quick Start Examples

### Create an Agent

```python
from dialetica import Dialetica, AgentRequest

client = Dialetica()

# Create a single agent
agent = client.agents.create(
    AgentRequest(
        name="Debate Master",
        description="I engage in thoughtful debate and present balanced arguments.",
        model="openai/gpt-4o-mini",
        temperature=0.7,
        max_tokens=1000,
        instructions=[
            "You are a thoughtful debater",
            "Present both sides of arguments",
            "Be respectful and logical"
        ]
    )
)
print(f"Created agent: {agent.id}")
```

### Create Multiple Agents (Bulk)

```python
# Create multiple agents at once
agents = client.agents.bulk_create([
    AgentRequest(
        name="Einstein",
        description="Theoretical physicist",
        model="anthropic/claude-3-5-sonnet-20241022",
        instructions=["You are Einstein", "Discuss relativity and quantum mechanics"]
    ),
    AgentRequest(
        name="Darwin",
        description="Evolutionary biologist",
        model="google/gemini-2.0-flash-exp:free",
        instructions=["You are Darwin", "Explain evolution and natural selection"]
    )
])
```

### Create a Multi-Agent Context

```python
from dialetica import ContextRequest

# Create a context with multiple agents
context = client.contexts.create(
    ContextRequest(
        name="Scientific Discovery Lab",
        description="Multi-agent scientific research collaboration",
        agents=[agents[0].id, agents[1].id],
        instructions=[
            "Agents collaborate on scientific hypotheses",
            "Share insights and build upon each other's theories"
        ]
    )
)
```

### Run a Conversation

```python
from dialetica import MessageRequest

# Send a message to the context
# The agents will collaborate and respond
messages = [
    MessageRequest(
        role="user",
        sender_name="Student",
        content="How might quantum mechanics and evolution inform our understanding of consciousness?"
    )
]

responses = client.contexts.run(context.id, messages)

# Print all responses
for response in responses:
    print(f"{response.sender_name}: {response.content}")
```

### Stream Responses

```python
# Stream responses in real-time
async for event in client.contexts.stream(context.id, messages):
    if event.type == "token_delta":
        print(event.payload.get("delta"), end="", flush=True)
    elif event.type == "agent_completed":
        print(f"\n\n{event.payload.get('agent_name')} completed")
```

## 🎯 Core Concepts

### Agents

Agents are AI personalities that can participate in conversations. Each agent has:
- **Name & Description**: Identity and purpose
- **Model**: The underlying LLM (OpenAI, Anthropic, Google, etc.)
- **Instructions**: System prompts that define behavior
- **Temperature & Max Tokens**: Generation parameters

### Contexts

Contexts are conversation environments that can contain multiple agents. They enable:
- **Multi-agent collaboration**: Agents can debate, discuss, and build on each other's ideas
- **Knowledge integration**: Attach knowledge bases for context-aware responses
- **Orchestration**: Control which agent speaks when

### Knowledge

Store information that agents can access via semantic search:
- **Context-level knowledge**: Available to all agents in a context
- **Agent-level knowledge**: Specific to individual agents
- **Semantic search**: Find relevant information automatically

## 📚 API Reference

### Agents

```python
# Create
agent = client.agents.create(AgentRequest(...))

# Bulk create
agents = client.agents.bulk_create([AgentRequest(...), ...])

# List
all_agents = client.agents.list()

# Get
agent = client.agents.get(agent_id)

# Update
updated = client.agents.update(agent_id, AgentRequest(...))

# Delete
client.agents.delete(agent_id)
```

### Contexts

```python
# Create
context = client.contexts.create(ContextRequest(...))

# Bulk create
contexts = client.contexts.bulk_create([ContextRequest(...), ...])

# List
all_contexts = client.contexts.list()

# Get
context = client.contexts.get(context_id)

# Update
updated = client.contexts.update(context_id, ContextRequest(...))

# Delete
client.contexts.delete(context_id)

# Run (send messages)
responses = client.contexts.run(context_id, [MessageRequest(...)])

# Stream responses
async for event in client.contexts.stream(context_id, [MessageRequest(...)]):
    ...

# Get history
history = client.contexts.get_history(context_id)
```

### Knowledge

```python
# Create
knowledge = client.knowledge.create(KnowledgeRequest(...))

# List
all_knowledge = client.knowledge.list()

# Get
knowledge = client.knowledge.get(knowledge_id)

# Update
updated = client.knowledge.update(knowledge_id, KnowledgeRequest(...))

# Delete
client.knowledge.delete(knowledge_id)

# Semantic search
results = client.knowledge.search(context_id, query="your search query")
```

### Scheduled Tasks (Crons)

```python
# Create
cron = client.crons.create(CronRequest(...))

# List
all_crons = client.crons.list()

# Get
cron = client.crons.get(cron_id)

# Update
updated = client.crons.update(cron_id, CronRequest(...))

# Delete
client.crons.delete(cron_id)
```

### Tool Configurations

```python
# Create
tool = client.tools.create(ToolConfigRequest(...))

# List
all_tools = client.tools.list()

# Get
tool = client.tools.get(tool_id)

# Update
updated = client.tools.update(tool_id, ToolConfigRequest(...))

# Delete
client.tools.delete(tool_id)
```

### Usage Tracking

```python
# Get summary
summary = client.usage.get_summary()

# Get detailed usage
details = client.usage.get_detailed(
    start_date="2025-01-01",
    end_date="2025-01-31",
    model="openai/gpt-4o"
)
```

### Available Models

```python
# List all available models
models = client.models.list()

for model in models:
    print(f"{model['label']} ({model['tier']}): {model['model']}")
```

## 🔒 Security Best Practices

1. **Never commit API keys** to version control
2. **Use environment variables** for API keys in production
3. **Rotate API keys** regularly
4. **Use different keys** for development and production

```python
# ✅ Good: Use environment variables
import os
client = Dialetica(api_key=os.getenv("DIALETICA_AI_API_KEY"))

# ❌ Bad: Hardcode API keys
client = Dialetica(api_key="dai_abc123...")  # Don't do this!
```

## 🌐 Supported Models

Dialetica AI supports models from multiple providers:

- **OpenAI**: `gpt-4o`, `gpt-4o-mini`, `gpt-4-turbo`, etc.
- **Anthropic**: `claude-3-5-sonnet-20241022`, `claude-3-haiku-20240307`, etc.
- **Google**: `gemini-2.0-flash-exp:free`, `gemini-pro`, etc.
- **And more**: Check `client.models.list()` for all available models

## 📝 Example: Multi-Agent Debate

```python
from dialetica import Dialetica, AgentRequest, ContextRequest, MessageRequest

client = Dialetica()

# Create debaters
pro_agent = client.agents.create(
    AgentRequest(
        name="Proponent",
        description="Argues in favor of renewable energy",
        model="openai/gpt-4o-mini",
        instructions=["You strongly support renewable energy", "Present compelling arguments"]
    )
)

con_agent = client.agents.create(
    AgentRequest(
        name="Skeptic",
        description="Questions renewable energy feasibility",
        model="anthropic/claude-3-haiku-20240307",
        instructions=["You question renewable energy", "Present counter-arguments"]
    )
)

# Create debate context
debate = client.contexts.create(
    ContextRequest(
        name="Energy Debate",
        agents=[pro_agent.id, con_agent.id],
        instructions=["Engage in respectful debate", "Build on each other's points"]
    )
)

# Start the debate
responses = client.contexts.run(
    debate.id,
    [MessageRequest(
        role="user",
        sender_name="Moderator",
        content="Should we transition to 100% renewable energy by 2030?"
    )]
)

# Print the debate
for response in responses:
    print(f"\n{response.sender_name}: {response.content}")
```

## 🔗 Resources

- **Documentation**: [https://dialetica.ai/docs](https://dialetica.ai/docs)
- **Website**: [https://dialetica.ai](https://dialetica.ai)
- **Support**: support@dialetica-ai.com

## 📄 License

MIT License - see LICENSE file for details

## 🤝 Contributing

Contributions are welcome! Please see our contributing guidelines.

---

**Made with ❤️ by the Dialetica AI team**

