matrixcode_core/providers/
openai.rs1use anyhow::Result;
2use async_trait::async_trait;
3use serde_json::{Value, json};
4
5use crate::models::context_window_for;
6use crate::tools::ToolDefinition;
7
8use super::{
9 ChatRequest, ChatResponse, ContentBlock, Message, MessageContent, Provider, Role, StopReason,
10 Usage,
11};
12
13pub struct OpenAIProvider {
14 api_key: String,
15 model: String,
16 base_url: String,
17 client: reqwest::Client,
18 extra_headers: Vec<(String, String)>,
20}
21
22impl OpenAIProvider {
23 pub fn new(api_key: String, model: String, base_url: String) -> Self {
24 Self::with_headers(api_key, model, base_url, None)
25 }
26
27 pub fn with_headers(
28 api_key: String,
29 model: String,
30 base_url: String,
31 extra_headers: Option<std::collections::HashMap<String, String>>,
32 ) -> Self {
33 let client = reqwest::Client::builder()
38 .timeout(std::time::Duration::from_secs(300))
39 .connect_timeout(std::time::Duration::from_secs(10))
40 .read_timeout(std::time::Duration::from_secs(60))
41 .build()
42 .unwrap_or_else(|_| reqwest::Client::new());
43 let extra_headers: Vec<(String, String)> = extra_headers
44 .map(|h| h.into_iter().collect())
45 .unwrap_or_default();
46 Self {
47 api_key,
48 model,
49 base_url,
50 client,
51 extra_headers,
52 }
53 }
54
55 fn convert_messages(&self, messages: &[Message], system: Option<&str>) -> Vec<Value> {
56 let mut result = Vec::new();
57
58 if let Some(sys) = system {
59 result.push(json!({"role": "system", "content": sys}));
60 }
61
62 for msg in messages {
63 match (&msg.role, &msg.content) {
64 (Role::System, _) => {}
65 (Role::User, MessageContent::Text(text)) => {
66 result.push(json!({"role": "user", "content": text}));
67 }
68 (Role::Assistant, MessageContent::Text(text)) => {
69 result.push(json!({"role": "assistant", "content": text}));
70 }
71 (Role::Assistant, MessageContent::Blocks(blocks)) => {
72 let mut tool_calls = Vec::new();
73 let mut text_parts = Vec::new();
74
75 for block in blocks {
76 match block {
77 ContentBlock::Text { text } => text_parts.push(text.clone()),
78 ContentBlock::ToolUse { id, name, input } => {
79 tool_calls.push(json!({
80 "id": id,
81 "type": "function",
82 "function": {
83 "name": name,
84 "arguments": input.to_string(),
85 }
86 }));
87 }
88 ContentBlock::Thinking { .. } => {}
89 _ => {}
90 }
91 }
92
93 let mut msg_obj = json!({"role": "assistant"});
94 if !text_parts.is_empty() {
95 msg_obj["content"] = json!(text_parts.join("\n"));
96 }
97 if !tool_calls.is_empty() {
98 msg_obj["tool_calls"] = json!(tool_calls);
99 }
100 result.push(msg_obj);
101 }
102 (Role::Tool, MessageContent::Blocks(blocks)) => {
103 self.push_tool_results(blocks, &mut result);
104 }
105 (Role::User, MessageContent::Blocks(blocks)) => {
106 if blocks
108 .iter()
109 .any(|b| matches!(b, ContentBlock::ToolResult { .. }))
110 {
111 self.push_tool_results(blocks, &mut result);
113 } else {
114 let text: String = blocks
116 .iter()
117 .filter_map(|b| match b {
118 ContentBlock::Text { text } => Some(text.as_str()),
119 _ => None,
120 })
121 .collect::<Vec<_>>()
122 .join("\n");
123 result.push(json!({"role": "user", "content": text}));
124 }
125 }
126 _ => {}
127 }
128 }
129
130 result
131 }
132
133 fn push_tool_results(&self, blocks: &[ContentBlock], result: &mut Vec<Value>) {
135 for block in blocks {
136 if let ContentBlock::ToolResult {
137 tool_use_id,
138 content,
139 } = block
140 {
141 result.push(json!({
142 "role": "tool",
143 "tool_call_id": tool_use_id,
144 "content": content,
145 }));
146 }
147 }
148 }
149
150 fn convert_tools(&self, tools: &[ToolDefinition]) -> Vec<Value> {
151 tools
152 .iter()
153 .map(|t| {
154 json!({
155 "type": "function",
156 "function": {
157 "name": t.name,
158 "description": t.description,
159 "parameters": t.parameters,
160 }
161 })
162 })
163 .collect()
164 }
165}
166
167#[async_trait]
168impl Provider for OpenAIProvider {
169 fn context_size(&self) -> Option<u32> {
170 context_window_for(&self.model)
171 }
172
173 fn clone_box(&self) -> Box<dyn Provider> {
174 Box::new(Self {
175 api_key: self.api_key.clone(),
176 model: self.model.clone(),
177 base_url: self.base_url.clone(),
178 client: reqwest::Client::new(),
179 extra_headers: self.extra_headers.clone(),
180 })
181 }
182
183 async fn chat(&self, request: ChatRequest) -> Result<ChatResponse> {
184 let messages = self.convert_messages(&request.messages, request.system.as_deref());
185
186 let mut body = json!({
187 "model": self.model,
188 "messages": messages,
189 "max_completion_tokens": request.max_tokens,
190 });
191
192 if !request.tools.is_empty() {
193 body["tools"] = json!(self.convert_tools(&request.tools));
194 }
195
196 let url = format!("{}/chat/completions", self.base_url);
197
198 crate::debug::debug_log().api_request(&url, &serde_json::to_string(&body).unwrap_or_default());
200
201 let mut req = self
202 .client
203 .post(&url)
204 .header("Authorization", format!("Bearer {}", self.api_key))
205 .header("Content-Type", "application/json")
206 .json(&body);
207
208 for (name, value) in &self.extra_headers {
210 req = req.header(name, value);
211 }
212
213 let response = req.send().await?;
214
215 let status = response.status();
216 let response_body: Value = response.json().await?;
217
218 crate::debug::debug_log().api_response(status.as_u16(), &serde_json::to_string(&response_body).unwrap_or_default());
220
221 if !status.is_success() {
222 let err_msg = response_body["error"]["message"]
223 .as_str()
224 .unwrap_or("unknown error");
225 anyhow::bail!("OpenAI API error ({}): {}", status, err_msg);
226 }
227
228 let choice = &response_body["choices"][0];
229 let message = &choice["message"];
230 let finish_reason = choice["finish_reason"].as_str().unwrap_or("stop");
231
232 let stop_reason = match finish_reason {
233 "tool_calls" => StopReason::ToolUse,
234 "length" => StopReason::MaxTokens,
235 _ => StopReason::EndTurn,
236 };
237
238 let mut content = Vec::new();
239
240 let usage_blob = &response_body["usage"];
241 let usage = Usage {
242 input_tokens: usage_blob["prompt_tokens"].as_u64().unwrap_or(0) as u32,
243 output_tokens: usage_blob["completion_tokens"].as_u64().unwrap_or(0) as u32,
244 cache_creation_input_tokens: 0,
245 cache_read_input_tokens: usage_blob["prompt_tokens_details"]["cached_tokens"]
246 .as_u64()
247 .unwrap_or(0) as u32,
248 };
249
250 if let Some(text) = message["content"].as_str()
251 && !text.is_empty()
252 {
253 content.push(ContentBlock::Text {
254 text: text.to_string(),
255 });
256 }
257
258 if let Some(tool_calls) = message["tool_calls"].as_array() {
259 for tc in tool_calls {
260 let id = tc["id"].as_str().unwrap_or_default().to_string();
261 let name = tc["function"]["name"]
262 .as_str()
263 .unwrap_or_default()
264 .to_string();
265 let arguments = tc["function"]["arguments"].as_str().unwrap_or("{}");
266 let input: Value = serde_json::from_str(arguments).unwrap_or(json!({}));
267
268 content.push(ContentBlock::ToolUse { id, name, input });
269 }
270
271 if stop_reason == StopReason::EndTurn && !tool_calls.is_empty() {
272 return Ok(ChatResponse {
273 content,
274 stop_reason: StopReason::ToolUse,
275 usage: usage.clone(),
276 });
277 }
278 }
279
280 Ok(ChatResponse {
281 content,
282 stop_reason,
283 usage,
284 })
285 }
286}