ares/types/
mod.rs

1//! Core types used throughout the A.R.E.S server.
2//!
3//! This module contains all the common data structures used for:
4//! - API requests and responses
5//! - Agent configuration and context
6//! - Memory and user preferences
7//! - Tool definitions and calls
8//! - RAG (Retrieval Augmented Generation)
9//! - Authentication
10//! - Error handling
11
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14use utoipa::ToSchema;
15
16// ============= API Request/Response Types =============
17
18/// Request payload for chat endpoints.
19#[derive(Debug, Serialize, Deserialize, ToSchema)]
20pub struct ChatRequest {
21    /// The user's message to send to the agent.
22    pub message: String,
23    /// Optional agent type to handle the request. Defaults to router.
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub agent_type: Option<AgentType>,
26    /// Optional context ID for conversation continuity.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub context_id: Option<String>,
29}
30
31/// Response from chat endpoints.
32#[derive(Debug, Serialize, Deserialize, ToSchema)]
33pub struct ChatResponse {
34    /// The agent's response text.
35    pub response: String,
36    /// The name of the agent that handled the request.
37    pub agent: String,
38    /// Context ID for continuing this conversation.
39    pub context_id: String,
40    /// Optional sources used to generate the response.
41    pub sources: Option<Vec<Source>>,
42}
43
44/// A source reference used in responses.
45#[derive(Debug, Serialize, Deserialize, ToSchema, Clone)]
46pub struct Source {
47    /// Title of the source document or webpage.
48    pub title: String,
49    /// URL of the source, if available.
50    pub url: Option<String>,
51    /// Relevance score (0.0 to 1.0) indicating how relevant this source is.
52    pub relevance_score: f32,
53}
54
55/// Request payload for deep research endpoints.
56#[derive(Debug, Serialize, Deserialize, ToSchema)]
57pub struct ResearchRequest {
58    /// The research query or question.
59    pub query: String,
60    /// Optional maximum depth for recursive research (default: 3).
61    pub depth: Option<u8>,
62    /// Optional maximum iterations across all agents (default: 10).
63    pub max_iterations: Option<u8>,
64}
65
66/// Response from deep research endpoints.
67#[derive(Debug, Serialize, Deserialize, ToSchema)]
68pub struct ResearchResponse {
69    /// The compiled research findings.
70    pub findings: String,
71    /// Sources discovered during research.
72    pub sources: Vec<Source>,
73    /// Time taken for the research in milliseconds.
74    pub duration_ms: u64,
75}
76
77// ============= Workflow Types =============
78
79/// Request payload for workflow execution endpoints.
80#[derive(Debug, Serialize, Deserialize, ToSchema)]
81pub struct WorkflowRequest {
82    /// The query to process through the workflow.
83    pub query: String,
84    /// Additional context data as key-value pairs.
85    #[serde(default)]
86    pub context: std::collections::HashMap<String, serde_json::Value>,
87}
88
89// ============= Agent Types =============
90
91/// Available agent types in the system.
92#[derive(Debug, Serialize, Deserialize, ToSchema, Clone, Copy, PartialEq, Eq)]
93#[serde(rename_all = "lowercase")]
94pub enum AgentType {
95    /// Routes requests to appropriate specialized agents.
96    Router,
97    /// Orchestrates complex multi-step tasks.
98    Orchestrator,
99    /// Handles product-related queries.
100    Product,
101    /// Handles invoice and billing queries.
102    Invoice,
103    /// Handles sales-related queries.
104    Sales,
105    /// Handles financial queries and analysis.
106    Finance,
107    /// Handles HR and employee-related queries.
108    HR,
109}
110
111/// Context passed to agents during request processing.
112#[derive(Debug, Clone)]
113pub struct AgentContext {
114    /// Unique identifier for the user making the request.
115    pub user_id: String,
116    /// Session identifier for conversation tracking.
117    pub session_id: String,
118    /// Previous messages in the conversation.
119    pub conversation_history: Vec<Message>,
120    /// User's stored memory and preferences.
121    pub user_memory: Option<UserMemory>,
122}
123
124/// A single message in a conversation.
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct Message {
127    /// The role of the message sender.
128    pub role: MessageRole,
129    /// The message content.
130    pub content: String,
131    /// When the message was sent.
132    pub timestamp: DateTime<Utc>,
133}
134
135/// Role of a message sender in a conversation.
136#[derive(Debug, Clone, Serialize, Deserialize)]
137#[serde(rename_all = "lowercase")]
138pub enum MessageRole {
139    /// System instructions to the model.
140    System,
141    /// Message from the user.
142    User,
143    /// Response from the assistant/agent.
144    Assistant,
145}
146
147// ============= Memory Types =============
148
149/// User memory containing preferences and learned facts.
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct UserMemory {
152    /// The user's unique identifier.
153    pub user_id: String,
154    /// List of user preferences.
155    pub preferences: Vec<Preference>,
156    /// List of facts learned about the user.
157    pub facts: Vec<MemoryFact>,
158}
159
160/// A user preference entry.
161#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct Preference {
163    /// Category of the preference (e.g., "communication", "output").
164    pub category: String,
165    /// Key identifying the specific preference.
166    pub key: String,
167    /// The preference value.
168    pub value: String,
169    /// Confidence score (0.0 to 1.0) for this preference.
170    pub confidence: f32,
171}
172
173/// A fact learned about a user.
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct MemoryFact {
176    /// Unique identifier for this fact.
177    pub id: String,
178    /// The user this fact belongs to.
179    pub user_id: String,
180    /// Category of the fact (e.g., "personal", "work").
181    pub category: String,
182    /// Key identifying the specific fact.
183    pub fact_key: String,
184    /// The fact value.
185    pub fact_value: String,
186    /// Confidence score (0.0 to 1.0) for this fact.
187    pub confidence: f32,
188    /// When this fact was first recorded.
189    pub created_at: DateTime<Utc>,
190    /// When this fact was last updated.
191    pub updated_at: DateTime<Utc>,
192}
193
194// ============= Tool Types =============
195
196/// Definition of a tool that can be called by an LLM.
197#[derive(Debug, Serialize, Deserialize, Clone)]
198pub struct ToolDefinition {
199    /// Unique name of the tool.
200    pub name: String,
201    /// Human-readable description of what the tool does.
202    pub description: String,
203    /// JSON Schema defining the tool's parameters.
204    pub parameters: serde_json::Value,
205}
206
207/// A request to call a tool.
208#[derive(Debug, Serialize, Deserialize, Clone)]
209pub struct ToolCall {
210    /// Unique identifier for this tool call.
211    pub id: String,
212    /// Name of the tool to call.
213    pub name: String,
214    /// Arguments to pass to the tool.
215    pub arguments: serde_json::Value,
216}
217
218/// Result from executing a tool.
219#[derive(Debug, Serialize, Deserialize)]
220pub struct ToolResult {
221    /// ID of the tool call this result corresponds to.
222    pub tool_call_id: String,
223    /// The result data from the tool execution.
224    pub result: serde_json::Value,
225}
226
227// ============= RAG Types =============
228
229/// A document in the RAG knowledge base.
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct Document {
232    /// Unique identifier for the document.
233    pub id: String,
234    /// The document's text content.
235    pub content: String,
236    /// Metadata about the document.
237    pub metadata: DocumentMetadata,
238    /// Optional embedding vector for semantic search.
239    pub embedding: Option<Vec<f32>>,
240}
241
242/// Metadata associated with a document.
243#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct DocumentMetadata {
245    /// Title of the document.
246    pub title: String,
247    /// Source of the document (e.g., URL, file path).
248    pub source: String,
249    /// When the document was created or ingested.
250    pub created_at: DateTime<Utc>,
251    /// Tags for categorization and filtering.
252    pub tags: Vec<String>,
253}
254
255/// Query parameters for semantic search.
256#[derive(Debug, Clone)]
257pub struct SearchQuery {
258    /// The search query text.
259    pub query: String,
260    /// Maximum number of results to return.
261    pub limit: usize,
262    /// Minimum similarity threshold (0.0 to 1.0).
263    pub threshold: f32,
264    /// Optional filters to apply to results.
265    pub filters: Option<Vec<SearchFilter>>,
266}
267
268/// A filter to apply during search.
269#[derive(Debug, Clone)]
270pub struct SearchFilter {
271    /// Field name to filter on.
272    pub field: String,
273    /// Value to filter by.
274    pub value: String,
275}
276
277/// A single search result with relevance score.
278#[derive(Debug, Clone)]
279pub struct SearchResult {
280    /// The matching document.
281    pub document: Document,
282    /// Similarity score (0.0 to 1.0).
283    pub score: f32,
284}
285
286// ============= Authentication Types =============
287
288/// Request payload for user login.
289#[derive(Debug, Serialize, Deserialize, ToSchema)]
290pub struct LoginRequest {
291    /// User's email address.
292    pub email: String,
293    /// User's password.
294    pub password: String,
295}
296
297/// Request payload for user registration.
298#[derive(Debug, Serialize, Deserialize, ToSchema)]
299pub struct RegisterRequest {
300    /// Email address for the new account.
301    pub email: String,
302    /// Password for the new account.
303    pub password: String,
304    /// Display name for the user.
305    pub name: String,
306}
307
308/// Response containing authentication tokens.
309#[derive(Debug, Serialize, Deserialize, ToSchema)]
310pub struct TokenResponse {
311    /// JWT access token for API authentication.
312    pub access_token: String,
313    /// Refresh token for obtaining new access tokens.
314    pub refresh_token: String,
315    /// Time in seconds until the access token expires.
316    pub expires_in: i64,
317}
318
319/// JWT claims embedded in access tokens.
320#[derive(Debug, Serialize, Deserialize, Clone)]
321pub struct Claims {
322    /// Subject (user ID).
323    pub sub: String,
324    /// User's email address.
325    pub email: String,
326    /// Expiration time (Unix timestamp).
327    pub exp: usize,
328    /// Issued at time (Unix timestamp).
329    pub iat: usize,
330}
331
332// ============= Error Types =============
333
334/// Application-wide error type.
335#[derive(Debug, thiserror::Error)]
336pub enum AppError {
337    /// Database operation failed.
338    #[error("Database error: {0}")]
339    Database(String),
340
341    /// LLM operation failed.
342    #[error("LLM error: {0}")]
343    LLM(String),
344
345    /// Authentication or authorization failed.
346    #[error("Authentication error: {0}")]
347    Auth(String),
348
349    /// Requested resource was not found.
350    #[error("Not found: {0}")]
351    NotFound(String),
352
353    /// Input validation failed.
354    #[error("Invalid input: {0}")]
355    InvalidInput(String),
356
357    /// Configuration error.
358    #[error("Configuration error: {0}")]
359    Configuration(String),
360
361    /// External service call failed.
362    #[error("External service error: {0}")]
363    External(String),
364
365    /// Internal server error.
366    #[error("Internal error: {0}")]
367    Internal(String),
368}
369
370impl axum::response::IntoResponse for AppError {
371    fn into_response(self) -> axum::response::Response {
372        let (status, message) = match self {
373            AppError::Database(msg) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg),
374            AppError::LLM(msg) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg),
375            AppError::Auth(msg) => (axum::http::StatusCode::UNAUTHORIZED, msg),
376            AppError::NotFound(msg) => (axum::http::StatusCode::NOT_FOUND, msg),
377            AppError::InvalidInput(msg) => (axum::http::StatusCode::BAD_REQUEST, msg),
378            AppError::Configuration(msg) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg),
379            AppError::External(msg) => (axum::http::StatusCode::BAD_GATEWAY, msg),
380            AppError::Internal(msg) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg),
381        };
382
383        let body = serde_json::json!({
384            "error": message
385        });
386
387        (status, axum::Json(body)).into_response()
388    }
389}
390
391/// A specialized Result type for A.R.E.S operations.
392pub type Result<T> = std::result::Result<T, AppError>;