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")]
15#[non_exhaustive]
16pub enum Role {
17    System,
18    User,
19    Assistant,
20    Tool,
21}
22
23/// A tool call the model asked for.
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25pub struct ToolCall {
26    pub id: String,
27    pub name: String,
28    #[serde(default)]
29    pub arguments: Value,
30}
31
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct Message {
34    pub role: Role,
35    pub content: String,
36    #[serde(default, skip_serializing_if = "Vec::is_empty")]
37    pub tool_calls: Vec<ToolCall>,
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub tool_call_id: Option<String>,
40}
41
42impl Message {
43    pub fn system(content: impl Into<String>) -> Self {
44        Self { role: Role::System, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
45    }
46
47    pub fn user(content: impl Into<String>) -> Self {
48        Self { role: Role::User, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
49    }
50
51    pub fn assistant(content: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
52        Self { role: Role::Assistant, content: content.into(), tool_calls, tool_call_id: None }
53    }
54
55    pub fn tool(call_id: impl Into<String>, content: impl Into<String>) -> Self {
56        Self { role: Role::Tool, content: content.into(), tool_calls: Vec::new(), tool_call_id: Some(call_id.into()) }
57    }
58}
59
60/// One model turn: final text and any tool calls.
61#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
62pub struct ModelTurn {
63    pub text: String,
64    #[serde(default)]
65    pub tool_calls: Vec<ToolCall>,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
69#[non_exhaustive]
70pub enum ModelError {
71    #[error("model unavailable: {0}")]
72    Unavailable(String),
73    #[error("model failed: {0}")]
74    Failed(String),
75    #[error("cancelled")]
76    Cancelled,
77}
78
79/// Where a backend streams text as it is sampled.
80#[derive(Debug, Clone)]
81pub struct DeltaSink {
82    tx: Option<UnboundedSender<AgentEvent>>,
83}
84
85impl DeltaSink {
86    pub fn new(tx: Option<UnboundedSender<AgentEvent>>) -> Self {
87        Self { tx }
88    }
89
90    /// A sink that drops everything.
91    pub fn discard() -> Self {
92        Self { tx: None }
93    }
94
95    pub fn text(&self, delta: impl Into<String>) {
96        if let Some(tx) = &self.tx {
97            let _ = tx.send(AgentEvent::TextDelta(delta.into()));
98        }
99    }
100
101    /// Reasoning ("thinking") text, streamed apart from the answer. It is shown but never part
102    /// of the turn's text.
103    pub fn reasoning(&self, delta: impl Into<String>) {
104        if let Some(tx) = &self.tx {
105            let _ = tx.send(AgentEvent::ReasoningDelta(delta.into()));
106        }
107    }
108}
109
110/// A chat model with tool calling. Implementations should poll `cancel` while
111/// sampling and stream text through `deltas`.
112#[async_trait]
113pub trait ModelBackend: Send + Sync {
114    /// Shown in traces, for example `gemma-4-e4b@node-a`.
115    fn name(&self) -> String;
116
117    async fn complete(&self, messages: &[Message], tools: &[ToolSpec], deltas: &DeltaSink, cancel: &CancelToken) -> Result<ModelTurn, ModelError>;
118}