localgpt-server 0.3.4

LocalGPT HTTP server and Telegram bot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! OpenAI-compatible HTTP API
//!
//! Provides `/v1/chat/completions` and `/v1/models` endpoints that match
//! the OpenAI wire format, enabling integration with tools like Cursor,
//! Continue, Open WebUI, LibreChat, and the Python `openai` library.

use anyhow::Result;
use axum::{
    extract::State,
    http::StatusCode,
    response::{
        IntoResponse, Json, Response,
        sse::{Event, Sse},
    },
};
use futures::stream::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::convert::Infallible;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::{debug, info, warn};
use uuid::Uuid;

use localgpt_core::agent::{
    Agent, AgentConfig, LLMResponse, LLMResponseContent, Message, Role, StreamEvent, ToolCall,
    ToolSchema,
};
use localgpt_core::config::Config;

use crate::http::AppState;

// ============================================================================
// Request/Response Types (OpenAI Wire Format)
// ============================================================================

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct ChatCompletionRequest {
    pub model: String,
    pub messages: Vec<OaiMessage>,
    #[serde(default)]
    pub stream: bool,
    pub max_tokens: Option<usize>,
    pub temperature: Option<f64>,
    pub tools: Option<Vec<OaiToolDef>>,
    /// Map of tool_choice options: "auto", "none", or {"type": "function", "function": {"name": "..."}}
    pub tool_choice: Option<Value>,
}

#[derive(Debug, Deserialize, Clone)]
#[allow(dead_code)]
pub struct OaiMessage {
    pub role: String,
    pub content: Option<String>,
    pub tool_calls: Option<Vec<OaiToolCallResponse>>,
    pub tool_call_id: Option<String>,
    /// For assistant messages with tool calls, the content might be null or string
    #[serde(default)]
    pub name: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct OaiToolCallResponse {
    pub id: String,
    #[serde(rename = "type")]
    pub tool_type: Option<String>,
    pub function: OaiFunctionCall,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct OaiFunctionCall {
    pub name: String,
    pub arguments: String,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct OaiToolDef {
    #[serde(rename = "type")]
    pub tool_type: String,
    pub function: OaiFunctionDef,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct OaiFunctionDef {
    pub name: String,
    pub description: Option<String>,
    pub parameters: Option<Value>,
}

#[derive(Debug, Serialize)]
pub struct ChatCompletionResponse {
    pub id: String,
    pub object: &'static str,
    pub created: u64,
    pub model: String,
    pub choices: Vec<Choice>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<OaiUsage>,
}

#[derive(Debug, Serialize)]
pub struct Choice {
    pub index: usize,
    pub message: OaiResponseMessage,
    pub finish_reason: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct OaiResponseMessage {
    pub role: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<OaiToolCallResponse>>,
}

#[derive(Debug, Serialize)]
pub struct OaiUsage {
    pub prompt_tokens: u64,
    pub completion_tokens: u64,
    pub total_tokens: u64,
}

#[derive(Debug, Serialize)]
pub struct ChatCompletionChunk {
    pub id: String,
    pub object: &'static str,
    pub created: u64,
    pub model: String,
    pub choices: Vec<ChunkChoice>,
}

#[derive(Debug, Serialize)]
pub struct ChunkChoice {
    pub index: usize,
    pub delta: ChunkDelta,
    pub finish_reason: Option<String>,
}

#[derive(Debug, Serialize, Default)]
pub struct ChunkDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<OaiToolCallChunk>>,
}

#[derive(Debug, Serialize)]
pub struct OaiToolCallChunk {
    pub index: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "type")]
    pub tool_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function: Option<OaiFunctionCallChunk>,
}

#[derive(Debug, Serialize)]
pub struct OaiFunctionCallChunk {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct ModelsResponse {
    pub object: &'static str,
    pub data: Vec<ModelInfo>,
}

#[derive(Debug, Serialize)]
pub struct ModelInfo {
    pub id: String,
    pub object: &'static str,
    pub created: u64,
    pub owned_by: String,
}

// ============================================================================
// Message Conversion
// ============================================================================

/// Convert OpenAI messages to LocalGPT Message format
fn convert_messages(oai_messages: &[OaiMessage]) -> Result<Vec<Message>> {
    let mut messages = Vec::new();

    for msg in oai_messages {
        let role = match msg.role.to_lowercase().as_str() {
            "system" => Role::System,
            "user" => Role::User,
            "assistant" => Role::Assistant,
            "tool" => Role::Tool,
            other => {
                // Default unknown roles to user
                debug!("Unknown role '{}', treating as user", other);
                Role::User
            }
        };

        // Convert tool calls from OpenAI format to LocalGPT format
        let tool_calls = msg.tool_calls.as_ref().map(|calls| {
            calls
                .iter()
                .map(|tc| ToolCall {
                    id: tc.id.clone(),
                    name: tc.function.name.clone(),
                    arguments: tc.function.arguments.clone(),
                })
                .collect()
        });

        messages.push(Message {
            role,
            content: msg.content.clone().unwrap_or_default(),
            tool_calls,
            tool_call_id: msg.tool_call_id.clone(),
            images: Vec::new(),
        });
    }

    Ok(messages)
}

/// Convert OpenAI tool definitions to LocalGPT ToolSchema
fn convert_tools(oai_tools: &[OaiToolDef]) -> Vec<ToolSchema> {
    oai_tools
        .iter()
        .map(|t| ToolSchema {
            name: t.function.name.clone(),
            description: t.function.description.clone().unwrap_or_default(),
            parameters: t.function.parameters.clone().unwrap_or(json!({})),
        })
        .collect()
}

/// Get current Unix timestamp
fn unix_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

/// Generate a unique completion ID
fn generate_completion_id() -> String {
    format!("chatcmpl-{}", Uuid::new_v4().simple())
}

// ============================================================================
// Handlers
// ============================================================================

/// Handle POST /v1/chat/completions
pub async fn chat_completions(
    State(state): State<Arc<AppState>>,
    Json(req): Json<ChatCompletionRequest>,
) -> Result<Response, (StatusCode, String)> {
    if req.stream {
        return chat_completions_stream(state, req)
            .await
            .map(|r| r.into_response());
    }

    chat_completions_non_stream(state, req)
        .await
        .map(|r| r.into_response())
}

/// Non-streaming chat completion
async fn chat_completions_non_stream(
    state: Arc<AppState>,
    req: ChatCompletionRequest,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let messages = convert_messages(&req.messages)
        .map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid messages: {}", e)))?;

    let tools = req.tools.as_ref().map(|t| convert_tools(t));

    // Create a fresh agent for this request
    let agent_config = AgentConfig {
        model: req.model.clone(),
        context_window: state.config.agent.context_window,
        reserve_tokens: state.config.agent.reserve_tokens,
    };

    let memory = Arc::new(state.memory.clone());
    let mut agent = Agent::new(agent_config, &state.config, memory)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to create agent: {}", e),
            )
        })?;

    info!("OpenAI API: non-streaming request for model {}", req.model);

    // Call the provider
    let response = agent
        .chat_with_messages(&messages, tools.as_deref())
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("LLM error: {}", e),
            )
        })?;

    // Convert response
    let completion = to_completion_response(response, &req.model);

    Ok(Json(completion))
}

/// Streaming chat completion (SSE)
async fn chat_completions_stream(
    state: Arc<AppState>,
    req: ChatCompletionRequest,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    // Extract the last user message for streaming
    let last_message = req
        .messages
        .iter()
        .rev()
        .find(|m| m.role == "user")
        .and_then(|m| m.content.clone())
        .unwrap_or_default();

    let model = req.model.clone();
    let completion_id = generate_completion_id();
    let created = unix_timestamp();

    // Create a fresh agent for this request
    let agent_config = AgentConfig {
        model: model.clone(),
        context_window: state.config.agent.context_window,
        reserve_tokens: state.config.agent.reserve_tokens,
    };

    let memory = Arc::new(state.memory.clone());

    info!("OpenAI API: streaming request for model {}", model);

    // The agent must live for the duration of the stream, so we create the stream
    // in an async_stream that owns both the agent and the inner event stream.
    let event_stream = create_sse_stream_owned(
        agent_config,
        state.config.clone(),
        memory,
        last_message,
        completion_id,
        created,
        model,
    );

    Ok(Sse::new(event_stream).keep_alive(
        axum::response::sse::KeepAlive::new()
            .interval(std::time::Duration::from_secs(15))
            .text(""),
    ))
}

/// Create an SSE stream that owns its agent and handles the full lifecycle.
fn create_sse_stream_owned(
    agent_config: AgentConfig,
    config: Config,
    memory: Arc<localgpt_core::memory::MemoryManager>,
    message: String,
    completion_id: String,
    created: u64,
    model: String,
) -> impl Stream<Item = Result<Event, Infallible>> {
    async_stream::try_stream! {
        // Create agent inside the stream so it lives for the stream's duration
        let mut agent = match Agent::new(agent_config, &config, memory).await {
            Ok(a) => a,
            Err(e) => {
                warn!("Failed to create agent for streaming: {}", e);
                yield Event::default().data("[DONE]");
                return;
            }
        };

        let event_stream = match agent.chat_stream_with_tools(&message, Vec::new()).await {
            Ok(s) => s,
            Err(e) => {
                warn!("Failed to start stream: {}", e);
                yield Event::default().data("[DONE]");
                return;
            }
        };

        let mut stream = std::pin::pin!(event_stream);

        // Send initial chunk with role
        let initial = ChatCompletionChunk {
            id: completion_id.clone(),
            object: "chat.completion.chunk",
            created,
            model: model.clone(),
            choices: vec![ChunkChoice {
                index: 0,
                delta: ChunkDelta {
                    role: Some("assistant".to_string()),
                    content: None,
                    tool_calls: None,
                },
                finish_reason: None,
            }],
        };
        yield Event::default().json_data(initial).unwrap();

        let mut tool_call_index: usize = 0;

        while let Some(event) = stream.next().await {
            match event {
                Ok(StreamEvent::Content(text)) => {
                    let chunk = ChatCompletionChunk {
                        id: completion_id.clone(),
                        object: "chat.completion.chunk",
                        created,
                        model: model.clone(),
                        choices: vec![ChunkChoice {
                            index: 0,
                            delta: ChunkDelta {
                                role: None,
                                content: Some(text),
                                tool_calls: None,
                            },
                            finish_reason: None,
                        }],
                    };
                    yield Event::default().json_data(chunk).unwrap();
                }
                Ok(StreamEvent::ToolCallStart { name, id, arguments: _ }) => {
                    let chunk = ChatCompletionChunk {
                        id: completion_id.clone(),
                        object: "chat.completion.chunk",
                        created,
                        model: model.clone(),
                        choices: vec![ChunkChoice {
                            index: 0,
                            delta: ChunkDelta {
                                role: None,
                                content: None,
                                tool_calls: Some(vec![OaiToolCallChunk {
                                    index: tool_call_index,
                                    id: Some(id),
                                    tool_type: Some("function".to_string()),
                                    function: Some(OaiFunctionCallChunk {
                                        name: Some(name),
                                        arguments: None,
                                    }),
                                }]),
                            },
                            finish_reason: None,
                        }],
                    };
                    yield Event::default().json_data(chunk).unwrap();
                    tool_call_index += 1;
                }
                Ok(StreamEvent::ToolCallEnd { .. }) => {
                    // Tool call finished - the output will be processed internally
                    // We don't need to send anything special for the end
                }
                Ok(StreamEvent::Done) => {
                    // Send final chunk with finish_reason
                    let finish_chunk = ChatCompletionChunk {
                        id: completion_id.clone(),
                        object: "chat.completion.chunk",
                        created,
                        model: model.clone(),
                        choices: vec![ChunkChoice {
                            index: 0,
                            delta: ChunkDelta::default(),
                            finish_reason: Some("stop".to_string()),
                        }],
                    };
                    yield Event::default().json_data(finish_chunk).unwrap();
                    break;
                }
                Err(e) => {
                    warn!("Stream error: {}", e);
                    break;
                }
            }
        }

        // Send [DONE] marker
        yield Event::default().data("[DONE]");
    }
}

/// Handle GET /v1/models
pub async fn list_models(
    State(state): State<Arc<AppState>>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let mut models = Vec::new();

    // Add the default model
    let default_model = &state.config.agent.default_model;
    models.push(ModelInfo {
        id: default_model.clone(),
        object: "model",
        created: 0,
        owned_by: "localgpt".to_string(),
    });

    // Add fallback models
    for model in &state.config.agent.fallback_models {
        models.push(ModelInfo {
            id: model.clone(),
            object: "model",
            created: 0,
            owned_by: "localgpt".to_string(),
        });
    }

    // Add configured provider models
    if let Some(ollama) = &state.config.providers.ollama {
        models.push(ModelInfo {
            id: format!("ollama/{}", ollama.model),
            object: "model",
            created: 0,
            owned_by: "ollama".to_string(),
        });
    }

    Ok(Json(ModelsResponse {
        object: "list",
        data: models,
    }))
}

// ============================================================================
// Response Conversion
// ============================================================================

/// Convert LocalGPT LLMResponse to OpenAI ChatCompletionResponse
fn to_completion_response(response: LLMResponse, model: &str) -> ChatCompletionResponse {
    let (content, tool_calls, finish_reason) = match response.content {
        LLMResponseContent::Text(text) => (Some(text), None, "stop"),
        LLMResponseContent::ToolCalls { calls, text } => {
            let oai_calls: Vec<OaiToolCallResponse> = calls
                .iter()
                .map(|c| OaiToolCallResponse {
                    id: c.id.clone(),
                    tool_type: Some("function".to_string()),
                    function: OaiFunctionCall {
                        name: c.name.clone(),
                        arguments: c.arguments.clone(),
                    },
                })
                .collect();
            (text, Some(oai_calls), "tool_calls")
        }
    };

    let usage = response.usage.map(|u| OaiUsage {
        prompt_tokens: u.input_tokens,
        completion_tokens: u.output_tokens,
        total_tokens: u.total(),
    });

    ChatCompletionResponse {
        id: generate_completion_id(),
        object: "chat.completion",
        created: unix_timestamp(),
        model: model.to_string(),
        choices: vec![Choice {
            index: 0,
            message: OaiResponseMessage {
                role: "assistant".to_string(),
                content,
                tool_calls,
            },
            finish_reason: Some(finish_reason.to_string()),
        }],
        usage,
    }
}