Repository navigation
Expand file tree
/
Copy pathopenrouter.go
More file actions
392 lines (353 loc) · 14.1 KB
/
Copy pathopenrouter.go
File metadata and controls
392 lines (353 loc) · 14.1 KB
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
package contexting
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
defaultModel = "deepseek/deepseek-v4-flash"
defaultSynonyms = 5
defaultSynonymsMax = 12
defaultHTTPTimeout = 180 * time.Second // HTTP client timeout for API requests (3 min for large batches)
)
var defaultEndpoint = "https://openrouter.ai/api/v1/chat/completions"
type OpenRouterRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Format json.RawMessage `json:"response_format,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
Reasoning json.RawMessage `json:"reasoning,omitempty"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type OpenRouterResponse struct {
Choices []Choice `json:"choices"`
}
type Choice struct {
Message Message `json:"message"`
}
type SynonymResponse map[string][]string
func GetAPIKey() (string, error) {
key := strings.TrimSpace(os.Getenv("OPENROUTER_API_KEY"))
if key == "" {
return "", fmt.Errorf("OPENROUTER_API_KEY environment variable not set")
}
return key, nil
}
func GenerateSynonymsBatch(names []string, apiKey string, model string, endpoint string, temperature float64, maxTokens int, synonymsPerName int) (SynonymResponse, error) {
return GenerateSynonymsBatchWithContext(context.Background(), names, apiKey, model, endpoint, temperature, maxTokens, synonymsPerName, nil, nil)
}
func GenerateSynonymsBatchWithContext(ctx context.Context, names []string, apiKey string, model string, endpoint string, temperature float64, maxTokens int, synonymsMax int, symbols map[string][]string, imports map[string][]string) (SynonymResponse, error) {
for attempt := 0; ; attempt++ {
result, err := generateSynonymsAttempt(ctx, names, apiKey, model, endpoint, temperature, maxTokens, synonymsMax, symbols, imports)
var status *llmStatusError
if err == nil || attempt == 2 || !errors.As(err, &status) || (status.code != 429 && status.code < 500) {
return result, err
}
timer := time.NewTimer(time.Duration(attempt+1) * time.Second)
select {
case <-ctx.Done():
timer.Stop()
return nil, ctx.Err()
case <-timer.C:
}
}
}
type llmStatusError struct{ code int }
func (e *llmStatusError) Error() string {
return fmt.Sprintf("LLM request failed with HTTP status %d", e.code)
}
func generateSynonymsAttempt(ctx context.Context, names []string, apiKey string, model string, endpoint string, temperature float64, maxTokens int, synonymsMax int, symbols map[string][]string, imports map[string][]string) (SynonymResponse, error) {
if len(names) == 0 {
return make(SynonymResponse), nil
}
if model == "" {
model = defaultModel
}
if endpoint == "" {
endpoint = defaultEndpoint
}
parsedEndpoint, err := url.ParseRequestURI(endpoint)
if err != nil || parsedEndpoint.Host == "" || (parsedEndpoint.Scheme != "https" && parsedEndpoint.Scheme != "http") {
return nil, fmt.Errorf("invalid LLM endpoint: use an HTTP or HTTPS URL")
}
if parsedEndpoint.User != nil {
return nil, fmt.Errorf("invalid LLM endpoint: embedded credentials are not supported")
}
if parsedEndpoint.Scheme == "http" && !isLoopbackHost(parsedEndpoint.Hostname()) {
return nil, fmt.Errorf("insecure remote LLM endpoint: use HTTPS (HTTP is allowed only for loopback)")
}
if synonymsMax <= 0 {
synonymsMax = defaultSynonymsMax
}
systemPrompt := fmt.Sprintf(
"You generate search phrases that help a developer find each source file or folder without knowing its name. Generate up to %d phrases per entry. Include only phrases that add real search value; fewer well-supported phrases are better than a longer list.\n\n"+
"For every phrase, ask: could a developer plausibly type this to find this specific entry? Keep it only when the filename, symbols, or imports support that connection.\n"+
"Describe distinct search intents: the entry's concrete responsibility, domain, and actions. Use both nouns and verbs when each gives a different way to find it. Prefer specific developer language over broad conceptual associations.\n\n"+
"Do not pad the list. Exclude vague associations, generic software terms, guesses, duplicate concepts, symbol names, misspellings, file extensions, and phrases that merely repeat or mechanically reword the filename. When evidence is limited, use only specific responsibilities supported by the input; do not invent extra purposes to meet the requested count.\n\n"+
"Symbols indicate what the code defines and can reveal its responsibilities. Imports can suggest a domain, but are supporting evidence only: a common library alone does not prove what a file does. Describe what this entry itself implements; do not assign it responsibilities merely because it imports a dependency that implements them. If the name is generic and symbols/imports provide little context, avoid guessing a specific purpose.\n\n"+
"Example: for a file named \"quota.go\" with symbols \"ReserveTokens, ReleaseTokens\" and import \"redis\", useful phrases could be [\"reserve capacity\", \"release unused budget\"]. These inputs alone do not establish request throttling or rate-limit enforcement. Each phrase should describe a distinct search intent; do not add near-duplicates to reach a longer list.\n\n"+
"Return ONLY a valid JSON object. Each key must exactly match an input name, and each value must be a nonempty array of at most %d strings. There is no minimum phrase count beyond one; do not pad the list. No markdown, prose, or extra text.",
synonymsMax,
synonymsMax,
)
// Build user content with symbols and imports when available
var lines []string
for _, name := range names {
var parts []string
parts = append(parts, name)
if syns, ok := symbols[name]; ok && len(syns) > 0 {
// Cap symbols at 10 per file to avoid excessive token use
if len(syns) > 10 {
syns = syns[:10]
}
parts = append(parts, fmt.Sprintf("[symbols: %s]", strings.Join(syns, ", ")))
}
if imps, ok := imports[name]; ok && len(imps) > 0 {
// Cap imports at 5 per file — top dependencies are usually the most
// domain-revealing; rest is noise.
if len(imps) > 5 {
imps = imps[:5]
}
parts = append(parts, fmt.Sprintf("[imports: %s]", strings.Join(imps, ", ")))
}
lines = append(lines, strings.Join(parts, " "))
}
userContent := fmt.Sprintf("File and folder names with their code symbols and imports:\n%s", strings.Join(lines, "\n"))
reqBody := OpenRouterRequest{
Model: model,
Messages: []Message{
{Role: "system", Content: systemPrompt},
{Role: "user", Content: userContent},
},
Format: json.RawMessage(`{"type":"json_object"}`),
Reasoning: json.RawMessage(`{"exclude":true}`),
}
if temperature > 0 {
reqBody.Temperature = &temperature
}
if maxTokens > 0 {
reqBody.MaxTokens = &maxTokens
}
jsonBody, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(jsonBody))
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
if apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("HTTP-Referer", "https://github.com/ktappdev/contexting")
req.Header.Set("X-Title", "Contexting")
client := &http.Client{Timeout: defaultHTTPTimeout}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, &llmStatusError{code: resp.StatusCode}
}
var apiResp OpenRouterResponse
if err := json.NewDecoder(io.LimitReader(resp.Body, 8<<20)).Decode(&apiResp); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if len(apiResp.Choices) == 0 {
return nil, fmt.Errorf("LLM returned no choices")
}
content := strings.TrimSpace(apiResp.Choices[0].Message.Content)
if content == "" {
return nil, fmt.Errorf("LLM returned empty content")
}
var synonyms SynonymResponse
if err := json.Unmarshal([]byte(content), &synonyms); err != nil {
// Try to fix common LLM JSON issues (trailing commas, extra text)
fixed := sanitizeJSON(content)
if err2 := json.Unmarshal([]byte(fixed), &synonyms); err2 != nil {
return nil, fmt.Errorf("parse synonyms JSON: %w", err)
}
}
filtered := make(SynonymResponse)
var missing []string
for _, name := range names {
values := sanitizeSynonyms(synonyms[name], synonymsMax)
if len(values) == 0 {
missing = append(missing, name)
continue
}
filtered[name] = values
}
if len(missing) > 0 {
return filtered, fmt.Errorf("LLM omitted synonyms for %d requested names", len(missing))
}
return filtered, nil
}
func isLoopbackHost(host string) bool {
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
func GenerateSynonymsForNames(names []string, apiKey string, batchSize int, model string, endpoint string, temperature float64, maxTokens int, synonymsMax int) (SynonymResponse, error) {
return GenerateSynonymsForNamesWithContext(context.Background(), names, apiKey, batchSize, model, endpoint, temperature, maxTokens, synonymsMax, 1, nil, nil)
}
func GenerateSynonymsForNamesWithContext(ctx context.Context, names []string, apiKey string, batchSize int, model string, endpoint string, temperature float64, maxTokens int, synonymsMax int, parallelLimit int, symbols map[string][]string, imports map[string][]string) (SynonymResponse, error) {
if len(names) == 0 {
return make(SynonymResponse), nil
}
if model == "" {
model = defaultModel
}
if synonymsMax <= 0 {
synonymsMax = defaultSynonymsMax
}
if parallelLimit <= 0 {
parallelLimit = 1
}
// Smart batching: 0 means "auto" — up to 60 names per request
if batchSize <= 0 {
if len(names) <= 60 {
batchSize = len(names)
} else {
numBatches := (len(names) + 59) / 60
batchSize = (len(names) + numBatches - 1) / numBatches
}
}
if batchSize >= len(names) {
LogInfof(" Synonyms: processing %d names...", len(names))
return GenerateSynonymsBatchWithContext(ctx, names, apiKey, model, endpoint, temperature, maxTokens, synonymsMax, symbols, imports)
}
totalBatches := (len(names) + batchSize - 1) / batchSize
LogInfof(" Synonyms: %d names in %d batches (parallel=%d)", len(names), totalBatches, parallelLimit)
result := make(SynonymResponse)
sem := make(chan struct{}, parallelLimit)
var wg sync.WaitGroup
var mu sync.Mutex
var completed int32
var batchErrors []error
for i := 0; i < len(names); i += batchSize {
batchNum := i/batchSize + 1
end := i + batchSize
if end > len(names) {
end = len(names)
}
batchNames := names[i:end]
// Filter symbols and imports maps for this batch
batchSymbols := make(map[string][]string)
for _, name := range batchNames {
if syns, ok := symbols[name]; ok {
batchSymbols[name] = syns
}
}
batchImports := make(map[string][]string)
for _, name := range batchNames {
if imps, ok := imports[name]; ok {
batchImports[name] = imps
}
}
wg.Add(1)
go func(batchNum int, batchNames []string, batchSymbols map[string][]string, batchImports map[string][]string) {
defer wg.Done()
select {
case sem <- struct{}{}:
case <-ctx.Done():
return
}
defer func() { <-sem }()
synonyms, err := GenerateSynonymsBatchWithContext(ctx, batchNames, apiKey, model, endpoint, temperature, maxTokens, synonymsMax, batchSymbols, batchImports)
mu.Lock()
if err != nil {
batchErrors = append(batchErrors, fmt.Errorf("batch %d: %w", batchNum, err))
}
for name, values := range synonyms {
result[name] = values
}
mu.Unlock()
finished := atomic.AddInt32(&completed, 1)
if err != nil {
LogWarnf(" Synonyms: %d/%d batches finished — batch %d failed (%d names): %v", finished, totalBatches, batchNum, len(batchNames), err)
return
}
LogInfof(" Synonyms: %d/%d batches finished — batch %d completed (%d names)", finished, totalBatches, batchNum, len(batchNames))
}(batchNum, batchNames, batchSymbols, batchImports)
}
wg.Wait()
LogInfof(" Synonyms: %d names processed", len(result))
return result, errors.Join(append(batchErrors, ctx.Err())...)
}
// sanitizeJSON fixes common LLM JSON output issues.
// Handles: markdown wrapping, trailing commas, mismatched brackets/braces,
// truncated JSON (missing closing brackets), and extra trailing characters.
func sanitizeJSON(s string) string {
// Extract just the JSON object if wrapped in markdown or extra text
if idx := strings.Index(s, "{"); idx > 0 {
s = s[idx:]
}
if idx := strings.LastIndex(s, "}"); idx >= 0 && idx < len(s)-1 {
s = s[:idx+1]
}
// Remove trailing commas before } or ]
s = strings.ReplaceAll(s, ",]", "]")
s = strings.ReplaceAll(s, ",}", "}")
// Fix mismatched brackets: track expected close chars and fix wrong ones
fixed := make([]byte, 0, len(s))
var stack []byte
for i := 0; i < len(s); i++ {
ch := s[i]
switch ch {
case '{':
stack = append(stack, '}')
fixed = append(fixed, ch)
case '[':
stack = append(stack, ']')
fixed = append(fixed, ch)
case '}', ']':
if len(stack) > 0 && stack[len(stack)-1] == ch {
stack = stack[:len(stack)-1]
fixed = append(fixed, ch)
} else if len(stack) > 0 {
// Mismatched bracket: replace with expected close
fixed = append(fixed, stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
// If stack empty and extra close char, skip it
default:
fixed = append(fixed, ch)
}
}
// Close any unclosed brackets (truncated JSON)
for i := len(stack) - 1; i >= 0; i-- {
fixed = append(fixed, stack[i])
}
s = string(fixed)
// Remove stray backslashes before structural JSON characters
// These sequences are never valid in JSON and indicate LLM hallucination
s = strings.ReplaceAll(s, "\\,", ",")
s = strings.ReplaceAll(s, "\\]", "]")
s = strings.ReplaceAll(s, "\\}", "}")
s = strings.ReplaceAll(s, "\\[", "[")
s = strings.ReplaceAll(s, "\\{", "{")
// Remove trailing commas again after fixes
s = strings.ReplaceAll(s, ",]", "]")
s = strings.ReplaceAll(s, ",}", "}")
return s
}