blob: 0015d902bae30fcefb92aacd60f1caab5ae6b4cb [file] [log] [blame] [view]
iomodo76f9a2d2025-07-26 12:14:40 +04001# Agent Package
2
3The `agent` package provides an AI agent system that can autonomously process tasks using LLM services, manage tasks through a task management system, and create pull requests with solutions.
4
5## Overview
6
7The agent system consists of:
8
9- **AI Agent**: Processes tasks using LLM services
10- **Task Manager**: Manages task lifecycle and assignment
11- **Git Integration**: Creates pull requests with solutions
12- **Infinite Loop**: Continuously processes assigned tasks
13
14## Features
15
16- **Autonomous Task Processing**: Agents automatically pick up and process assigned tasks
17- **LLM Integration**: Uses configurable LLM providers (OpenAI, Claude, etc.)
18- **Task Management**: Integrates with task management systems
19- **Git Operations**: Creates branches and pull requests for solutions
20- **Configurable Roles**: Different agents can have different roles and system prompts
21- **Error Handling**: Robust error handling with graceful recovery
22
23## Quick Start
24
25### 1. Basic Setup
26
27```go
28package main
29
30import (
31 "log"
32 "time"
33
34 "github.com/iomodo/staff/agent"
35 "github.com/iomodo/staff/git"
36 "github.com/iomodo/staff/llm"
37 "github.com/iomodo/staff/tm"
38 "github.com/iomodo/staff/tm/git_tm"
39)
40
41func main() {
42 // Create git interface for task management
43 gitInterface := git.DefaultGit("./tasks-repo")
44
45 // Create task manager
46 taskManager := git_tm.NewGitTaskManager(gitInterface, "./tasks-repo")
47
48 // Create LLM configuration
49 llmConfig := llm.Config{
50 Provider: llm.ProviderOpenAI,
51 APIKey: "your-openai-api-key-here",
52 BaseURL: "https://api.openai.com/v1",
53 Timeout: 30 * time.Second,
54 }
55
56 // Create agent configuration
57 config := agent.AgentConfig{
58 Name: "backend-engineer-1",
59 Role: "Backend Engineer",
60 GitUsername: "backend-agent",
61 GitEmail: "backend-agent@company.com",
62 WorkingDir: "./workspace",
63 LLMProvider: llm.ProviderOpenAI,
64 LLMModel: "gpt-4",
65 LLMConfig: llmConfig,
66 SystemPrompt: `You are a skilled backend engineer. Your role is to:
671. Analyze tasks and provide technical solutions
682. Write clean, maintainable code
693. Consider performance, security, and scalability
704. Provide clear documentation for your solutions
715. Follow best practices and coding standards`,
72 TaskManager: taskManager,
73 GitRepoPath: "./code-repo",
74 GitRemote: "origin",
75 GitBranch: "main",
76 }
77
78 // Create agent
79 agent, err := agent.NewAgent(config)
80 if err != nil {
81 log.Fatalf("Failed to create agent: %v", err)
82 }
83
84 // Run the agent
85 if err := agent.Run(); err != nil {
86 log.Fatalf("Agent failed: %v", err)
87 }
88}
89```
90
91### 2. Create a Task
92
93```go
94// Create a task for the agent to process
95ctx := context.Background()
96task, err := taskManager.CreateTask(ctx, &tm.TaskCreateRequest{
97 Title: "Implement user authentication API",
98 Description: "Create a REST API endpoint for user authentication with JWT tokens. Include login, logout, and token refresh functionality.",
99 OwnerID: "backend-engineer-1", // Must match agent name
100 Priority: tm.PriorityHigh,
101})
102if err != nil {
103 log.Fatalf("Failed to create task: %v", err)
104}
105```
106
107## Configuration
108
109### AgentConfig
110
111The `AgentConfig` struct contains all configuration for an agent:
112
113```go
114type AgentConfig struct {
115 Name string // Agent identifier
116 Role string // Agent role (e.g., "Backend Engineer")
117 GitUsername string // Git username for commits
118 GitEmail string // Git email for commits
119 WorkingDir string // Working directory for files
120
121 // LLM Configuration
122 LLMProvider llm.Provider // LLM provider type
123 LLMModel string // Model name (e.g., "gpt-4")
124 LLMConfig llm.Config // LLM provider configuration
125
126 // System prompt for the agent
127 SystemPrompt string // Instructions for the LLM
128
129 // Task Manager Configuration
130 TaskManager tm.TaskManager // Task management interface
131
132 // Git Configuration
133 GitRepoPath string // Path to git repository
134 GitRemote string // Remote name (usually "origin")
135 GitBranch string // Default branch name
136}
137```
138
139### System Prompts
140
141System prompts define the agent's behavior and expertise. Here are some examples:
142
143#### Backend Engineer
144```
145You are a skilled backend engineer. Your role is to:
1461. Analyze tasks and provide technical solutions
1472. Write clean, maintainable code
1483. Consider performance, security, and scalability
1494. Provide clear documentation for your solutions
1505. Follow best practices and coding standards
151
152When responding to tasks, provide:
153- Detailed technical analysis
154- Code examples where appropriate
155- Implementation considerations
156- Testing recommendations
157- Documentation suggestions
158```
159
160#### Frontend Engineer
161```
162You are a frontend engineer. Focus on:
163- User interface design and implementation
164- React/Vue/Angular development
165- Responsive design and accessibility
166- Performance optimization
167- User experience best practices
168```
169
170#### Product Manager
171```
172You are a product manager. Focus on:
173- Product strategy and roadmap
174- User research and requirements gathering
175- Feature prioritization and planning
176- Stakeholder communication
177- Product documentation and specifications
178```
179
180## How It Works
181
182### 1. Task Processing Loop
183
184The agent runs in an infinite loop that:
185
1861. **Fetches Tasks**: Gets tasks assigned to the agent from the task manager
1872. **Filters Tasks**: Looks for tasks with "todo" status
1883. **Starts Task**: Marks the task as "in progress"
1894. **Processes with LLM**: Sends task description to LLM for solution
1905. **Creates PR**: Creates a git branch and pull request with the solution
1916. **Completes Task**: Marks the task as completed
192
193### 2. Git Operations
194
195For each task, the agent:
196
1971. Creates a new branch: `task/{task-id}-{clean-title}`
1982. Writes solution to a markdown file
1993. Commits the solution
2004. Pushes the branch to create a pull request
201
202### 3. Solution Format
203
204Solutions are formatted as markdown files containing:
205
206- Task metadata (ID, title, agent info)
207- Original task description
208- LLM-generated solution
209- Timestamp and attribution
210
211## Multiple Agents
212
213You can run multiple agents with different roles:
214
215```go
216// Create agents with different roles
217agents := []agent.AgentConfig{
218 {
219 Name: "backend-engineer-1",
220 Role: "Backend Engineer",
221 // ... backend configuration
222 },
223 {
224 Name: "frontend-engineer-1",
225 Role: "Frontend Engineer",
226 // ... frontend configuration
227 },
228 {
229 Name: "product-manager-1",
230 Role: "Product Manager",
231 // ... product manager configuration
232 },
233}
234
235// Start all agents
236for _, config := range agents {
237 agent, err := agent.NewAgent(config)
238 if err != nil {
239 log.Printf("Failed to create agent %s: %v", config.Name, err)
240 continue
241 }
242
243 go func(agent *agent.Agent, name string) {
244 log.Printf("Starting agent: %s", name)
245 if err := agent.Run(); err != nil {
246 log.Printf("Agent %s stopped with error: %v", name, err)
247 }
248 }(agent, config.Name)
249}
250```
251
252## Error Handling
253
254The agent includes robust error handling:
255
256- **Configuration Validation**: Validates all required fields
257- **Graceful Recovery**: Continues running even if individual tasks fail
258- **Logging**: Comprehensive logging of all operations
259- **Resource Cleanup**: Proper cleanup of LLM connections
260
261## Testing
262
263Run the tests with:
264
265```bash
266go test ./server/agent/...
267```
268
269The test suite includes:
270
271- Configuration validation
272- Branch name generation
273- Task prompt building
274- Solution formatting
275- Error handling
276
277## Dependencies
278
279The agent package depends on:
280
281- `github.com/iomodo/staff/llm` - LLM service interface
282- `github.com/iomodo/staff/tm` - Task management interface
283- `github.com/iomodo/staff/git` - Git operations interface
284
285## Examples
286
287See `example.go` for complete working examples:
288
289- `ExampleAgent()` - Single agent setup
290- `ExampleMultipleAgents()` - Multiple agents with different roles
291
292## Best Practices
293
2941. **Unique Agent Names**: Ensure each agent has a unique name
2952. **Role-Specific Prompts**: Tailor system prompts to the agent's role
2963. **Task Assignment**: Assign tasks to agents by setting the `OwnerID` to the agent's name
2974. **Monitoring**: Monitor agent logs for errors and performance
2985. **Resource Management**: Ensure proper cleanup when stopping agents