# TypeDialog Agents - Quick Start Guide

## Installation

```bash
cd /Users/Akasha/Development/typedialog
cargo build --release --package typedialog-ag
```text

The binary will be at: `./target/release/typedialog-ag`

## Setup

Configure your API key:

```bash
export ANTHROPIC_API_KEY=sk-ant-your-key-here
```text

## Example Agents

The `agents/` directory contains 9 production-ready example agents:

| Agent | Purpose | Model | Best For |
|-------|---------|-------|----------|
| **greeting** | Friendly greetings | Haiku | Simple interactions |
| **code-reviewer** | Code review | Opus 4.5 | Quality assurance |
| **architect** | Architecture design | Opus 4.5 | System design |
| **summarizer** | Text summarization | Sonnet | Content processing |
| **test-generator** | Generate tests | Sonnet | Test automation |
| **doc-generator** | Documentation | Sonnet | API docs |
| **translator** | Language translation | Sonnet | i18n |
| **debugger** | Debug issues | Opus 4.5 | Troubleshooting |
| **refactor** | Code refactoring | Opus 4.5 | Code quality |

## Usage

### 1. CLI Mode (Interactive)

```bash
# Execute agent with interactive prompts
./target/release/typedialog-ag agents/greeting.agent.mdx
# Will prompt: name (String)
# Enter: Alice
# Response: Warm greeting for Alice

# Execute with predefined inputs
echo '{"name":"Bob"}' | ./target/release/typedialog-ag agents/greeting.agent.mdx --inputs -
```text

### 2. Validate Agents

```bash
# Validate syntax and configuration
./target/release/typedialog-ag validate agents/code-reviewer.agent.mdx

# Output
# ✓ MDX syntax valid
# ✓ Transpilation successful
# ✓ Type checking passed
# ✓ Evaluation successful
#
# Agent Summary
#   Role: senior code reviewer
#   Model: claude-opus-4-5-20251101
#   Max tokens: 4096
#   Temperature: 0.7
```text

### 3. Transpile to Nickel

```bash
# See the generated Nickel configuration
./target/release/typedialog-ag transpile agents/architect.agent.mdx

# Output: Nickel code with full configuration
```text

### 4. HTTP Server Mode

Start the server:

```bash
./target/release/typedialog-ag serve --port 8765
```text

Output:

```text
🚀 Starting TypeAgent HTTP Server

⚙️  Configuration:
   Config: defaults
   Host: 127.0.0.1
   Port: 8765
   Address: http://127.0.0.1:8765

🤖 Available Agents (9):
   • architect
   • code-reviewer
   • debugger
   • doc-generator
   • greeting
   • refactor
   • summarizer
   • test-generator
   • translator

📡 API Endpoints:
   GET  /health                    - Health check
   POST /execute                   - Execute agent from file
   POST /agents/{name}/execute     - Execute agent by name
   POST /transpile                 - Transpile MDX to Nickel
   POST /validate                  - Validate agent file

Press Ctrl+C to stop the server
```text

### 5. HTTP API Examples

#### Execute greeting agent

```bash
curl -X POST http://localhost:8765/agents/greeting/execute \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Alice"
  }'
```text

Response:

```json
{
  "output": "Hello Alice! I hope you're having a wonderful day...",
  "validation_passed": true,
  "validation_errors": [],
  "metadata": {
    "duration_ms": 1234,
    "tokens": 45,
    "model": "claude-3-5-haiku-20241022"
  }
}
```text

#### Code Review

```bash
curl -X POST http://localhost:8765/agents/code-reviewer/execute \
  -H "Content-Type: application/json" \
  -d '{
    "language": "rust",
    "code": "fn add(a: i32, b: i32) -> i32 { a + b }"
  }'
```text

Response includes structured review with sections:

- **Review**
- **Suggestions**
- **Security Considerations**

### Architecture Design

```bash
curl -X POST http://localhost:8765/agents/architect/execute \
  -H "Content-Type: application/json" \
  -d '{
    "feature": "Real-time collaborative document editor",
    "tech_stack": "Rust, WebSockets, PostgreSQL, Redis"
  }'
```text

Response includes:

- **Architecture**
- **Components**
- **Data Flow**
- **Technical Considerations**
- **Implementation Strategy**

### Generate Tests

```bash
curl -X POST http://localhost:8765/agents/test-generator/execute \
  -H "Content-Type: application/json" \
  -d '{
    "language": "python",
    "function_code": "def factorial(n):\n    return 1 if n == 0 else n * factorial(n-1)"
  }'
```text

#### Debug Code

```bash
curl -X POST http://localhost:8765/agents/debugger/execute \
  -H "Content-Type: application/json" \
  -d '{
    "language": "rust",
    "code": "let v = vec![1,2,3]; println!(\"{}\", v[5]);",
    "error": "index out of bounds: the len is 3 but the index is 5"
  }'
```text

Response includes:

- **Root Cause**
- **Fix**
- **Prevention**
- **Testing**

### Refactor Code

```bash
curl -X POST http://localhost:8765/agents/refactor/execute \
  -H "Content-Type: application/json" \
  -d '{
    "language": "typescript",
    "code": "function calc(a,b,op){if(op=='+')return a+b;if(op=='-')return a-b;}",
    "goal": "Improve type safety and readability"
  }'
```text

## Cache Management

TypeDialog automatically caches transpiled Nickel code for faster execution:

```bash
# View cache statistics
./target/release/typedialog-ag cache stats

# Output
# 📊 Cache Statistics
#
# Strategy
#   Both { max_entries: 1000, cache_dir: "/Users/.../.typeagent/cache" }
#
# Entries
#   Memory: 5
#   Disk: 9
#   Total: 14
#
# Location
#   /Users/.../.typeagent/cache
#   Size: 12.34 KB

# Clear cache
./target/release/typedialog-ag cache clear
```text

## Advanced Features

### Optional Inputs

Agents support optional inputs with `?` suffix:

```mdx
@input feature: String
@input tech_stack?: String  # Optional
```text

Usage:

```bash
# With optional input
curl -X POST http://localhost:8765/agents/architect/execute \
  -d '{"feature":"Chat","tech_stack":"Rust"}'

# Without optional input (uses default)
curl -X POST http://localhost:8765/agents/architect/execute \
  -d '{"feature":"Chat"}'
```text

### Conditional Template Logic

Agents use Tera templates (Jinja2-like):

```mdx
{% if tech_stack %}
**Tech Stack**: {{ tech_stack }}
{% else %}
**Tech Stack**: Choose appropriate technologies
{% endif %}
```text

### Output Validation

Agents enforce quality with validation rules:

```mdx
@validate output {
  must_contain: ["## Review", "## Suggestions"],
  format: markdown,
  min_length: 100,
  max_length: 5000
}
```text

## Performance

### First Run (Cold Start)

```text
Parse MDX:       ~5ms
Transpile:      ~10ms
Evaluate:       ~15ms
LLM Execution:  ~2000ms (varies by model)
Total:          ~2030ms
```text

### Subsequent Runs (Cached)

```text
Cache Hit:       ~0ms (instant)
Evaluate:       ~15ms
LLM Execution:  ~2000ms
Total:          ~2015ms (15ms faster)
```text

### Speedup

- **~2x faster** for agent loading
- Cache persists across restarts
- Automatic invalidation on file changes (mtime-based)

## Testing

Run the comprehensive test suite:

```bash
./test-agents.sh
```text

Output:

```text
=== TypeDialog Agent System Tests ===

Test 1: Validating all agents...
  ✓ All 9 agents validated

Test 2: Transpiling agents...
  ✓ Transpilation works

Test 3: Cache functionality...
  ✓ Cache working

Test 4: HTTP Server endpoints...
  ✓ All endpoints operational

=== All tests passed! ===
```text

## Creating Custom Agents

### 1. Create Agent File

```mdx
---
@agent {
  role: your custom role,
  llm: claude-3-5-sonnet-20241022,
  max_tokens: 1000,
  temperature: 0.5
}

@input task: String
@input context?: String

@validate output {
  format: markdown,
  min_length: 50
}
---

Your prompt template here using {{ task }} and {{ context }}.
```text

### 2. Validate

```bash
typedialog-ag validate agents/my-agent.agent.mdx
```text

### 3. Test

```bash
# CLI
typedialog-ag agents/my-agent.agent.mdx

# HTTP
curl -X POST http://localhost:8765/agents/my-agent/execute \
  -d '{"task":"Explain Rust ownership"}'
```text

## Model Selection Guide

| Model | Speed | Cost | Quality | Use Case |
|-------|-------|------|---------|----------|
| **Claude 3.5 Haiku** | ⚡⚡⚡ | $ | Good | Simple tasks, greetings |
| **Claude 3.5 Sonnet** | ⚡⚡ | $$ | Great | Most use cases |
| **Claude Opus 4.5** | ⚡ | $$$ | Best | Complex reasoning |

## Temperature Guide

| Temperature | Behavior | Use Case |
|-------------|----------|----------|
| **0.0-0.3** | Deterministic | Code, debugging, translation |
| **0.4-0.6** | Balanced | Architecture, refactoring |
| **0.7-1.0** | Creative | Greetings, content writing |

## Best Practices

1. **Start with validation**: Always validate before executing
2. **Use appropriate models**: Haiku for simple, Opus for complex
3. **Set validation rules**: Ensure output quality
4. **Cache is automatic**: No manual management needed
5. **Monitor tokens**: Set appropriate max_tokens
6. **Test locally first**: Use CLI before HTTP API

## Troubleshooting

### Agent won't execute

```bash
# Check validation
typedialog-ag validate agents/your-agent.agent.mdx

# Common issues
# - Missing API key: export ANTHROPIC_API_KEY=...
# - Invalid syntax: Check MDX format
# - Wrong model name: Use exact model IDs
```text

### Cache issues

```bash
# Clear cache and retry
typedialog-ag cache clear
```text

### Server won't start

```bash
# Check if port is in use
lsof -i :8765

# Use different port
typedialog-ag serve --port 9000
```text

## Next Steps

- Explore `agents/README.md` for detailed agent documentation
- Create custom agents for your use cases
- Integrate HTTP API into your applications
- Monitor cache performance with `cache stats`

## Support

- Issues: Report at project repository
- Examples: See `agents/` directory
- Tests: Run `./test-agents.sh`
