neuromance_common/
agents.rs

1//! Agent state management and context types.
2//!
3//! This module provides types for managing agent state, memory, and context in autonomous
4//! LLM-powered agents. These types enable agents to maintain conversation history, track
5//! execution statistics, store short/long-term memory, and manage task context.
6//!
7//! ## Core Types
8//!
9//! - [`AgentState`]: Complete agent state including messages, memory, context, and stats
10//! - [`AgentMemory`]: Memory storage with short-term, long-term, and working memory
11//! - [`AgentContext`]: Task context including goals, constraints, and environment
12//! - [`AgentMessage`]: Enum for different message types agents can process
13//! - [`AgentResponse`]: Response from agent execution including content and tool results
14//! - [`AgentStats`]: Execution statistics for monitoring and debugging
15//!
16//! ## Example: Using Agent State
17//!
18//! ```
19//! use neuromance_common::agents::{AgentState, AgentContext, AgentMemory, AgentStats};
20//!
21//! // Create a new agent state with default values
22//! let mut state = AgentState::default();
23//!
24//! // Configure the agent's task context
25//! state.context.task = Some("Research the Rust programming language".to_string());
26//! state.context.goals = vec![
27//!     "Find creation date".to_string(),
28//!     "Identify key features".to_string(),
29//! ];
30//! state.context.constraints = vec!["Use only reliable sources".to_string()];
31//!
32//! // Add to short-term memory
33//! state.memory.short_term.push("User prefers concise answers".to_string());
34//!
35//! // Track statistics
36//! state.stats.total_messages += 1;
37//! state.stats.successful_tool_calls += 2;
38//! ```
39//!
40//! ## Memory Management
41//!
42//! [`AgentMemory`] provides three types of memory storage:
43//!
44//! - **Short-term**: Recent context and observations (Vec of strings)
45//! - **Long-term**: Persistent knowledge (key-value string storage)
46//! - **Working memory**: Arbitrary JSON data for active processing
47//!
48//! ## Context Updates
49//!
50//! The [`ContextUpdate`] enum allows dynamic modification of agent context:
51//!
52//! ```
53//! use neuromance_common::agents::ContextUpdate;
54//!
55//! // Examples of context updates
56//! let updates = vec![
57//!     ContextUpdate::SetTask("New task description".to_string()),
58//!     ContextUpdate::AddGoal("Complete research".to_string()),
59//!     ContextUpdate::AddConstraint("Time limit: 5 minutes".to_string()),
60//!     ContextUpdate::SetEnvironmentVariable("debug".to_string(), "true".to_string()),
61//! ];
62//! ```
63
64use std::collections::HashMap;
65
66use serde::{Deserialize, Serialize};
67
68use crate::chat::Message;
69
70/// Updates that can be applied to an agent's context.
71///
72/// Allows dynamic modification of task, goals, constraints, and environment during execution.
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub enum ContextUpdate {
75    /// Set or replace the current task description.
76    SetTask(String),
77    /// Add a new goal to the agent's objectives.
78    AddGoal(String),
79    /// Remove a goal from the agent's objectives.
80    RemoveGoal(String),
81    /// Add a constraint that limits agent behavior.
82    AddConstraint(String),
83    /// Remove a previously added constraint.
84    RemoveConstraint(String),
85    /// Set an environment variable (key-value pair).
86    SetEnvironmentVariable(String, String),
87    /// Clear all memory (short-term, long-term, and working).
88    ClearMemory,
89}
90
91/// Messages that can be sent to or from an agent.
92///
93/// Represents different types of communication in an agent system.
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub enum AgentMessage {
96    /// Input from a user.
97    UserInput(String),
98    /// System-level prompt or instruction.
99    SystemPrompt(String),
100    /// Result from tool execution.
101    ToolResult(String),
102    /// Response generated by the agent.
103    AgentResponse(Box<AgentResponse>),
104    /// Request to update agent context.
105    ContextUpdate(ContextUpdate),
106}
107
108/// Response from agent execution.
109///
110/// Contains the main content, optional reasoning trace, and any tool execution results.
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct AgentResponse {
113    /// The primary response message from the agent.
114    pub content: Message,
115    /// Optional chain-of-thought or reasoning explanation.
116    pub reasoning: Option<String>,
117    /// Messages from tool executions that contributed to this response.
118    pub tool_responses: Vec<Message>,
119}
120
121/// Complete state of an agent.
122///
123/// Maintains all messages, conversation history, memory, context, and execution statistics.
124#[derive(Debug, Clone, Default, Serialize, Deserialize)]
125pub struct AgentState {
126    /// All messages in the current conversation.
127    pub messages: Vec<Message>,
128    /// History of agent interactions (message-response pairs).
129    pub conversation_history: Vec<(AgentMessage, AgentResponse)>,
130    /// Agent's memory systems.
131    pub memory: AgentMemory,
132    /// Current task context and objectives.
133    pub context: AgentContext,
134    /// Execution statistics and metrics.
135    pub stats: AgentStats,
136}
137
138/// Execution statistics for monitoring agent performance.
139#[derive(Debug, Clone, Default, Serialize, Deserialize)]
140pub struct AgentStats {
141    /// Total number of messages processed.
142    pub total_messages: usize,
143    /// Total tokens consumed across all interactions.
144    pub tokens_used: usize,
145    /// Number of successful tool executions.
146    pub successful_tool_calls: usize,
147    /// Number of failed tool executions.
148    pub failed_tool_calls: usize,
149}
150
151/// Context describing the agent's current task and environment.
152#[derive(Debug, Clone, Default, Serialize, Deserialize)]
153pub struct AgentContext {
154    /// The current task or objective.
155    pub task: Option<String>,
156    /// List of goals the agent should achieve.
157    pub goals: Vec<String>,
158    /// Constraints that limit agent behavior.
159    pub constraints: Vec<String>,
160    /// Environment variables available to the agent.
161    pub environment: HashMap<String, String>,
162}
163
164/// Memory storage for agents.
165///
166/// Provides three types of memory for different use cases:
167/// - Short-term: Recent observations and context
168/// - Long-term: Persistent facts and knowledge
169/// - Working: Arbitrary data for active processing
170#[derive(Debug, Clone, Default, Serialize, Deserialize)]
171pub struct AgentMemory {
172    /// Recent observations and temporary context.
173    pub short_term: Vec<String>,
174    /// Persistent knowledge stored as key-value pairs.
175    pub long_term: HashMap<String, String>,
176    /// Arbitrary JSON data for active processing.
177    pub working_memory: HashMap<String, serde_json::Value>,
178}