Skip to main content

weirdnet_agent/
model.rs

1//! The model backend trait and chat messages. Inference lives elsewhere
2//! (`weirdnet-model`, remote nodes); this crate only drives it.
3
4use async_trait::async_trait;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use tokio::sync::mpsc::UnboundedSender;
8
9use crate::cancel::CancelToken;
10use crate::session::AgentEvent;
11use crate::tool::ToolSpec;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum Role {
16    System,
17    User,
18    Assistant,
19    Tool,
20}
21
22/// A tool call the model asked for.
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct ToolCall {
25    pub id: String,
26    pub name: String,
27    #[serde(default)]
28    pub arguments: Value,
29}
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub struct Message {
33    pub role: Role,
34    pub content: String,
35    #[serde(default, skip_serializing_if = "Vec::is_empty")]
36    pub tool_calls: Vec<ToolCall>,
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub tool_call_id: Option<String>,
39}
40
41impl Message {
42    pub fn system(content: impl Into<String>) -> Self {
43        Self { role: Role::System, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
44    }
45
46    pub fn user(content: impl Into<String>) -> Self {
47        Self { role: Role::User, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
48    }
49
50    pub fn assistant(content: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
51        Self { role: Role::Assistant, content: content.into(), tool_calls, tool_call_id: None }
52    }
53
54    pub fn tool(call_id: impl Into<String>, content: impl Into<String>) -> Self {
55        Self { role: Role::Tool, content: content.into(), tool_calls: Vec::new(), tool_call_id: Some(call_id.into()) }
56    }
57}
58
59/// One model turn: final text and any tool calls.
60#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
61pub struct ModelTurn {
62    pub text: String,
63    #[serde(default)]
64    pub tool_calls: Vec<ToolCall>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
68pub enum ModelError {
69    #[error("model unavailable: {0}")]
70    Unavailable(String),
71    #[error("model failed: {0}")]
72    Failed(String),
73    #[error("cancelled")]
74    Cancelled,
75}
76
77/// Where a backend streams text as it is sampled.
78#[derive(Debug, Clone)]
79pub struct DeltaSink {
80    tx: Option<UnboundedSender<AgentEvent>>,
81}
82
83impl DeltaSink {
84    pub fn new(tx: Option<UnboundedSender<AgentEvent>>) -> Self {
85        Self { tx }
86    }
87
88    /// A sink that drops everything.
89    pub fn discard() -> Self {
90        Self { tx: None }
91    }
92
93    pub fn text(&self, delta: impl Into<String>) {
94        if let Some(tx) = &self.tx {
95            let _ = tx.send(AgentEvent::TextDelta(delta.into()));
96        }
97    }
98}
99
100/// A chat model with tool calling. Implementations should poll `cancel` while
101/// sampling and stream text through `deltas`.
102#[async_trait]
103pub trait ModelBackend: Send + Sync {
104    /// Shown in traces, for example `gemma-4-e4b@alien-blue`.
105    fn name(&self) -> String;
106
107    async fn complete(&self, messages: &[Message], tools: &[ToolSpec], deltas: &DeltaSink, cancel: &CancelToken) -> Result<ModelTurn, ModelError>;
108}