1use crate::chat::ChatMessage;
2use crate::config::{LLMConfig, LocalConfig};
3use crate::error::{HeliosError, Result};
4use crate::tools::ToolDefinition;
5use async_trait::async_trait;
6use futures::stream::StreamExt;
7use llama_cpp_2::context::params::LlamaContextParams;
8use llama_cpp_2::llama_backend::LlamaBackend;
9use llama_cpp_2::llama_batch::LlamaBatch;
10use llama_cpp_2::model::params::LlamaModelParams;
11use llama_cpp_2::model::{AddBos, LlamaModel, Special};
12use llama_cpp_2::token::LlamaToken;
13use reqwest::Client;
14use serde::{Deserialize, Serialize};
15use std::sync::Arc;
16use tokio::task;
17use std::fs::File;
18use std::os::fd::AsRawFd;
19
20impl From<llama_cpp_2::LLamaCppError> for HeliosError {
22 fn from(err: llama_cpp_2::LLamaCppError) -> Self {
23 HeliosError::LlamaCppError(format!("{:?}", err))
24 }
25}
26
27#[derive(Clone)]
28pub enum LLMProviderType {
29 Remote(LLMConfig),
30 Local(LocalConfig),
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct LLMRequest {
35 pub model: String,
36 pub messages: Vec<ChatMessage>,
37 #[serde(skip_serializing_if = "Option::is_none")]
38 pub temperature: Option<f32>,
39 #[serde(skip_serializing_if = "Option::is_none")]
40 pub max_tokens: Option<u32>,
41 #[serde(skip_serializing_if = "Option::is_none")]
42 pub tools: Option<Vec<ToolDefinition>>,
43 #[serde(skip_serializing_if = "Option::is_none")]
44 pub tool_choice: Option<String>,
45 #[serde(skip_serializing_if = "Option::is_none")]
46 pub stream: Option<bool>,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct StreamChunk {
51 pub id: String,
52 pub object: String,
53 pub created: u64,
54 pub model: String,
55 pub choices: Vec<StreamChoice>,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct StreamChoice {
60 pub index: u32,
61 pub delta: Delta,
62 pub finish_reason: Option<String>,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct Delta {
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub role: Option<String>,
69 #[serde(skip_serializing_if = "Option::is_none")]
70 pub content: Option<String>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct LLMResponse {
75 pub id: String,
76 pub object: String,
77 pub created: u64,
78 pub model: String,
79 pub choices: Vec<Choice>,
80 pub usage: Usage,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct Choice {
85 pub index: u32,
86 pub message: ChatMessage,
87 pub finish_reason: Option<String>,
88}
89
90#[derive(Debug, Clone, Serialize, Deserialize)]
91pub struct Usage {
92 pub prompt_tokens: u32,
93 pub completion_tokens: u32,
94 pub total_tokens: u32,
95}
96
97#[async_trait]
98pub trait LLMProvider: Send + Sync {
99 async fn generate(&self, request: LLMRequest) -> Result<LLMResponse>;
100}
101
102pub struct LLMClient {
103 provider: Box<dyn LLMProvider + Send + Sync>,
104 provider_type: LLMProviderType,
105}
106
107impl LLMClient {
108 pub async fn new(provider_type: LLMProviderType) -> Result<Self> {
109 let provider: Box<dyn LLMProvider + Send + Sync> = match &provider_type {
110 LLMProviderType::Remote(config) => Box::new(RemoteLLMClient::new(config.clone())),
111 LLMProviderType::Local(config) => {
112 Box::new(LocalLLMProvider::new(config.clone()).await?)
113 }
114 };
115
116 Ok(Self {
117 provider,
118 provider_type,
119 })
120 }
121
122 pub fn provider_type(&self) -> &LLMProviderType {
123 &self.provider_type
124 }
125}
126
127pub struct RemoteLLMClient {
129 config: LLMConfig,
130 client: Client,
131}
132
133impl RemoteLLMClient {
134 pub fn new(config: LLMConfig) -> Self {
135 Self {
136 config,
137 client: Client::new(),
138 }
139 }
140
141 pub fn config(&self) -> &LLMConfig {
142 &self.config
143 }
144}
145
146fn suppress_output() -> (i32, i32) {
148 let dev_null = File::open("/dev/null").expect("Failed to open /dev/null");
150
151 let stdout_backup = unsafe { libc::dup(1) };
153 let stderr_backup = unsafe { libc::dup(2) };
154
155 unsafe {
157 libc::dup2(dev_null.as_raw_fd(), 1); libc::dup2(dev_null.as_raw_fd(), 2); }
160
161 (stdout_backup, stderr_backup)
162}
163
164fn restore_output(stdout_backup: i32, stderr_backup: i32) {
166 unsafe {
167 libc::dup2(stdout_backup, 1); libc::dup2(stderr_backup, 2); libc::close(stdout_backup);
170 libc::close(stderr_backup);
171 }
172}
173
174pub struct LocalLLMProvider {
175 model: Arc<LlamaModel>,
176}
177
178impl LocalLLMProvider {
179 pub async fn new(config: LocalConfig) -> Result<Self> {
180 let (stdout_backup, stderr_backup) = suppress_output();
182
183 let backend = LlamaBackend::init().map_err(|e| {
185 restore_output(stdout_backup, stderr_backup);
186 HeliosError::LLMError(format!("Failed to initialize llama backend: {:?}", e))
187 })?;
188
189 let model_path = Self::download_model(&config).await.map_err(|e| {
191 restore_output(stdout_backup, stderr_backup);
192 e
193 })?;
194
195 let model_params = LlamaModelParams::default().with_n_gpu_layers(99); let model = LlamaModel::load_from_file(&backend, &model_path, &model_params)
199 .map_err(|e| {
200 restore_output(stdout_backup, stderr_backup);
201 HeliosError::LLMError(format!("Failed to load model: {:?}", e))
202 })?;
203
204 restore_output(stdout_backup, stderr_backup);
206
207 Ok(Self {
208 model: Arc::new(model),
209 })
210 }
211
212 async fn download_model(config: &LocalConfig) -> Result<std::path::PathBuf> {
213 use std::process::Command;
214
215 if let Some(cached_path) = Self::find_model_in_cache(&config.huggingface_repo, &config.model_file) {
217 return Ok(cached_path);
219 }
220
221 let output = Command::new("huggingface-cli")
225 .args(&[
226 "download",
227 &config.huggingface_repo,
228 &config.model_file,
229 "--local-dir",
230 ".cache/models",
231 "--local-dir-use-symlinks",
232 "False",
233 ])
234 .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .output()
237 .map_err(|e| HeliosError::LLMError(format!("Failed to run huggingface-cli: {}", e)))?;
238
239 if !output.status.success() {
240 return Err(HeliosError::LLMError(format!(
241 "Failed to download model: {}",
242 String::from_utf8_lossy(&output.stderr)
243 )));
244 }
245
246 let model_path = std::path::PathBuf::from(".cache/models").join(&config.model_file);
247 if !model_path.exists() {
248 return Err(HeliosError::LLMError(format!(
249 "Model file not found after download: {}",
250 model_path.display()
251 )));
252 }
253
254 Ok(model_path)
255 }
256
257 fn find_model_in_cache(repo: &str, model_file: &str) -> Option<std::path::PathBuf> {
258 let cache_dir = std::env::var("HF_HOME")
260 .map(std::path::PathBuf::from)
261 .unwrap_or_else(|_| {
262 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
263 std::path::PathBuf::from(home).join(".cache").join("huggingface")
264 });
265
266 let hub_dir = cache_dir.join("hub");
267
268 let cache_repo_name = format!("models--{}", repo.replace("/", "--"));
271 let repo_dir = hub_dir.join(&cache_repo_name);
272
273 if !repo_dir.exists() {
274 return None;
275 }
276
277 let snapshots_dir = repo_dir.join("snapshots");
279 if snapshots_dir.exists() {
280 if let Ok(entries) = std::fs::read_dir(&snapshots_dir) {
281 for entry in entries.flatten() {
282 if let Ok(snapshot_path) = entry.path().join(model_file).canonicalize() {
283 if snapshot_path.exists() {
284 return Some(snapshot_path);
285 }
286 }
287 }
288 }
289 }
290
291 let blobs_dir = repo_dir.join("blobs");
293 if blobs_dir.exists() {
294 }
298
299 None
300 }
301
302 fn format_messages(&self, messages: &[ChatMessage]) -> String {
303 let mut formatted = String::new();
304
305 formatted.push_str("<|im_start|>system\n");
307 if let Some(system_msg) = messages.iter().find(|m| m.role == crate::chat::Role::System) {
308 formatted.push_str(&system_msg.content);
309 } else {
310 formatted.push_str("You are a helpful AI assistant. Provide direct, concise answers.");
311 }
312 formatted.push_str("\n<|im_end|>\n");
313
314 if let Some(user_msg) = messages.iter().find(|m| m.role == crate::chat::Role::User) {
316 formatted.push_str(&format!("<|im_start|>user\n{}\n<|im_end|>\n", user_msg.content));
317 }
318
319 formatted.push_str("<|im_start|>assistant\n");
320
321 formatted
322 }
323}
324
325#[async_trait]
326impl LLMProvider for RemoteLLMClient {
327 async fn generate(&self, request: LLMRequest) -> Result<LLMResponse> {
328 let url = format!("{}/chat/completions", self.config.base_url);
329
330 let response = self
331 .client
332 .post(&url)
333 .header("Authorization", format!("Bearer {}", self.config.api_key))
334 .header("Content-Type", "application/json")
335 .json(&request)
336 .send()
337 .await?;
338
339 if !response.status().is_success() {
340 let status = response.status();
341 let error_text = response
342 .text()
343 .await
344 .unwrap_or_else(|_| "Unknown error".to_string());
345 return Err(HeliosError::LLMError(format!(
346 "LLM API request failed with status {}: {}",
347 status, error_text
348 )));
349 }
350
351 let llm_response: LLMResponse = response.json().await?;
352 Ok(llm_response)
353 }
354}
355
356impl RemoteLLMClient {
357 pub async fn chat(
358 &self,
359 messages: Vec<ChatMessage>,
360 tools: Option<Vec<ToolDefinition>>,
361 ) -> Result<ChatMessage> {
362 let request = LLMRequest {
363 model: self.config.model_name.clone(),
364 messages,
365 temperature: Some(self.config.temperature),
366 max_tokens: Some(self.config.max_tokens),
367 tools,
368 tool_choice: None,
369 stream: None,
370 };
371
372 let response = self.generate(request).await?;
373
374 response
375 .choices
376 .into_iter()
377 .next()
378 .map(|choice| choice.message)
379 .ok_or_else(|| HeliosError::LLMError("No response from LLM".to_string()))
380 }
381
382 pub async fn chat_stream<F>(
383 &self,
384 messages: Vec<ChatMessage>,
385 tools: Option<Vec<ToolDefinition>>,
386 mut on_chunk: F,
387 ) -> Result<ChatMessage>
388 where
389 F: FnMut(&str) + Send,
390 {
391 let request = LLMRequest {
392 model: self.config.model_name.clone(),
393 messages,
394 temperature: Some(self.config.temperature),
395 max_tokens: Some(self.config.max_tokens),
396 tools,
397 tool_choice: None,
398 stream: Some(true),
399 };
400
401 let url = format!("{}/chat/completions", self.config.base_url);
402
403 let response = self
404 .client
405 .post(&url)
406 .header("Authorization", format!("Bearer {}", self.config.api_key))
407 .header("Content-Type", "application/json")
408 .json(&request)
409 .send()
410 .await?;
411
412 if !response.status().is_success() {
413 let status = response.status();
414 let error_text = response
415 .text()
416 .await
417 .unwrap_or_else(|_| "Unknown error".to_string());
418 return Err(HeliosError::LLMError(format!(
419 "LLM API request failed with status {}: {}",
420 status, error_text
421 )));
422 }
423
424 let mut stream = response.bytes_stream();
425 let mut full_content = String::new();
426 let mut role = None;
427 let mut buffer = String::new();
428
429 while let Some(chunk_result) = stream.next().await {
430 let chunk = chunk_result?;
431 let chunk_str = String::from_utf8_lossy(&chunk);
432 buffer.push_str(&chunk_str);
433
434 while let Some(line_end) = buffer.find('\n') {
436 let line = buffer[..line_end].trim().to_string();
437 buffer = buffer[line_end + 1..].to_string();
438
439 if line.is_empty() || line == "data: [DONE]" {
440 continue;
441 }
442
443 if let Some(data) = line.strip_prefix("data: ") {
444 match serde_json::from_str::<StreamChunk>(data) {
445 Ok(stream_chunk) => {
446 if let Some(choice) = stream_chunk.choices.first() {
447 if let Some(r) = &choice.delta.role {
448 role = Some(r.clone());
449 }
450 if let Some(content) = &choice.delta.content {
451 full_content.push_str(content);
452 on_chunk(content);
453 }
454 }
455 }
456 Err(e) => {
457 tracing::debug!("Failed to parse stream chunk: {} - Data: {}", e, data);
458 }
459 }
460 }
461 }
462 }
463
464 Ok(ChatMessage {
465 role: crate::chat::Role::from(role.as_deref().unwrap_or("assistant")),
466 content: full_content,
467 name: None,
468 tool_calls: None,
469 tool_call_id: None,
470 })
471 }
472}
473
474#[async_trait]
475impl LLMProvider for LocalLLMProvider {
476 async fn generate(&self, request: LLMRequest) -> Result<LLMResponse> {
477 let prompt = self.format_messages(&request.messages);
478 let model = Arc::clone(&self.model);
479
480 let (stdout_backup, stderr_backup) = suppress_output();
482
483 let result = task::spawn_blocking(move || {
485 let backend = LlamaBackend::init().map_err(|e| {
487 HeliosError::LLMError(format!("Failed to initialize backend: {:?}", e))
488 })?;
489
490 use std::num::NonZeroU32;
492 let ctx_params =
493 LlamaContextParams::default().with_n_ctx(Some(NonZeroU32::new(2048).unwrap()));
494
495 let mut context = model
496 .new_context(&backend, ctx_params)
497 .map_err(|e| HeliosError::LLMError(format!("Failed to create context: {:?}", e)))?;
498
499 let tokens = context
501 .model
502 .str_to_token(&prompt, AddBos::Always)
503 .map_err(|e| HeliosError::LLMError(format!("Tokenization failed: {:?}", e)))?;
504
505 let mut prompt_batch = LlamaBatch::new(tokens.len(), 1);
507 for (i, &token) in tokens.iter().enumerate() {
508 let compute_logits = true; prompt_batch
510 .add(token, i as i32, &[0], compute_logits)
511 .map_err(|e| {
512 HeliosError::LLMError(format!(
513 "Failed to add prompt token to batch: {:?}",
514 e
515 ))
516 })?;
517 }
518
519 context
521 .decode(&mut prompt_batch)
522 .map_err(|e| HeliosError::LLMError(format!("Failed to decode prompt: {:?}", e)))?;
523
524 let mut generated_text = String::new();
526 let max_new_tokens = 128; let mut next_pos = tokens.len() as i32; for _ in 0..max_new_tokens {
530 let logits = context.get_logits();
532
533 let token_idx = logits
534 .iter()
535 .enumerate()
536 .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
537 .map(|(idx, _)| idx)
538 .unwrap_or_else(|| {
539 let eos = context.model.token_eos();
540 eos.0 as usize
541 });
542 let token = LlamaToken(token_idx as i32);
543
544 if token == context.model.token_eos() {
546 break;
547 }
548
549 match context.model.token_to_str(token, Special::Plaintext) {
551 Ok(text) => {
552 generated_text.push_str(&text);
553 },
554 Err(_) => continue, }
556
557 let mut gen_batch = LlamaBatch::new(1, 1);
559 gen_batch.add(token, next_pos, &[0], true).map_err(|e| {
560 HeliosError::LLMError(format!(
561 "Failed to add generated token to batch: {:?}",
562 e
563 ))
564 })?;
565
566 context.decode(&mut gen_batch).map_err(|e| {
568 HeliosError::LLMError(format!("Failed to decode token: {:?}", e))
569 })?;
570
571 next_pos += 1;
572 }
573
574 Ok::<String, HeliosError>(generated_text)
575 })
576 .await
577 .map_err(|e| {
578 restore_output(stdout_backup, stderr_backup);
579 HeliosError::LLMError(format!("Task failed: {}", e))
580 })??;
581
582 restore_output(stdout_backup, stderr_backup);
584
585 let response = LLMResponse {
586 id: format!("local-{}", chrono::Utc::now().timestamp()),
587 object: "chat.completion".to_string(),
588 created: chrono::Utc::now().timestamp() as u64,
589 model: "local-model".to_string(),
590 choices: vec![Choice {
591 index: 0,
592 message: ChatMessage {
593 role: crate::chat::Role::Assistant,
594 content: result,
595 name: None,
596 tool_calls: None,
597 tool_call_id: None,
598 },
599 finish_reason: Some("stop".to_string()),
600 }],
601 usage: Usage {
602 prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, },
606 };
607
608 Ok(response)
609 }
610}
611
612#[async_trait]
613impl LLMProvider for LLMClient {
614 async fn generate(&self, request: LLMRequest) -> Result<LLMResponse> {
615 self.provider.generate(request).await
616 }
617}
618
619impl LLMClient {
620 pub async fn chat(
621 &self,
622 messages: Vec<ChatMessage>,
623 tools: Option<Vec<ToolDefinition>>,
624 ) -> Result<ChatMessage> {
625 let (model_name, temperature, max_tokens) = match &self.provider_type {
626 LLMProviderType::Remote(config) => (
627 config.model_name.clone(),
628 config.temperature,
629 config.max_tokens,
630 ),
631 LLMProviderType::Local(config) => (
632 "local-model".to_string(),
633 config.temperature,
634 config.max_tokens,
635 ),
636 };
637
638 let request = LLMRequest {
639 model: model_name,
640 messages,
641 temperature: Some(temperature),
642 max_tokens: Some(max_tokens),
643 tools,
644 tool_choice: None,
645 stream: None,
646 };
647
648 let response = self.generate(request).await?;
649
650 response
651 .choices
652 .into_iter()
653 .next()
654 .map(|choice| choice.message)
655 .ok_or_else(|| HeliosError::LLMError("No response from LLM".to_string()))
656 }
657
658 pub async fn chat_stream<F>(
659 &self,
660 messages: Vec<ChatMessage>,
661 tools: Option<Vec<ToolDefinition>>,
662 on_chunk: F,
663 ) -> Result<ChatMessage>
664 where
665 F: FnMut(&str) + Send,
666 {
667 match &self.provider_type {
669 LLMProviderType::Remote(config) => {
670 let remote_client = RemoteLLMClient::new(config.clone());
671 remote_client.chat_stream(messages, tools, on_chunk).await
672 }
673 LLMProviderType::Local(_) => {
674 self.chat(messages, tools).await
677 }
678 }
679 }
680}