# Examples

Real-world examples you can copy and adapt.

## Basic Examples

### Simple Calculator Agent

```python
from connectonion import Agent

def calculate(expression: str) -> str:
    """Perform mathematical calculations."""
    try:
        result = eval(expression)
        return f"Result: {result}"
    except Exception as e:
        return f"Error: {str(e)}"

agent = Agent("calculator", tools=[calculate])
result = agent.input("What is 42 * 17 + 3?")
print(result)
```

### Multi-Tool Assistant

```python
from connectonion import Agent
from datetime import datetime
import json

def get_time() -> str:
    """Get the current time."""
    return datetime.now().strftime("%I:%M %p")

def save_note(title: str, content: str) -> str:
    """Save a note to a file."""
    filename = f"notes/{title.replace(' ', '_')}.txt"
    with open(filename, 'w') as f:
        f.write(content)
    return f"Note saved to {filename}"

def list_notes() -> str:
    """List all saved notes."""
    import os
    if not os.path.exists("notes"):
        return "No notes found"
    notes = os.listdir("notes")
    return "Notes: " + ", ".join(notes)

agent = Agent(
    "assistant",
    tools=[get_time, save_note, list_notes],
    system_prompt="You are a helpful note-taking assistant."
)

# Use multiple tools
agent.input("Save a note titled 'Meeting' with the current time")
agent.input("What notes do I have?")
```

## System Prompt Examples

### Using Direct String Prompts

```python
agent = Agent(
    "teacher",
    system_prompt="""You are an enthusiastic teacher who:
    - Explains concepts clearly with examples
    - Encourages students to ask questions
    - Uses analogies to make complex topics simple""",
    tools=[explain_concept, create_quiz]
)
```

### Loading Prompts from Files

Create a directory structure for your prompts:

```
project/
   prompts/
      customer_support.md
      code_reviewer.txt
      data_analyst.prompt
   main.py
```

**prompts/customer_support.md:**
```markdown
# Customer Support Specialist

You are a senior customer support agent with 10 years of experience.

## Core Values
- **Empathy First**: Always acknowledge the customer's feelings
- **Solution-Oriented**: Focus on resolving issues, not blame
- **Clear Communication**: Use simple, jargon-free language

## Response Framework
1. Acknowledge the issue
2. Express understanding
3. Provide clear next steps
4. Follow up on resolution

## Tone
Professional yet warm and approachable. Use "I" statements to take ownership.
```

**main.py:**
```python
from connectonion import Agent

def check_order(order_id: str) -> str:
    """Check order status."""
    # Implementation here
    return f"Order {order_id} is in transit"

def process_refund(order_id: str, reason: str) -> str:
    """Process a refund request."""
    # Implementation here
    return f"Refund initiated for order {order_id}"

# Load prompt from markdown file
support_agent = Agent(
    "support",
    system_prompt="prompts/customer_support.md",
    tools=[check_order, process_refund]
)

# The agent will use the personality defined in the file
result = support_agent.input("My order #12345 never arrived!")
# Response will be empathetic and solution-focused
```

### Dynamic Prompt Selection

```python
from pathlib import Path
from connectonion import Agent

def get_agent_for_task(task_type: str) -> Agent:
    """Select appropriate agent based on task type."""
    
    prompt_map = {
        "technical": "prompts/technical_expert.md",
        "creative": "prompts/creative_writer.md",
        "analytical": "prompts/data_analyst.md",
        "educational": "prompts/teacher.md"
    }
    
    prompt_file = prompt_map.get(task_type, "prompts/general.md")
    
    return Agent(
        f"{task_type}_agent",
        system_prompt=Path(prompt_file),
        tools=[...]  # Add appropriate tools
    )

# Use different agents for different tasks
tech_agent = get_agent_for_task("technical")
creative_agent = get_agent_for_task("creative")
```

### Environment-Based Prompts

```python
import os
from connectonion import Agent

# Use different prompts for dev/staging/production
environment = os.getenv("ENV", "development")

prompt_file = f"prompts/{environment}/assistant.md"

agent = Agent(
    "assistant",
    system_prompt=prompt_file if os.path.exists(prompt_file) else None,
    tools=[...]
)
```

## Advanced Examples

### Code Review Agent

```python
from connectonion import Agent
import ast

def analyze_code(code: str) -> str:
    """Analyze Python code for issues."""
    try:
        ast.parse(code)
        return "Code is syntactically valid"
    except SyntaxError as e:
        return f"Syntax error: {e}"

def suggest_improvements(code: str) -> str:
    """Suggest code improvements."""
    suggestions = []
    if "print(" in code:
        suggestions.append("Consider using logging instead of print")
    if not code.strip().startswith('"""'):
        suggestions.append("Add module docstring")
    return "\n".join(suggestions) if suggestions else "Code looks good"

# Create prompt file: prompts/code_reviewer.md
"""
# Senior Code Reviewer

You are a senior software engineer with expertise in:
- Python best practices and PEP 8
- Design patterns and SOLID principles
- Performance optimization
- Security considerations

## Review Guidelines
- Be constructive, not critical
- Explain why something should be changed
- Provide code examples when suggesting improvements
- Acknowledge good practices when you see them
"""

code_reviewer = Agent(
    "reviewer",
    system_prompt="prompts/code_reviewer.md",
    tools=[analyze_code, suggest_improvements]
)

# Review code
code = '''
def calculate_total(items):
    total = 0
    for i in items:
        total = total + i.price
    print("Total:", total)
    return total
'''

review = code_reviewer.run(f"Review this code:\n{code}")
```

### Research Assistant

```python
from connectonion import Agent
import requests
from datetime import datetime

def search_web(query: str) -> str:
    """Search the web for information."""
    # Simulated search - replace with actual API
    return f"Search results for '{query}': [relevant information]"

def summarize_text(text: str, max_words: int = 100) -> str:
    """Summarize long text."""
    words = text.split()
    if len(words) <= max_words:
        return text
    return " ".join(words[:max_words]) + "..."

def save_research(topic: str, findings: str) -> str:
    """Save research findings."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"research/{topic}_{timestamp}.md"
    with open(filename, 'w') as f:
        f.write(f"# Research: {topic}\n\n{findings}")
    return f"Research saved to {filename}"

# Prompt file: prompts/researcher.md
"""
You are a thorough research assistant who:
- Gathers information from multiple sources
- Identifies key insights and patterns
- Presents findings in a clear, structured format
- Always cites sources when available
- Distinguishes between facts and speculation
"""

researcher = Agent(
    "researcher",
    system_prompt="prompts/researcher.md",
    tools=[search_web, summarize_text, save_research]
)

# Conduct research
result = researcher.run(
    "Research the latest developments in quantum computing and save a summary"
)
```

### Data Analysis Agent

```python
from connectonion import Agent
import json
import statistics

def load_data(filename: str) -> str:
    """Load data from a JSON file."""
    try:
        with open(filename, 'r') as f:
            data = json.load(f)
        return f"Loaded {len(data)} records"
    except Exception as e:
        return f"Error loading data: {e}"

def calculate_stats(numbers: str) -> str:
    """Calculate statistics for comma-separated numbers."""
    try:
        nums = [float(n.strip()) for n in numbers.split(',')]
        return f"""
        Mean: {statistics.mean(nums):.2f}
        Median: {statistics.median(nums):.2f}
        Std Dev: {statistics.stdev(nums):.2f}
        Min: {min(nums)}, Max: {max(nums)}
        """
    except Exception as e:
        return f"Error: {e}"

def create_report(title: str, content: str) -> str:
    """Create an analysis report."""
    with open(f"reports/{title}.md", 'w') as f:
        f.write(f"# {title}\n\n{content}")
    return f"Report saved: reports/{title}.md"

# Prompt file: prompts/data_analyst.md
"""
You are a data analyst who excels at:
- Finding patterns and insights in data
- Creating clear visualizations (describe them)
- Explaining statistical concepts in simple terms
- Making data-driven recommendations

Always:
- Check data quality first
- Consider multiple interpretations
- Highlight limitations and assumptions
"""

analyst = Agent(
    "data_analyst",
    system_prompt="prompts/data_analyst.md",
    tools=[load_data, calculate_stats, create_report]
)

# Analyze data
result = analyst.run(
    "Calculate statistics for these sales figures: 1200, 1350, 980, 1500, 1275, 1400"
)
```

## Testing Agents

### Unit Testing Tools

```python
import unittest
from connectonion import Agent

def calculator(expr: str) -> str:
    return str(eval(expr))

class TestCalculatorAgent(unittest.TestCase):
    def setUp(self):
        self.agent = Agent("test_calc", tools=[calculator])
    
    def test_simple_math(self):
        result = self.agent.input("Calculate 2 + 2")
        self.assertIn("4", result)
    
    def test_complex_expression(self):
        result = self.agent.input("What is (10 * 5) + 3?")
        self.assertIn("53", result)

if __name__ == "__main__":
    unittest.main()
```

### Testing with Mock LLM

```python
from unittest.mock import Mock
from connectonion import Agent
from connectonion.llm import LLMResponse

def test_agent_with_mock():
    # Create mock LLM
    mock_llm = Mock()
    mock_llm.complete.return_value = LLMResponse(
        content="The answer is 42",
        tool_calls=[],
        raw_response=None
    )
    
    # Create agent with mock
    agent = Agent("test", llm=mock_llm)
    
    # Test
    result = agent.input("What is the meaning of life?")
    assert result == "The answer is 42"
```

## Best Practices

### 1. Organize Prompts by Role

```
prompts/
   support/
      tier1.md
      tier2.md
      escalation.md
   engineering/
      frontend.md
      backend.md
      devops.md
   analysis/
       financial.md
       marketing.md
       product.md
```

### 2. Version Your Prompts

```python
# Track prompt versions
PROMPT_VERSION = "2.1"
prompt_file = f"prompts/v{PROMPT_VERSION}/assistant.md"

agent = Agent("assistant", system_prompt=prompt_file)
```

### 3. Validate Prompts Exist

```python
from pathlib import Path

def create_agent_safely(name: str, prompt_path: str, tools: list):
    """Create agent with prompt validation."""
    path = Path(prompt_path)
    
    if not path.exists():
        print(f"Warning: Prompt file {prompt_path} not found, using default")
        return Agent(name, tools=tools)
    
    if path.stat().st_size == 0:
        print(f"Warning: Prompt file {prompt_path} is empty, using default")
        return Agent(name, tools=tools)
    
    return Agent(name, system_prompt=path, tools=tools)
```

### 4. Template Prompts

```python
def create_specialized_prompt(specialty: str, experience: int) -> str:
    """Generate specialized prompts from templates."""
    template = """
You are a {specialty} expert with {experience} years of experience.

Core competencies:
- Deep knowledge of {specialty} best practices
- Problem-solving in {specialty} domain
- Mentoring junior team members

Approach:
- Be specific and actionable
- Provide examples when helpful
- Consider edge cases
"""
    return template.format(specialty=specialty, experience=experience)

# Use generated prompt
agent = Agent(
    "expert",
    system_prompt=create_specialized_prompt("Python", 10),
    tools=[...]
)
```

## Integration Examples

### Flask Web API

```python
from flask import Flask, request, jsonify
from connectonion import Agent

app = Flask(__name__)

# Initialize agent
agent = Agent(
    "api_assistant",
    system_prompt="prompts/api_assistant.md",
    tools=[...]  # Add your tools
)

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    task = data.get("message")
    
    if not task:
        return jsonify({"error": "No message provided"}), 400
    
    try:
        response = agent.input(task)
        return jsonify({"response": response})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True)
```

### Discord Bot

```python
import discord
from connectonion import Agent

# Initialize bot and agent
bot = discord.Client()
agent = Agent(
    "discord_helper",
    system_prompt="prompts/discord_bot.md",
    tools=[...]  # Add your tools
)

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    
    if bot.user.mentioned_in(message):
        # Process with agent
        response = agent.input(message.content)
        await message.channel.send(response)

bot.run("YOUR_BOT_TOKEN")
```

### CLI Application

```python
import click
from connectonion import Agent
from pathlib import Path

@click.command()
@click.option('--prompt', type=click.Path(exists=True), 
              help='Path to system prompt file')
@click.option('--task', prompt='What do you need?',
              help='Task for the agent')
def main(prompt, task):
    """Interactive CLI agent."""
    
    # Create agent with optional custom prompt
    if prompt:
        agent = Agent("cli_agent", system_prompt=Path(prompt))
    else:
        agent = Agent("cli_agent")
    
    # Process task
    result = agent.input(task)
    click.echo(result)

if __name__ == "__main__":
    main()
```