1use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11use crate::capability::ToolSpec;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
14pub enum ProviderKind {
15 Ollama,
17 LlamaCpp,
19 OpenAiCompatible,
21 Anthropic,
23 McpBridge,
26}
27
28#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
31pub struct ProviderConfig {
32 pub kind: ProviderKind,
33 pub base_url: String,
34 pub model: String,
35 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub api_key_env: Option<String>,
37}
38
39impl ProviderConfig {
40 pub fn ollama(model: impl Into<String>) -> Self {
41 Self {
42 kind: ProviderKind::Ollama,
43 base_url: "http://localhost:11434".into(),
44 model: model.into(),
45 api_key_env: None,
46 }
47 }
48 pub fn llama_cpp(model: impl Into<String>, port: u16) -> Self {
49 Self {
50 kind: ProviderKind::LlamaCpp,
51 base_url: format!("http://localhost:{port}"),
52 model: model.into(),
53 api_key_env: None,
54 }
55 }
56 pub fn openai_compatible(
58 base_url: impl Into<String>,
59 model: impl Into<String>,
60 key_env: impl Into<String>,
61 ) -> Self {
62 Self {
63 kind: ProviderKind::OpenAiCompatible,
64 base_url: base_url.into(),
65 model: model.into(),
66 api_key_env: Some(key_env.into()),
67 }
68 }
69 pub fn anthropic(model: impl Into<String>) -> Self {
70 Self {
71 kind: ProviderKind::Anthropic,
72 base_url: "https://api.anthropic.com".into(),
73 model: model.into(),
74 api_key_env: Some("ANTHROPIC_API_KEY".into()),
75 }
76 }
77
78 pub fn api_key(&self) -> Option<String> {
80 self.api_key_env
81 .as_ref()
82 .and_then(|var| std::env::var(var).ok())
83 }
84}
85
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "lowercase")]
88pub enum Role {
89 System,
90 User,
91 Assistant,
92 Tool,
93}
94
95#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
96pub struct ChatMessage {
97 pub role: Role,
98 pub content: String,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub tool_call_id: Option<String>,
102}
103
104impl ChatMessage {
105 pub fn system(s: impl Into<String>) -> Self {
106 Self {
107 role: Role::System,
108 content: s.into(),
109 tool_call_id: None,
110 }
111 }
112 pub fn user(s: impl Into<String>) -> Self {
113 Self {
114 role: Role::User,
115 content: s.into(),
116 tool_call_id: None,
117 }
118 }
119 pub fn assistant(s: impl Into<String>) -> Self {
120 Self {
121 role: Role::Assistant,
122 content: s.into(),
123 tool_call_id: None,
124 }
125 }
126 pub fn tool(id: impl Into<String>, result: impl Into<String>) -> Self {
127 Self {
128 role: Role::Tool,
129 content: result.into(),
130 tool_call_id: Some(id.into()),
131 }
132 }
133}
134
135#[derive(Clone, Debug, Default)]
136pub struct ChatRequest {
137 pub messages: Vec<ChatMessage>,
138 pub tools: Vec<ToolSpec>,
140 pub temperature: Option<f32>,
141}
142
143#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
145pub struct ToolCall {
146 pub call_id: String,
147 pub name: String,
148 pub args: Value,
149}
150
151#[derive(Clone, Debug, PartialEq)]
153pub enum AssistantTurn {
154 Text(String),
155 Calls(Vec<ToolCall>),
157 Both {
159 text: String,
160 calls: Vec<ToolCall>,
161 },
162}
163
164impl AssistantTurn {
165 pub fn calls(&self) -> &[ToolCall] {
166 match self {
167 AssistantTurn::Text(_) => &[],
168 AssistantTurn::Calls(c) | AssistantTurn::Both { calls: c, .. } => c,
169 }
170 }
171 pub fn text(&self) -> &str {
172 match self {
173 AssistantTurn::Text(t) | AssistantTurn::Both { text: t, .. } => t,
174 AssistantTurn::Calls(_) => "",
175 }
176 }
177}
178
179#[derive(Debug, thiserror::Error)]
180pub enum ProviderError {
181 #[error("Transport-Fehler: {0}")]
182 Transport(String),
183 #[error("Protokoll-Fehler: Antwort nicht interpretierbar: {0}")]
184 Protocol(String),
185 #[error("Auth fehlgeschlagen (Schlüssel gesetzt?): {0}")]
186 Auth(String),
187 #[error("Provider kann das nicht: {0}")]
188 Unsupported(String),
189}
190
191pub trait AiProvider: Send {
195 fn kind(&self) -> ProviderKind;
196 fn complete(&mut self, req: &ChatRequest) -> Result<AssistantTurn, ProviderError>;
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn turn_helpers_aggregieren() {
205 let t = AssistantTurn::Both {
206 text: "schaue nach".into(),
207 calls: vec![ToolCall {
208 call_id: "1".into(),
209 name: "scene.stats".into(),
210 args: Value::Null,
211 }],
212 };
213 assert_eq!(t.calls().len(), 1);
214 assert_eq!(t.text(), "schaue nach");
215 }
216
217 #[test]
218 fn konfigurationen_zeigen_nur_env_namen() {
219 let c = ProviderConfig::anthropic("claude-x");
220 assert_eq!(c.api_key_env.as_deref(), Some("ANTHROPIC_API_KEY"));
221 let dbg = format!("{c:?}");
223 assert!(!dbg.contains("sk-"));
224 }
225}