| 310 | } |
| 311 | |
| 312 | async fn call_anthropic(&self, context: &str, query: &str) -> Result<LlmResponse, AiError> { |
| 313 | let url = format!("{}/messages", self.base_url); |
| 314 | let body = serde_json::json!({ |
| 315 | "model": self.model, |
| 316 | "max_tokens": 1024, |
| 317 | "system": "You are a code assistant for a repository tracked by Atomic VCS (not git). \ |
| 318 | The context includes: entities (functions, structs, traits extracted by AST), \ |
| 319 | files, changes (these ARE the commit history — each has a date, sequence number, and message), \ |
| 320 | views (like branches), goals (development sessions), and intents (work items). \ |
| 321 | Change nodes show the project's history — use their dates and messages to answer questions about \ |
| 322 | recent modifications. Answer using only the provided context. Be concise and precise.", |
| 323 | "messages": [{ |
| 324 | "role": "user", |
| 325 | "content": format!("{}\n\nQuestion: {}", context, query) |
| 326 | }] |
| 327 | }); |
| 328 | |
| 329 | let client = reqwest::Client::new(); |
| 330 | let resp = client |
| 331 | .post(&url) |
| 332 | .header("x-api-key", &self.api_key) |
| 333 | .header("anthropic-version", "2023-06-01") |
| 334 | .header("content-type", "application/json") |
| 335 | .json(&body) |
| 336 | .send() |
| 337 | .await |
| 338 | .map_err(|e| AiError::Http(e.to_string()))?; |
| 339 | |
| 340 | if !resp.status().is_success() { |
| 341 | let status = resp.status(); |
| 342 | let text = resp.text().await.unwrap_or_default(); |
| 343 | return Err(AiError::ApiError { |
| 344 | status: status.as_u16(), |
| 345 | body: text, |
| 346 | }); |
| 347 | } |
| 348 | |
| 349 | let json: serde_json::Value = resp |
| 350 | .json() |
| 351 | .await |
| 352 | .map_err(|e| AiError::Http(e.to_string()))?; |
| 353 | |
| 354 | let text = json["content"] |
| 355 | .as_array() |
| 356 | .and_then(|arr| arr.first()) |
| 357 | .and_then(|c| c["text"].as_str()) |
| 358 | .unwrap_or("") |
| 359 | .to_string(); |
| 360 | |
| 361 | let tokens = json["usage"]["output_tokens"].as_u64(); |
| 362 | |
| 363 | Ok(LlmResponse { |
| 364 | answer: text, |
| 365 | model: self.model.clone(), |
| 366 | tokens_used: tokens, |
| 367 | }) |
| 368 | } |
| 369 | |