# ConnectOnion Examples

Copy-paste ready examples following the correct workflow.

## Basic Pattern: Calculator

```bash
co create calculator
cd calculator
```

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

def add(a: float, b: float) -> float:
    """Add two numbers."""
    return a + b

def multiply(a: float, b: float) -> float:
    """Multiply two numbers."""
    return a * b

agent = Agent("calculator", system_prompt="prompt.md", tools=[add, multiply])

if __name__ == "__main__":
    agent.input("What is 5 + 3?")
```

**prompt.md:**
```markdown
You are a calculator. Use the tools to compute math expressions.
```

---

## File Operations: Duplicate Cleaner

```bash
co create file-cleaner
cd file-cleaner
```

**agent.py:**
```python
from connectonion import Agent
from pathlib import Path
import hashlib
import os

def list_files(dir: str) -> list[str]:
    """List all files in directory."""
    return [str(f) for f in Path(dir).iterdir() if f.is_file()]

def get_hash(path: str) -> str:
    """Get MD5 hash of a file."""
    return hashlib.md5(open(path, 'rb').read()).hexdigest()

def delete_file(path: str) -> str:
    """Delete a file."""
    os.remove(path)
    return f"Deleted {path}"

agent = Agent("file-cleaner", system_prompt="prompt.md", tools=[list_files, get_hash, delete_file])

if __name__ == "__main__":
    agent.input("Find and remove duplicate files in /tmp/test")
```

**prompt.md:**
```markdown
You are a file cleaner agent.

Strategy:
1. List all files
2. Hash each file
3. Group by hash
4. Keep first, delete duplicates
```

---

## Web Research Agent

```bash
co create researcher
cd researcher
```

**agent.py:**
```python
from connectonion import Agent
import requests

def search_web(query: str) -> str:
    """Search the web for information."""
    # Replace with actual search API
    return f"Results for: {query}"

def summarize(text: str) -> str:
    """Summarize text to key points."""
    words = text.split()
    return " ".join(words[:50]) + "..." if len(words) > 50 else text

def save_report(filename: str, content: str) -> str:
    """Save research to file."""
    with open(filename, 'w') as f:
        f.write(content)
    return f"Saved to {filename}"

agent = Agent("researcher", system_prompt="prompt.md", tools=[search_web, summarize, save_report])

if __name__ == "__main__":
    agent.input("Research quantum computing and save a summary")
```

**prompt.md:**
```markdown
You are a research assistant.

- Search for information
- Summarize key findings
- Save reports with clear structure
```

---

## Using Built-in Tools

```bash
co create email-bot
cd email-bot
```

**agent.py:**
```python
from connectonion import Agent, Gmail

gmail = Gmail()

agent = Agent("email-bot", system_prompt="prompt.md", tools=[gmail])

if __name__ == "__main__":
    agent.input("Check my unread emails")
```

**prompt.md:**
```markdown
You are an email assistant. Help manage emails professionally.
```

---

## Class-Based Tools (Shared State)

```bash
co create browser-bot --template playwright
```

Or manually:

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

class Browser:
    def __init__(self):
        self.current_url = None

    def navigate(self, url: str) -> str:
        """Go to a URL."""
        self.current_url = url
        return f"Navigated to {url}"

    def screenshot(self) -> str:
        """Take screenshot of current page."""
        return f"Screenshot of {self.current_url}"

    def click(self, selector: str) -> str:
        """Click an element."""
        return f"Clicked {selector}"

browser = Browser()
agent = Agent("browser-bot", system_prompt="prompt.md", tools=[browser])

if __name__ == "__main__":
    agent.input("Go to google.com and take a screenshot")
```

**prompt.md:**
```markdown
You are a browser automation agent. Navigate, click, and capture screenshots.
```

---

## Key Patterns

| Pattern | When to Use |
|---------|-------------|
| Functions | Stateless tools (most cases) |
| Class | Shared state between tools |
| Built-in tools | Gmail, Shell, Memory, WebFetch |

## Tool Design Rules

```python
# GOOD: One action per tool
def list_files(dir: str) -> list[str]: ...
def read_file(path: str) -> str: ...
def delete_file(path: str) -> str: ...

# BAD: Multiple actions in one tool
def file_manager(action: str, path: str) -> str: ...
```

```python
# GOOD: Informative return
def delete_file(path: str) -> str:
    os.remove(path)
    return f"Deleted {path}"

# BAD: Vague return
def delete_file(path: str) -> str:
    os.remove(path)
    return "Done"
```
