|
| 1 | +package ollama |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/labstack/echo/v4" |
| 8 | + "github.com/mudler/LocalAI/core/backend" |
| 9 | + "github.com/mudler/LocalAI/core/config" |
| 10 | + openaiEndpoint "github.com/mudler/LocalAI/core/http/endpoints/openai" |
| 11 | + "github.com/mudler/LocalAI/core/http/middleware" |
| 12 | + "github.com/mudler/LocalAI/core/schema" |
| 13 | + "github.com/mudler/LocalAI/core/templates" |
| 14 | + "github.com/mudler/LocalAI/pkg/model" |
| 15 | + "github.com/mudler/xlog" |
| 16 | +) |
| 17 | + |
| 18 | +// ChatEndpoint handles Ollama-compatible /api/chat requests |
| 19 | +func ChatEndpoint(cl *config.ModelConfigLoader, ml *model.ModelLoader, evaluator *templates.Evaluator, appConfig *config.ApplicationConfig) echo.HandlerFunc { |
| 20 | + return func(c echo.Context) error { |
| 21 | + input, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_LOCALAI_REQUEST).(*schema.OllamaChatRequest) |
| 22 | + if !ok || input.Model == "" { |
| 23 | + return ollamaError(c, 400, "model is required") |
| 24 | + } |
| 25 | + |
| 26 | + cfg, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_MODEL_CONFIG).(*config.ModelConfig) |
| 27 | + if !ok || cfg == nil { |
| 28 | + return ollamaError(c, 400, "model configuration not found") |
| 29 | + } |
| 30 | + |
| 31 | + // Apply Ollama options to config |
| 32 | + applyOllamaOptions(input.Options, cfg) |
| 33 | + |
| 34 | + // Convert Ollama messages to OpenAI format |
| 35 | + openAIMessages := ollamaMessagesToOpenAI(input.Messages) |
| 36 | + |
| 37 | + // Build an OpenAI-compatible request |
| 38 | + openAIReq := &schema.OpenAIRequest{ |
| 39 | + PredictionOptions: schema.PredictionOptions{ |
| 40 | + BasicModelRequest: schema.BasicModelRequest{Model: input.Model}, |
| 41 | + }, |
| 42 | + Messages: openAIMessages, |
| 43 | + Stream: input.IsStream(), |
| 44 | + Context: input.Context, |
| 45 | + Cancel: input.Cancel, |
| 46 | + } |
| 47 | + |
| 48 | + if input.Options != nil { |
| 49 | + openAIReq.Temperature = input.Options.Temperature |
| 50 | + openAIReq.TopP = input.Options.TopP |
| 51 | + openAIReq.TopK = input.Options.TopK |
| 52 | + openAIReq.RepeatPenalty = input.Options.RepeatPenalty |
| 53 | + if input.Options.NumPredict != nil { |
| 54 | + openAIReq.Maxtokens = input.Options.NumPredict |
| 55 | + } |
| 56 | + if len(input.Options.Stop) > 0 { |
| 57 | + openAIReq.Stop = input.Options.Stop |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + predInput := evaluator.TemplateMessages(*openAIReq, openAIReq.Messages, cfg, nil, false) |
| 62 | + xlog.Debug("Ollama Chat - Prompt (after templating)", "prompt_len", len(predInput)) |
| 63 | + |
| 64 | + if input.IsStream() { |
| 65 | + return handleOllamaChatStream(c, input, cfg, ml, cl, appConfig, predInput, openAIReq) |
| 66 | + } |
| 67 | + |
| 68 | + return handleOllamaChatNonStream(c, input, cfg, ml, cl, appConfig, predInput, openAIReq) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +func handleOllamaChatNonStream(c echo.Context, input *schema.OllamaChatRequest, cfg *config.ModelConfig, ml *model.ModelLoader, cl *config.ModelConfigLoader, appConfig *config.ApplicationConfig, predInput string, openAIReq *schema.OpenAIRequest) error { |
| 73 | + startTime := time.Now() |
| 74 | + var result string |
| 75 | + |
| 76 | + cb := func(s string, choices *[]schema.Choice) { |
| 77 | + result = s |
| 78 | + } |
| 79 | + |
| 80 | + _, tokenUsage, _, err := openaiEndpoint.ComputeChoices(openAIReq, predInput, cfg, cl, appConfig, ml, cb, nil) |
| 81 | + if err != nil { |
| 82 | + xlog.Error("Ollama chat inference failed", "error", err) |
| 83 | + return ollamaError(c, 500, fmt.Sprintf("model inference failed: %v", err)) |
| 84 | + } |
| 85 | + |
| 86 | + totalDuration := time.Since(startTime) |
| 87 | + |
| 88 | + resp := schema.OllamaChatResponse{ |
| 89 | + Model: input.Model, |
| 90 | + CreatedAt: time.Now().UTC(), |
| 91 | + Message: schema.OllamaMessage{ |
| 92 | + Role: "assistant", |
| 93 | + Content: result, |
| 94 | + }, |
| 95 | + Done: true, |
| 96 | + DoneReason: "stop", |
| 97 | + TotalDuration: totalDuration.Nanoseconds(), |
| 98 | + PromptEvalCount: tokenUsage.Prompt, |
| 99 | + EvalCount: tokenUsage.Completion, |
| 100 | + } |
| 101 | + |
| 102 | + return c.JSON(200, resp) |
| 103 | +} |
| 104 | + |
| 105 | +func handleOllamaChatStream(c echo.Context, input *schema.OllamaChatRequest, cfg *config.ModelConfig, ml *model.ModelLoader, cl *config.ModelConfigLoader, appConfig *config.ApplicationConfig, predInput string, openAIReq *schema.OpenAIRequest) error { |
| 106 | + c.Response().Header().Set("Content-Type", "application/x-ndjson") |
| 107 | + c.Response().Header().Set("Cache-Control", "no-cache") |
| 108 | + c.Response().Header().Set("Connection", "keep-alive") |
| 109 | + |
| 110 | + startTime := time.Now() |
| 111 | + |
| 112 | + tokenCallback := func(token string, usage backend.TokenUsage) bool { |
| 113 | + chunk := schema.OllamaChatResponse{ |
| 114 | + Model: input.Model, |
| 115 | + CreatedAt: time.Now().UTC(), |
| 116 | + Message: schema.OllamaMessage{ |
| 117 | + Role: "assistant", |
| 118 | + Content: token, |
| 119 | + }, |
| 120 | + Done: false, |
| 121 | + } |
| 122 | + return writeNDJSON(c, chunk) |
| 123 | + } |
| 124 | + |
| 125 | + _, tokenUsage, _, err := openaiEndpoint.ComputeChoices(openAIReq, predInput, cfg, cl, appConfig, ml, func(s string, choices *[]schema.Choice) {}, tokenCallback) |
| 126 | + if err != nil { |
| 127 | + xlog.Error("Ollama chat stream inference failed", "error", err) |
| 128 | + errChunk := schema.OllamaChatResponse{ |
| 129 | + Model: input.Model, |
| 130 | + CreatedAt: time.Now().UTC(), |
| 131 | + Done: true, |
| 132 | + DoneReason: "error", |
| 133 | + } |
| 134 | + writeNDJSON(c, errChunk) |
| 135 | + return nil |
| 136 | + } |
| 137 | + |
| 138 | + // Send final done message |
| 139 | + totalDuration := time.Since(startTime) |
| 140 | + finalChunk := schema.OllamaChatResponse{ |
| 141 | + Model: input.Model, |
| 142 | + CreatedAt: time.Now().UTC(), |
| 143 | + Message: schema.OllamaMessage{Role: "assistant", Content: ""}, |
| 144 | + Done: true, |
| 145 | + DoneReason: "stop", |
| 146 | + TotalDuration: totalDuration.Nanoseconds(), |
| 147 | + PromptEvalCount: tokenUsage.Prompt, |
| 148 | + EvalCount: tokenUsage.Completion, |
| 149 | + } |
| 150 | + writeNDJSON(c, finalChunk) |
| 151 | + |
| 152 | + return nil |
| 153 | +} |
0 commit comments