# Agent Message Examples

This document provides comprehensive examples of agent user message setups, in-context messages, and tool call/response patterns in XML format for the contaigents system.

## Overview

The contaigents system uses a hybrid message architecture that supports both conversation-capable providers (OpenAI, Anthropic, DeepSeek, OpenRouter) and simple prompt-based providers (HuggingFace, Ollama, Replicate).

## Message Architecture Types

### 1. Conversation-Capable Providers
- Support proper conversation arrays with role separation
- Tool responses are internal user messages
- Maintain conversation flow and context

### 2. Simple Prompt Providers  
- Use concatenated prompt strings
- Tool responses are visible context
- Single prompt execution model

## Agent User Message Setup

### Basic Agent Setup

```typescript
// Agent configuration
const agentConfig = {
  name: "ContentWriter",
  description: "AI assistant specialized in content creation and editing",
  systemPrompt: `You are a professional content writer and editor with access to file operations.
  
Your capabilities include:
- Reading and analyzing existing content
- Creating new articles, documentation, and marketing copy
- Editing and improving existing content
- Researching topics and gathering information
- Maintaining consistent tone and style

Always be helpful, accurate, and maintain professional writing standards.`,
  
  tools: ["read_file", "write_file", "command_execution"],
  provider: "OpenAI",
  model: "gpt-4"
};

// Session creation
const session = chatService.createSession(agentConfig);
```

### Advanced Agent with Memory

```typescript
const advancedAgentConfig = {
  name: "ProjectManager",
  description: "AI project manager with context awareness and memory",
  systemPrompt: `You are an experienced project manager with access to file operations and command execution.

Your responsibilities include:
- Analyzing project structure and requirements
- Creating and updating project documentation
- Managing task lists and timelines
- Coordinating development workflows
- Maintaining project standards and best practices

You have access to shared memory for maintaining context across conversations.
Use the .memory directory for storing project insights, decisions, and ongoing context.`,

  tools: ["read_file", "write_file", "command_execution"],
  provider: "Anthropic",
  model: "claude-3-sonnet",
  memoryEnabled: true,
  memoryPath: ".memory/project_context"
};
```

## In-Context Message Setup

### Simplified In-Context Messages (Recommended)

The system uses a simplified approach where:
- **Conversation providers**: Use proper message arrays with role separation
- **Simple providers**: Use concatenated prompt strings
- **Tool responses**: Are handled internally and don't clutter the UI

```typescript
// ✅ Simplified conversation structure for conversation-capable providers
const conversationMessages = [
  {
    role: "system",
    content: systemPrompt + fileTreeContext + toolInstructions
  },
  {
    role: "user", 
    content: "Can you analyze the project structure?"
  },
  {
    role: "assistant",
    content: "I'll analyze the project structure for you.\n\n<tool_call name=\"read_file\" id=\"1\">\n  <file_path>package.json</file_path>\n</tool_call>"
  },
  {
    role: "user",
    content: "<tool_response id=\"1\">...</tool_response>",
    metadata: { internal: true, isToolResponse: true }
  },
  {
    role: "assistant", 
    content: "Based on the package.json analysis..."
  }
];
```

### Message Metadata Structure

```typescript
interface ConversationMessage {
  id: string;
  role: 'system' | 'user' | 'assistant';
  content: string;
  timestamp: number;
  metadata?: {
    isToolResponse?: boolean;    // Marks tool response messages
    toolCallId?: string;        // Links to specific tool call
    provider?: string;          // Provider that generated this message
    internal?: boolean;         // Hide from UI (for tool responses)
    turnCount?: number;         // Track conversation turns
    maxTurns?: number;          // Maximum turns for this conversation
  };
}
```

## Tool Call Examples in XML Format

### Basic File Operations

#### Reading Files
```xml
<tool_call name="read_file" id="1">
  <file_path>README.md</file_path>
</tool_call>

<tool_call name="read_file" id="2">
  <file_path>src/components/Header.tsx</file_path>
  <encoding>utf-8</encoding>
</tool_call>
```

#### Writing Files
```xml
<!-- Create new file -->
<tool_call name="write_file" id="3">
  <operation_type>create</operation_type>
  <file_path>docs/api-guide.md</file_path>
  <content><![CDATA[
# API Guide

This guide covers the main API endpoints and usage patterns.

## Authentication
All API requests require authentication via API key.

## Endpoints
- GET /api/users - List users
- POST /api/users - Create user
]]></content>
</tool_call>

<!-- Update existing file -->
<tool_call name="write_file" id="4">
  <operation_type>update</operation_type>
  <file_path>package.json</file_path>
  <content><![CDATA[{
  "name": "contaigents",
  "version": "1.2.0",
  "description": "AI-powered content generation platform",
  "main": "dist/index.js",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "ts-node src/index.ts",
    "test": "jest"
  }
}]]></content>
</tool_call>

<!-- Partial file update -->
<tool_call name="write_file" id="5">
  <operation_type>partial</operation_type>
  <file_path>src/config.ts</file_path>
  <start_line>15</start_line>
  <end_line>20</end_line>
  <content><![CDATA[export const API_CONFIG = {
  baseUrl: 'https://api.contaigents.com',
  timeout: 30000,
  retries: 3
};]]></content>
</tool_call>
```

### Command Execution

```xml
<!-- Install dependencies -->
<tool_call name="command_execution" id="6">
  <command>npm install --save express cors helmet</command>
  <working_directory>.</working_directory>
  <timeout>60</timeout>
  <capture_stderr>true</capture_stderr>
</tool_call>

<!-- Run tests -->
<tool_call name="command_execution" id="7">
  <command>npm test -- --coverage</command>
  <working_directory>.</working_directory>
  <timeout>120</timeout>
  <capture_stderr>true</capture_stderr>
</tool_call>

<!-- Build project -->
<tool_call name="command_execution" id="8">
  <command>npm run build</command>
  <working_directory>.</working_directory>
  <timeout>180</timeout>
  <capture_stderr>true</capture_stderr>
</tool_call>
```

### Complex Multi-Step Operations

```xml
<!-- Research and create comprehensive documentation -->
<tool_call name="read_file" id="9">
  <file_path>src/index.ts</file_path>
</tool_call>

<tool_call name="read_file" id="10">
  <file_path>src/services/chatService.ts</file_path>
</tool_call>

<tool_call name="read_file" id="11">
  <file_path>src/services/tools/ToolManager.ts</file_path>
</tool_call>

<tool_call name="write_file" id="12">
  <operation_type>create</operation_type>
  <file_path>docs/architecture-overview.md</file_path>
  <content><![CDATA[
# Architecture Overview

## Core Components

### ChatService
The main service that orchestrates conversations between users and AI providers.

Key features:
- Multi-provider support (OpenAI, Anthropic, etc.)
- Tool integration for file operations
- Session management and persistence
- Conversation flow control

### ToolManager
Manages the execution of tools that extend AI capabilities.

Available tools:
- File operations (read, write, create)
- Command execution
- Project structure analysis

### Message Architecture
Hybrid system supporting both conversation arrays and prompt strings.

## Usage Patterns

### Basic Chat
```typescript
const session = chatService.createSession({
  systemPrompt: "You are a helpful assistant"
});

const response = await chatService.sendMessage(
  session.id,
  "Hello, how can you help me?"
);
```

### Tool-Enhanced Conversations
Agents can read files, execute commands, and maintain project context.
]]></content>
</tool_call>
```

## Tool Response Examples in XML Format

### Successful File Read Response

```xml
<tool_response id="1">
  <tool_call name="read_file">
    <file_path>README.md</file_path>
  </tool_call>
  <result>
    <content>
# Contaigents

Open-source platform for creating and managing content using locally running AI agents.

## Features
- Multi-provider AI support
- File operations and project awareness
- Extensible tool architecture
- Local execution for privacy

## Installation
```bash
npm install -g contaigents
```

## Usage
```bash
contaigents chat "Help me write documentation"
```
    </content>
  </result>
</tool_response>
```

### Successful File Write Response

```xml
<tool_response id="3">
  <tool_call name="write_file">
    <operation_type>create</operation_type>
    <file_path>docs/api-guide.md</file_path>
    <content>...</content>
  </tool_call>
  <result>
    <message>File created successfully: docs/api-guide.md</message>
    <data>
      <file_path>docs/api-guide.md</file_path>
      <operation>create</operation>
      <size_bytes>1247</size_bytes>
      <backup_created>false</backup_created>
    </data>
  </result>
</tool_response>
```

### Successful Command Execution Response

```xml
<tool_response id="6">
  <tool_call name="command_execution">
    <command>npm install --save express cors helmet</command>
    <working_directory>.</working_directory>
    <timeout>60</timeout>
    <capture_stderr>true</capture_stderr>
  </tool_call>
  <result>
    <data>
      <stdout>
added 245 packages, and audited 246 packages in 12s

58 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
      </stdout>
      <stderr></stderr>
      <exitCode>0</exitCode>
      <command>npm install --save express cors helmet</command>
      <workingDirectory>/Users/user/projects/contaigents</workingDirectory>
      <executionTime>12.4</executionTime>
    </data>
    <message>Command executed successfully (exit code: 0)</message>
  </result>
</tool_response>
```

### Error Response Examples

#### File Not Found Error
```xml
<tool_response id="2">
  <tool_call name="read_file">
    <file_path>nonexistent.md</file_path>
  </tool_call>
  <result>
    <error>File not found: nonexistent.md</error>
  </result>
</tool_response>
```

#### Command Execution Error
```xml
<tool_response id="7">
  <tool_call name="command_execution">
    <command>npm run invalid-script</command>
    <working_directory>.</working_directory>
    <timeout>30</timeout>
    <capture_stderr>true</capture_stderr>
  </tool_call>
  <result>
    <error>Command execution failed</error>
    <data>
      <stdout></stdout>
      <stderr>npm ERR! Missing script: "invalid-script"</stderr>
      <exitCode>1</exitCode>
      <command>npm run invalid-script</command>
      <workingDirectory>/Users/user/projects/contaigents</workingDirectory>
      <executionTime>0.3</executionTime>
    </data>
  </result>
</tool_response>
```

#### Permission Error
```xml
<tool_response id="8">
  <tool_call name="write_file">
    <operation_type>create</operation_type>
    <file_path>/etc/restricted-file.txt</file_path>
    <content>test content</content>
  </tool_call>
  <result>
    <error>Permission denied: Cannot write to /etc/restricted-file.txt</error>
  </result>
</tool_response>
```

## Complete Conversation Examples

### Content Creation Workflow

**User Message:**
```
"Create a blog post about the benefits of AI-powered content creation. Research our existing content first, then write a comprehensive article."
```

**Agent Response with Tool Calls:**
```
I'll help you create a comprehensive blog post about AI-powered content creation. Let me first research your existing content to understand your style and avoid duplication.

<tool_call name="read_file" id="1">
  <file_path>content/blog/existing-posts.md</file_path>
</tool_call>

<tool_call name="read_file" id="2">
  <file_path>content/style-guide.md</file_path>
</tool_call>

<tool_call name="command_execution" id="3">
  <command>find content/blog -name "*.md" -type f | head -10</command>
  <working_directory>.</working_directory>
  <timeout>10</timeout>
  <capture_stderr>true</capture_stderr>
</tool_call>
```

**Tool Responses:**
```xml
<tool_response id="1">
  <tool_call name="read_file">
    <file_path>content/blog/existing-posts.md</file_path>
  </tool_call>
  <result>
    <content>
# Existing Blog Posts

## Published Articles
- "The Future of Content Marketing" (2024-01-15)
- "Automation in Creative Workflows" (2024-02-03)
- "Building Better User Experiences" (2024-02-20)

## Style Notes
- Conversational but professional tone
- Include practical examples
- 1500-2000 word target length
- Use subheadings for readability
    </content>
  </result>
</tool_response>

<tool_response id="2">
  <tool_call name="read_file">
    <file_path>content/style-guide.md</file_path>
  </tool_call>
  <result>
    <content>
# Content Style Guide

## Voice and Tone
- Professional yet approachable
- Focus on practical value
- Use active voice
- Include real-world examples

## Structure
- Compelling headline
- Brief introduction with hook
- 3-5 main sections with subheadings
- Conclusion with actionable takeaways
- Call-to-action

## SEO Guidelines
- Target keyword density: 1-2%
- Include meta description
- Use semantic HTML structure
    </content>
  </result>
</tool_response>

<tool_response id="3">
  <tool_call name="command_execution">
    <command>find content/blog -name "*.md" -type f | head -10</command>
    <working_directory>.</working_directory>
    <timeout>10</timeout>
    <capture_stderr>true</capture_stderr>
  </tool_call>
  <result>
    <data>
      <stdout>
content/blog/future-content-marketing.md
content/blog/automation-creative-workflows.md
content/blog/building-better-ux.md
content/blog/ai-tools-comparison.md
content/blog/content-strategy-2024.md
      </stdout>
      <stderr></stderr>
      <exitCode>0</exitCode>
      <command>find content/blog -name "*.md" -type f | head -10</command>
      <workingDirectory>/Users/user/projects/contaigents</workingDirectory>
      <executionTime>0.1</executionTime>
    </data>
    <message>Command executed successfully (exit code: 0)</message>
  </result>
</tool_response>
```

**Follow-up Agent Response:**
```
Perfect! I've analyzed your existing content and style guide. Now I'll create a comprehensive blog post about AI-powered content creation that aligns with your established voice and complements your existing articles.

<tool_call name="write_file" id="4">
  <operation_type>create</operation_type>
  <file_path>content/blog/ai-powered-content-creation-benefits.md</file_path>
  <content><![CDATA[
---
title: "Revolutionizing Content Creation: The Transformative Benefits of AI-Powered Writing"
meta_description: "Discover how AI-powered content creation is transforming businesses with faster production, consistent quality, and enhanced creativity. Learn practical implementation strategies."
date: 2024-03-15
author: "Content Team"
tags: ["AI", "Content Creation", "Productivity", "Marketing"]
---

# Revolutionizing Content Creation: The Transformative Benefits of AI-Powered Writing

In today's fast-paced digital landscape, content is king—but creating high-quality, engaging content consistently can feel like an uphill battle. Enter AI-powered content creation, a game-changing technology that's reshaping how businesses approach their content strategies.

## The Content Creation Challenge

Before diving into AI's benefits, let's acknowledge the reality most content creators face:

- **Time constraints**: Quality content takes time, but deadlines are relentless
- **Consistency pressure**: Maintaining voice and quality across large volumes
- **Resource limitations**: Small teams handling massive content demands
- **Creative blocks**: Even the best writers face inspiration droughts

These challenges have led forward-thinking organizations to explore AI as a strategic solution.

## Key Benefits of AI-Powered Content Creation

### 1. Accelerated Production Speed

AI content tools can generate first drafts in minutes rather than hours. This doesn't replace human creativity—it amplifies it by handling the heavy lifting of initial content structure and research.

**Real-world impact**: A marketing team that previously produced 4 blog posts per week now creates 12, with the same quality standards and team size.

### 2. Enhanced Consistency and Brand Voice

AI systems can be trained on your existing content to maintain consistent tone, style, and messaging across all materials. This ensures brand coherence whether you're creating social media posts, email campaigns, or long-form articles.

### 3. Data-Driven Content Optimization

Modern AI tools analyze performance metrics, audience engagement patterns, and SEO requirements to suggest content improvements in real-time. This data-driven approach removes guesswork from content strategy.

### 4. Multilingual Content Scaling

AI-powered translation and localization tools enable businesses to create content for global audiences without proportionally scaling their content teams.

### 5. Creative Inspiration and Ideation

AI excels at generating multiple angles, headlines, and approaches for any topic, helping human creators overcome creative blocks and explore new perspectives.

## Practical Implementation Strategies

### Start Small and Scale Gradually

Begin with specific use cases like:
- Social media post generation
- Email subject line optimization
- Blog post outlines and research
- Product description creation

### Maintain Human Oversight

AI should augment human creativity, not replace it. Establish review processes that ensure:
- Factual accuracy
- Brand alignment
- Emotional resonance
- Ethical considerations

### Choose the Right Tools

Evaluate AI content tools based on:
- Integration capabilities with existing workflows
- Customization options for brand voice
- Quality of output for your specific content types
- Pricing structure and scalability

## Measuring Success

Track these key metrics to evaluate your AI content strategy:

- **Production velocity**: Content pieces created per time period
- **Quality consistency**: Brand voice adherence scores
- **Engagement rates**: Audience interaction with AI-assisted content
- **Cost efficiency**: Content creation cost per piece
- **Team satisfaction**: Creator feedback on workflow improvements

## Looking Ahead: The Future of AI Content Creation

As AI technology continues evolving, we can expect:

- More sophisticated understanding of context and nuance
- Better integration with content management systems
- Enhanced personalization capabilities
- Improved collaboration between AI and human creators

## Conclusion: Embracing the AI Content Revolution

AI-powered content creation isn't about replacing human creativity—it's about amplifying it. By handling routine tasks, providing data-driven insights, and offering creative inspiration, AI enables content creators to focus on strategy, storytelling, and building genuine connections with audiences.

The organizations that embrace this technology thoughtfully, with proper human oversight and clear quality standards, will find themselves with a significant competitive advantage in the content-driven marketplace.

**Ready to explore AI-powered content creation for your organization?** Start with a pilot project in one content area and gradually expand based on results and team comfort levels.

---

*Want to learn more about implementing AI tools in your content workflow? Check out our related articles on [automation in creative workflows](automation-creative-workflows.md) and [content strategy for 2024](content-strategy-2024.md).*
]]></content>
</tool_call>
```

### Project Analysis and Documentation

**User Message:**
```
"Analyze this project structure and create comprehensive documentation for new developers."
```

**Agent Response:**
```
I'll analyze your project structure and create comprehensive onboarding documentation for new developers. Let me start by examining the project layout and key files.

<tool_call name="command_execution" id="1">
  <command>find . -type f -name "*.json" -o -name "*.md" -o -name "*.ts" -o -name "*.js" | grep -E "(package\.json|README|tsconfig|index)" | head -20</command>
  <working_directory>.</working_directory>
  <timeout>10</timeout>
  <capture_stderr>true</capture_stderr>
</tool_call>

<tool_call name="read_file" id="2">
  <file_path>package.json</file_path>
</tool_call>

<tool_call name="read_file" id="3">
  <file_path>README.md</file_path>
</tool_call>

<tool_call name="command_execution" id="4">
  <command>tree -I 'node_modules|dist|.git' -L 3</command>
  <working_directory>.</working_directory>
  <timeout>15</timeout>
  <capture_stderr>true</capture_stderr>
</tool_call>
```

This example demonstrates the complete flow of:
1. User request
2. Agent acknowledgment with immediate tool calls
3. Tool execution and XML responses
4. Follow-up agent actions based on tool results
5. Final deliverable creation

## Simplified In-Context Message Architecture

### Yes, We Keep It Simplified

The current architecture maintains a **simplified in-context message setup** that:

1. **Separates concerns** between conversation-capable and simple providers
2. **Hides tool responses** from the UI while maintaining conversation flow
3. **Uses internal metadata** to track tool responses without cluttering user experience
4. **Maintains conversation continuity** through proper role separation

### Key Simplifications:

#### For Conversation Providers:
- System message contains all context (file tree, tools, base prompt)
- Tool responses are internal user messages with `metadata: { internal: true }`
- UI only shows actual user and assistant messages
- Conversation flow is preserved for better AI performance

#### For Simple Providers:
- Everything concatenated into a single prompt string
- Tool responses visible as context within the prompt
- Optimized for providers that don't support conversation arrays

## Best Practices

### Tool Call Guidelines

1. **Always include unique IDs** for tool calls to enable proper response matching
2. **Use CDATA sections** for complex content with special characters
3. **Be specific with file paths** - use relative paths from project root
4. **Include error handling** - anticipate and handle common failure scenarios
5. **Batch related operations** when possible to reduce conversation turns

### Message Flow Optimization

1. **Include tool calls immediately** when acknowledging work that requires them
2. **Keep interim messages brief** (1-2 sentences) when continuing with tool calls
3. **Provide comprehensive final responses** after all tool operations complete
4. **Use internal metadata** to hide tool responses from UI while maintaining conversation flow

### Memory and Context Management

1. **Use .memory directory** for persistent context across conversations
2. **Store project insights** and decisions for future reference
3. **Maintain conversation turn limits** to prevent infinite loops
4. **Leverage file tree context** for project awareness

### XML Format Advantages

The XML format provides several key benefits:

1. **Reliable Parsing**: Well-defined parsing rules handle edge cases robustly
2. **CDATA Support**: Complex content with quotes, brackets, and special characters
3. **Multiline Content**: Natural handling without escaping issues
4. **Better Error Recovery**: Clear error messages and recovery mechanisms
5. **Cleaner Syntax**: More readable and easier for LLMs to generate correctly
6. **Extensible**: Can easily add attributes or nested structures

This architecture enables powerful, context-aware AI agents that can perform complex multi-step operations while maintaining clean, user-friendly conversation interfaces.
