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
|
// Summary: Ollama client against a local server; supports chat responses and streaming via /api/chat.
// Not yet reviewed by a human
package llm
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"hexai/internal/logging"
)
// ollamaClient implements Client against a local Ollama server.
type ollamaClient struct {
httpClient *http.Client
baseURL string
defaultModel string
chatLogger logging.ChatLogger
defaultTemperature *float64
}
type ollamaChatRequest struct {
Model string `json:"model"`
Messages []oaMessage `json:"messages"`
Stream bool `json:"stream"`
Options any `json:"options,omitempty"`
}
type ollamaChatResponse struct {
Message struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"message"`
Done bool `json:"done"`
Error string `json:"error,omitempty"`
}
// Constructor (kept among the first functions by convention)
func newOllama(baseURL, model string, defaultTemp *float64) Client {
if strings.TrimSpace(baseURL) == "" {
baseURL = "http://localhost:11434"
}
if strings.TrimSpace(model) == "" {
model = "qwen3-coder:30b-a3b-q4_K_M`"
}
return ollamaClient{
httpClient: &http.Client{Timeout: 30 * time.Second},
baseURL: strings.TrimRight(baseURL, "/"),
defaultModel: model,
chatLogger: logging.NewChatLogger("ollama"),
defaultTemperature: defaultTemp,
}
}
// TODO: This function is too long and should be refactored for readability and maintainability.
func (c ollamaClient) Chat(ctx context.Context, messages []Message, opts ...RequestOption) (string, error) {
o := Options{Model: c.defaultModel}
for _, opt := range opts {
opt(&o)
}
if o.Model == "" {
o.Model = c.defaultModel
}
start := time.Now()
logMessages := make([]struct {
Role string
Content string
}, len(messages))
for i, m := range messages {
logMessages[i] = struct {
Role string
Content string
}{Role: m.Role, Content: m.Content}
}
c.chatLogger.LogStart(false, o.Model, o.Temperature, o.MaxTokens, o.Stop, logMessages)
req := ollamaChatRequest{Model: o.Model, Stream: false}
req.Messages = make([]oaMessage, len(messages))
for i, m := range messages {
req.Messages[i] = oaMessage{Role: m.Role, Content: m.Content}
}
// Build options map only if any option is set
optsMap := map[string]any{}
if o.Temperature != 0 {
optsMap["temperature"] = o.Temperature
} else if c.defaultTemperature != nil {
optsMap["temperature"] = *c.defaultTemperature
}
if o.MaxTokens > 0 {
optsMap["num_predict"] = o.MaxTokens
}
if len(o.Stop) > 0 {
optsMap["stop"] = o.Stop
}
if len(optsMap) > 0 {
req.Options = optsMap
}
body, err := json.Marshal(req)
if err != nil {
return "", err
}
endpoint := c.baseURL + "/api/chat"
logging.Logf("llm/ollama ", "POST %s", endpoint)
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return "", err
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
logging.Logf("llm/ollama ", "%shttp error after %s: %v%s", logging.AnsiRed, time.Since(start), err, logging.AnsiBase)
return "", err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var apiErr ollamaChatResponse
_ = json.NewDecoder(resp.Body).Decode(&apiErr)
if strings.TrimSpace(apiErr.Error) != "" {
logging.Logf("llm/ollama ", "%sapi error status=%d msg=%s duration=%s%s", logging.AnsiRed, resp.StatusCode, apiErr.Error, time.Since(start), logging.AnsiBase)
return "", fmt.Errorf("ollama error: %s (status %d)", apiErr.Error, resp.StatusCode)
}
logging.Logf("llm/ollama ", "%shttp non-2xx status=%d duration=%s%s", logging.AnsiRed, resp.StatusCode, time.Since(start), logging.AnsiBase)
return "", fmt.Errorf("ollama http error: status %d", resp.StatusCode)
}
var out ollamaChatResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
logging.Logf("llm/ollama ", "%sdecode error after %s: %v%s", logging.AnsiRed, time.Since(start), err, logging.AnsiBase)
return "", err
}
if strings.TrimSpace(out.Message.Content) == "" {
logging.Logf("llm/ollama ", "%sempty content returned duration=%s%s", logging.AnsiRed, time.Since(start), logging.AnsiBase)
return "", errors.New("ollama: empty content")
}
content := out.Message.Content
logging.Logf("llm/ollama ", "success size=%d preview=%s%s%s duration=%s", len(content), logging.AnsiGreen, logging.PreviewForLog(content), logging.AnsiBase, time.Since(start))
return content, nil
}
// Provider metadata
func (c ollamaClient) Name() string { return "ollama" }
func (c ollamaClient) DefaultModel() string { return c.defaultModel }
// Streaming support (optional)
func (c ollamaClient) ChatStream(ctx context.Context, messages []Message, onDelta func(string), opts ...RequestOption) error {
o := Options{Model: c.defaultModel}
for _, opt := range opts {
opt(&o)
}
if o.Model == "" {
o.Model = c.defaultModel
}
start := time.Now()
logMessages := make([]struct {
Role string
Content string
}, len(messages))
for i, m := range messages {
logMessages[i] = struct {
Role string
Content string
}{Role: m.Role, Content: m.Content}
}
c.chatLogger.LogStart(true, o.Model, o.Temperature, o.MaxTokens, o.Stop, logMessages)
req := ollamaChatRequest{Model: o.Model, Stream: true}
req.Messages = make([]oaMessage, len(messages))
for i, m := range messages {
req.Messages[i] = oaMessage{Role: m.Role, Content: m.Content}
}
// Build options map
optsMap := map[string]any{}
if o.Temperature != 0 {
optsMap["temperature"] = o.Temperature
} else if c.defaultTemperature != nil {
optsMap["temperature"] = *c.defaultTemperature
}
if o.MaxTokens > 0 {
optsMap["num_predict"] = o.MaxTokens
}
if len(o.Stop) > 0 {
optsMap["stop"] = o.Stop
}
if len(optsMap) > 0 {
req.Options = optsMap
}
body, err := json.Marshal(req)
if err != nil {
return err
}
endpoint := c.baseURL + "/api/chat"
logging.Logf("llm/ollama ", "POST %s (stream)", endpoint)
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return err
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
logging.Logf("llm/ollama ", "%shttp error after %s: %v%s", logging.AnsiRed, time.Since(start), err, logging.AnsiBase)
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var apiErr ollamaChatResponse
_ = json.NewDecoder(resp.Body).Decode(&apiErr)
if strings.TrimSpace(apiErr.Error) != "" {
logging.Logf("llm/ollama ", "%sapi error status=%d msg=%s duration=%s%s", logging.AnsiRed, resp.StatusCode, apiErr.Error, time.Since(start), logging.AnsiBase)
return fmt.Errorf("ollama error: %s (status %d)", apiErr.Error, resp.StatusCode)
}
logging.Logf("llm/ollama ", "%shttp non-2xx status=%d duration=%s%s", logging.AnsiRed, resp.StatusCode, time.Since(start), logging.AnsiBase)
return fmt.Errorf("ollama http error: status %d", resp.StatusCode)
}
dec := json.NewDecoder(resp.Body)
for {
var ev ollamaChatResponse
if err := dec.Decode(&ev); err != nil {
if errors.Is(err, io.EOF) {
break
}
logging.Logf("llm/ollama ", "%sdecode stream error after %s: %v%s", logging.AnsiRed, time.Since(start), err, logging.AnsiBase)
return err
}
if strings.TrimSpace(ev.Error) != "" {
logging.Logf("llm/ollama ", "%sstream event error: %s%s", logging.AnsiRed, ev.Error, logging.AnsiBase)
return fmt.Errorf("ollama stream error: %s", ev.Error)
}
if s := ev.Message.Content; strings.TrimSpace(s) != "" {
onDelta(s)
}
if ev.Done {
break
}
}
logging.Logf("llm/ollama ", "stream end duration=%s", time.Since(start))
return nil
}
|