-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2050 lines (1879 loc) · 62.4 KB
/
main.go
File metadata and controls
2050 lines (1879 loc) · 62.4 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
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
var (
// defaults (same as your zsh script)
defaultBaseURL = "https://integrate.api.nvidia.com/v1"
defaultModel = "openai/gpt-oss-120b"
defaultTemperature = "1"
defaultTopP = "1"
defaultFrequency = "0"
defaultPresence = "0"
defaultMaxTokens = "4096"
defaultStream = "true"
defaultReasoning = "low"
defaultStop = ""
defaultHistorySubdir = ".cache/nvidia-chat"
defaultHistoryLimit = 40
modelsList = []string{
"openai/gpt-oss-120b",
"bytedance/seed-oss-36b-instruct",
"qwen/qwen3-coder-480b-a35b-instruct",
"nvidia/nvidia-nemotron-nano-9b-v2",
"nvidia/llama-3.3-nemotron-super-49b-v1.5",
"mistralai/mistral-nemotron",
"mistralai/mistral-small-24b-instruct",
"deepseek-ai/deepseek-v3.1",
"deepseek-ai/deepseek-r1-distill-qwen-32b",
"deepseek-ai/deepseek-r1-distill-llama-8b",
"deepseek-ai/deepseek-r1-0528",
"qwen/qwen3-next-80b-a3b-instruct",
"qwen/qwen3-next-80b-a3b-thinking",
"moonshotai/kimi-k2-instruct-0905",
"google/codegemma-7b",
"google/gemma-7b",
"mistralai/mixtral-8x22b-instruct-v0.1",
}
apiEnvNames = []string{"NVIDIA_BUILD_AI_ACCESS_TOKEN", "NVIDIA_ACCESS_TOKEN", "ACCESS_TOKEN", "NVIDIA_API_KEY", "API_KEY"}
)
// ModelSettings represents the settings for a single model or the default settings.
// It's a map to flexibly accommodate various parameters across different models.
type ModelSettings map[string]interface{}
// TopLevelSettings holds the overall settings in the conversation file.
type TopLevelSettings struct {
Stream bool `json:"stream"`
HistoryLimit int `json:"history_limit"`
Default ModelSettings `json:"default"`
Models map[string]ModelSettings `json:"models"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
// ConversationFile is the top-level structure for the conversation JSON file.
type ConversationFile struct {
System string `json:"system"`
Settings TopLevelSettings `json:"settings"`
Messages []Message `json:"messages"`
}
func tput(name string) string {
return ""
}
var (
bold = tput("bold")
normal = tput("sgr0")
blue = tput("setaf 4")
green = tput("setaf 2")
red = tput("setaf 1")
)
func printInteractiveHelp() {
var builder strings.Builder
builder.WriteString(fmt.Sprintf("%sInteractive Commands:%s\n", bold, normal))
builder.WriteString(" /help Show this help message.\n")
builder.WriteString(" /exit, /quit Exit the program.\n")
builder.WriteString(" /history Print full conversation JSON.\n")
builder.WriteString(" /clear Clear conversation messages.\n")
builder.WriteString(" /save <file> Save conversation to a new file.\n")
builder.WriteString(" /list List supported models.\n")
builder.WriteString(" /model <model_name> Switch model for the session.\n")
builder.WriteString(" /modelinfo [name] List settings for a model (defaults to current).\n")
builder.WriteString(" /askfor_model_setting Interactively set model parameters.\n")
builder.WriteString(" /persist-settings Save the current session's settings to the conversation file.\n")
builder.WriteString(" /persist-system <file>\n Persist a system prompt from a file.\n")
builder.WriteString(" /exportlast [-t] <file>\n Export last AI response to a markdown file (-t filters thinking).\n")
builder.WriteString(" /exportlastn [-t] <n> <file>\n Export last n AI responses.\n")
builder.WriteString(" /exportn [-t] <n> <file>\n Export the Nth-to-last AI response.\n")
builder.WriteString(" /randomodel Switch to a random supported model.\n\n")
builder.WriteString("For any model setting, you can use `/setting_name <value>` or `/setting_name unset`.\n")
builder.WriteString("For example: `/temperature 0.8`, `/stop unset`\n\n")
fmt.Print(builder.String())
}
func printHelp(cfg map[string]string) {
var builder strings.Builder
// --- Usage ---
builder.WriteString(fmt.Sprintf("%snvidia-chat (go)%s\n", bold, normal))
builder.WriteString("Usage: nvidia-chat [OPTIONS] [CONVERSATION_FILE]\n\n")
builder.WriteString(fmt.Sprintf("If CONVERSATION_FILE is omitted, one will be created at:\n %s/conversation-<timestamp>.json\nand its path will be printed.\n\n", cfg["HISTORY_DIR"]))
// --- General Options ---
builder.WriteString(fmt.Sprintf("%sGeneral Options:%s\n", bold, normal))
builder.WriteString(fmt.Sprintf(" -m, --model NAME Model ID to use (default: %s)\n", defaultModel))
builder.WriteString(" -s, --sys-prompt-file PATH\n Path to system prompt text file (content used for this run).\n")
builder.WriteString(" -S Persist the -s content into the conversation file's 'system' field.\n")
builder.WriteString(" --save-settings Persist current model settings into the conversation file.\n")
builder.WriteString(" -k, --access-token KEY\n Provide API key (overrides environment variables).\n")
builder.WriteString(" --prompt TEXT|FILE|-\n Non-interactive mode: provide a prompt and print the response.\n")
builder.WriteString(" -l, --list List supported models and exit.\n")
builder.WriteString(" --modelinfo NAME Show detailed settings for a specific model and exit.\n")
builder.WriteString(" -h, --help Show this help.\n\n")
// --- Model Setting Options (Dynamic) ---
builder.WriteString(fmt.Sprintf("%sModel Setting Options:%s\n", bold, normal))
builder.WriteString("These flags override settings for the current session. For model-specific ranges and defaults, use `/modelinfo <model_name>`.\n\n")
// Collect all unique parameters from all models
allParams := make(map[string]ModelParameter)
paramOrder := []string{}
for _, modelDef := range ModelDefinitions {
for name, param := range modelDef.Parameters {
if _, exists := allParams[name]; !exists {
allParams[name] = param
paramOrder = append(paramOrder, name)
}
}
}
sort.Strings(paramOrder)
// Add global settings to the list
paramOrder = append([]string{"stream", "history_limit"}, paramOrder...)
allParams["stream"] = ModelParameter{Type: Bool, Default: true, Description: "Enable or disable streaming responses."}
allParams["history_limit"] = ModelParameter{Type: Int, Default: defaultHistoryLimit, Description: "Maximum number of messages in conversation history."}
for _, name := range paramOrder {
param := allParams[name]
flagName := strings.ReplaceAll(name, "_", "-")
builder.WriteString(fmt.Sprintf(" --%s VALUE\n", flagName))
builder.WriteString(fmt.Sprintf(" %s\n", param.Description))
builder.WriteString(fmt.Sprintf(" To unset, use the interactive command: /%s unset\n\n", name))
}
// --- Interactive Commands ---
builder.WriteString(fmt.Sprintf("%sInteractive Commands:%s\n", bold, normal))
builder.WriteString(" /help Show this help message.\n")
builder.WriteString(" /exit, /quit Exit the program.\n")
builder.WriteString(" /history Print full conversation JSON.\n")
builder.WriteString(" /clear Clear conversation messages.\n")
builder.WriteString(" /save <file> Save conversation to a new file.\n")
builder.WriteString(" /model <model_name> Switch model for the session.\n")
builder.WriteString(" /modelinfo <name> List settings for a specific model.\n")
builder.WriteString(" /persist-settings Save the current session's settings to the conversation file.\n")
builder.WriteString(" /persist-system <file>\n Persist a system prompt from a file.\n")
builder.WriteString(" /exportlast [-t] <file>\n Export last AI response to a markdown file (-t filters thinking).\n")
builder.WriteString(" /exportlastn [-t] <n> <file>\n Export last n AI responses.\n")
builder.WriteString(" /exportn [-t] <n> <file>\n Export the Nth-to-last AI response.\n")
builder.WriteString(" /randomodel Switch to a random supported model.\n\n")
builder.WriteString("For any model setting, you can use `/setting_name <value>` or `/setting_name unset`.\n")
builder.WriteString("For example: `/temperature 0.8`, `/stop unset`\n\n")
fmt.Print(builder.String())
}
// helpers
func mustAtoi(s string, def int) int {
if v, err := strconv.Atoi(s); err == nil {
return v
}
return def
}
func mustParseFloat(s string, def float64) float64 {
if v, err := strconv.ParseFloat(s, 64); err == nil {
return v
}
return def
}
func ensureHistoryFileStructure(path string, cfg map[string]string) error {
// if file doesn't exist, create it with defaults
if _, err := os.Stat(path); os.IsNotExist(err) {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
// build default file
stream := cfg["STREAM"] == "true"
limit, _ := strconv.Atoi(cfg["HISTORY_LIMIT"])
// Create default settings based on the generic model definition
defaultSettings := make(ModelSettings)
genericDef := GetModelDefinition("others")
for name, param := range genericDef.Parameters {
defaultSettings[name] = param.Default
}
s := TopLevelSettings{
Stream: stream,
HistoryLimit: limit,
Default: defaultSettings,
Models: make(map[string]ModelSettings),
}
// Add the specific default model to the models map
s.Models[defaultModel] = ModelSettings{
"temperature": mustParseFloat(defaultTemperature, 1.0),
"top_p": mustParseFloat(defaultTopP, 1.0),
"frequency_penalty": mustParseFloat(defaultFrequency, 0),
"presence_penalty": mustParseFloat(defaultPresence, 0),
"max_tokens": mustAtoi(defaultMaxTokens, 4096),
"reasoning_effort": defaultReasoning,
}
cf := ConversationFile{
System: "",
Settings: s,
Messages: []Message{},
}
b, _ := json.MarshalIndent(cf, "", " ")
return ioutil.WriteFile(path, b, 0o644)
}
// file exists: verify shape; if not, back up and recreate
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
var cf ConversationFile
if err := json.Unmarshal(data, &cf); err != nil {
// back up and recreate
backup := path + ".bak." + strconv.FormatInt(time.Now().Unix(), 10)
_ = os.Rename(path, backup)
fmt.Fprintf(os.Stderr, "Warning: Conversation file at %s was malformed. Backed up to %s and creating a new one.\n", path, backup)
return ensureHistoryFileStructure(path, cfg)
}
// Basic validation of structure
if cf.Messages == nil || cf.Settings.Default == nil || cf.Settings.Models == nil {
backup := path + ".bak." + strconv.FormatInt(time.Now().Unix(), 10)
_ = os.Rename(path, backup)
fmt.Fprintf(os.Stderr, "Warning: Conversation file at %s was missing required fields. Backed up to %s and creating a new one.\n", path, backup)
return ensureHistoryFileStructure(path, cfg)
}
return nil
}
func readConversation(path string) (*ConversationFile, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var cf ConversationFile
if err := json.Unmarshal(data, &cf); err != nil {
return nil, err
}
return &cf, nil
}
func writeConversation(path string, cf *ConversationFile) error {
b, err := json.MarshalIndent(cf, "", " ")
if err != nil {
return err
}
tmp := path + ".tmp"
if err := ioutil.WriteFile(tmp, b, 0o644); err != nil {
return err
}
return os.Rename(tmp, path)
}
func appendMessage(path, role, content string) error {
cf, err := readConversation(path)
if err != nil {
return err
}
cf.Messages = append(cf.Messages, Message{Role: role, Content: content})
return writeConversation(path, cf)
}
func messageCount(path string) (int, error) {
cf, err := readConversation(path)
if err != nil {
return 0, err
}
return len(cf.Messages), nil
}
func persistSystemToFile(path, content string) error {
cf, err := readConversation(path)
if err != nil {
return err
}
cf.System = content
return writeConversation(path, cf)
}
func persistSettingsToFile(path string, cfg map[string]string) error {
cf, err := readConversation(path)
if err != nil {
return err
}
modelName := cfg["MODEL"]
modelDef := GetModelDefinition(modelName)
// Get current model settings or initialize if not present
modelSettings, ok := cf.Settings.Models[modelName]
if !ok {
modelSettings = make(ModelSettings)
}
// Update settings for the current model from the session config (cfg)
for key, paramDef := range modelDef.Parameters {
if valStr, ok := cfg[strings.ToUpper(key)]; ok {
// Convert string value from cfg to the correct type
switch paramDef.Type {
case Float:
val, err := strconv.ParseFloat(valStr, 64)
if err == nil {
modelSettings[key] = val
}
case Int:
val, err := strconv.Atoi(valStr)
if err == nil {
modelSettings[key] = val
}
case String, StringA:
modelSettings[key] = valStr
case Bool:
val, err := strconv.ParseBool(valStr)
if err == nil {
modelSettings[key] = val
}
}
}
}
// Save the updated model-specific settings
cf.Settings.Models[modelName] = modelSettings
// Also save global settings
cf.Settings.Stream = cfg["STREAM"] == "true"
cf.Settings.HistoryLimit = mustAtoi(cfg["HISTORY_LIMIT"], defaultHistoryLimit)
return writeConversation(path, cf)
}
func applyFileSettingsAsDefaults(path string, cfg map[string]string, provided map[string]bool) error {
cf, err := readConversation(path)
if err != nil {
return err
}
modelName := cfg["MODEL"]
// Get the settings for the current model, falling back to default settings.
settings, ok := cf.Settings.Models[modelName]
if !ok {
settings = cf.Settings.Default
}
// Apply model-specific settings if they were not provided via CLI flags.
modelDef := GetModelDefinition(modelName)
for key, paramDef := range modelDef.Parameters {
configKey := strings.ToUpper(key)
if !provided[configKey] {
if value, exists := settings[key]; exists {
// Convert the loaded value to a string for the cfg map
switch paramDef.Type {
case Float:
if v, ok := value.(float64); ok {
cfg[configKey] = fmt.Sprintf("%g", v)
}
case Int:
// JSON unmarshals numbers into float64 by default
if v, ok := value.(float64); ok {
cfg[configKey] = fmt.Sprintf("%d", int(v))
} else if v, ok := value.(int); ok {
cfg[configKey] = fmt.Sprintf("%d", v)
}
case String, StringA:
if v, ok := value.(string); ok {
cfg[configKey] = v
}
case Bool:
if v, ok := value.(bool); ok {
cfg[configKey] = strconv.FormatBool(v)
}
}
}
}
}
// Apply global settings
if !provided["STREAM"] {
cfg["STREAM"] = strconv.FormatBool(cf.Settings.Stream)
}
if !provided["HISTORY_LIMIT"] && cf.Settings.HistoryLimit != 0 {
cfg["HISTORY_LIMIT"] = fmt.Sprintf("%d", cf.Settings.HistoryLimit)
}
return nil
}
func validateNumericRanges(cfg map[string]string) error {
// temperature 0..1
t, err := strconv.ParseFloat(cfg["TEMPERATURE"], 64)
if err != nil || t < 0 || t > 1 {
return fmt.Errorf("Invalid temperature (0..1): %s", cfg["TEMPERATURE"])
}
tp, err := strconv.ParseFloat(cfg["TOP_P"], 64)
if err != nil || tp < 0.01 || tp > 1 {
return fmt.Errorf("Invalid top_p (0.01..1): %s", cfg["TOP_P"])
}
freq, err := strconv.ParseFloat(cfg["FREQUENCY_PENALTY"], 64)
if err != nil || freq < -2 || freq > 2 {
return fmt.Errorf("Invalid frequency_penalty (-2..2): %s", cfg["FREQUENCY_PENALTY"])
}
pres, err := strconv.ParseFloat(cfg["PRESENCE_PENALTY"], 64)
if err != nil || pres < -2 || pres > 2 {
return fmt.Errorf("Invalid presence_penalty (-2..2): %s", cfg["PRESENCE_PENALTY"])
}
mt, err := strconv.Atoi(cfg["MAX_TOKENS"])
if err != nil || mt < 1 || mt > 4096 {
return fmt.Errorf("Invalid max_tokens (1..4096): %s", cfg["MAX_TOKENS"])
}
if cfg["REASONING_EFFORT"] != "low" && cfg["REASONING_EFFORT"] != "medium" && cfg["REASONING_EFFORT"] != "high" {
return fmt.Errorf("Invalid reasoning effort (low|medium|high): %s", cfg["REASONING_EFFORT"])
}
if cfg["STREAM"] != "true" && cfg["STREAM"] != "false" {
return fmt.Errorf("Invalid stream flag (true|false): %s", cfg["STREAM"])
}
return nil
}
// buildPayload constructs the JSON payload for the API call based on the current model's definition.
func buildPayload(cfg map[string]string, messages []Message) ([]byte, error) {
modelName := cfg["MODEL"]
modelDef := GetModelDefinition(modelName)
payload := map[string]interface{}{
"model": modelName,
"messages": messages,
"stream": cfg["STREAM"] == "true",
}
for key, paramDef := range modelDef.Parameters {
// Skip parameters that are not part of the API payload (e.g., internal 'thinking' flag)
if paramDef.APIKey == "" {
continue
}
configKey := strings.ToUpper(key)
valStr, ok := cfg[configKey]
if !ok {
continue // Should not happen if cfg is populated correctly from defaults
}
// Convert value and add to payload
switch paramDef.Type {
case Float:
if val, err := strconv.ParseFloat(valStr, 64); err == nil {
payload[paramDef.APIKey] = val
}
case Int:
if val, err := strconv.Atoi(valStr); err == nil {
// Special handling for seed=0, which usually means "omit"
if key == "seed" && val == 0 {
if modelName != "deepseek-ai/deepseek-v3.1" {
continue // Omit for other models
}
}
payload[paramDef.APIKey] = val
}
case String, StringA:
// Don't send empty stop strings
if key == "stop" && valStr == "" {
continue
}
payload[paramDef.APIKey] = valStr
case Bool:
if val, err := strconv.ParseBool(valStr); err == nil {
payload[paramDef.APIKey] = val
}
}
}
// Handle special payload structures like chat_template_kwargs
if modelDef.ChatTemplateKwargsThinking {
if thinking, err := strconv.ParseBool(cfg["THINKING"]); err == nil {
payload["chat_template_kwargs"] = map[string]interface{}{"thinking": thinking}
}
}
// Handle deepseek seed nil case. If seed wasn't in cfg, it won't be in payload yet.
if modelName == "deepseek-ai/deepseek-v3.1" {
if _, exists := payload["seed"]; !exists {
payload["seed"] = nil
}
}
return json.Marshal(payload)
}
// streaming JSON chunk structures (we only extract needed bits)
type ChoiceDelta struct {
Content *string `json:"content,omitempty"`
ReasoningContent *string `json:"reasoning_content,omitempty"`
}
type ChoiceStream struct {
Delta *ChoiceDelta `json:"delta,omitempty"`
Message map[string]interface{} `json:"message,omitempty"` // fallback
}
type StreamChunk struct {
Choices []ChoiceStream `json:"choices"`
}
func handleStream(respBody io.Reader, convFile string) (string, error) {
scanner := bufio.NewScanner(respBody)
assistantTextBuf := &bytes.Buffer{}
inReasoning := false
// Ensure scanner can read very long lines if needed
const maxCapacity = 1024 * 1024
buf := make([]byte, 0, 64*1024)
scanner.Buffer(buf, maxCapacity)
for scanner.Scan() {
line := scanner.Text()
// SSE style: lines may start with "data: "
if strings.HasPrefix(line, "data: ") {
line = strings.TrimPrefix(line, "data: ")
}
line = strings.TrimSpace(line)
if line == "" {
// skip event separators
continue
}
if line == "[DONE]" {
continue
}
// Try to parse JSON chunk
var chunk StreamChunk
if err := json.Unmarshal([]byte(line), &chunk); err != nil {
// Not parsable -> skip
continue
}
if len(chunk.Choices) == 0 {
continue
}
choice := chunk.Choices[0]
// Try delta.reasoning_content and delta.content
var reasoning, content string
if choice.Delta != nil {
if choice.Delta.ReasoningContent != nil {
reasoning = *choice.Delta.ReasoningContent
}
if choice.Delta.Content != nil {
content = *choice.Delta.Content
}
} else {
// fallback: some servers may put content under message
if msg := choice.Message; msg != nil {
if v, ok := msg["reasoning_content"].(string); ok {
reasoning = v
}
if v, ok := msg["content"].(string); ok {
content = v
}
}
}
if reasoning != "" {
if !inReasoning {
fmt.Printf("\n%s\n", green+"[Begin of Assistant Reasoning]"+normal)
assistantTextBuf.WriteString("[Begin of Assistant Reasoning]\n")
inReasoning = true
}
// JSON unmarshal already unescaped sequences; print directly
fmt.Print(reasoning)
assistantTextBuf.WriteString(reasoning)
}
if content != "" {
if inReasoning {
fmt.Printf("\n%s\n\n", green+"[/End of Assistant Reasoning]"+normal)
assistantTextBuf.WriteString("\n[/End of Assistant Reasoning]\n\n")
inReasoning = false
}
fmt.Print(content)
assistantTextBuf.WriteString(content)
}
}
if inReasoning {
fmt.Printf("\n%s\n\n", green+"[/End of Assistant Reasoning]"+normal)
assistantTextBuf.WriteString("\n[/End of Assistant Reasoning]\n\n")
inReasoning = false
}
if err := scanner.Err(); err != nil {
// Non-fatal; return what we have
return assistantTextBuf.String(), err
}
fmt.Println()
return assistantTextBuf.String(), nil
}
func handleNonStream(body []byte) (string, error) {
// try to extract .choices[0].delta.reasoning_content or .choices[0].message.reasoning_content and content fields
var j map[string]interface{}
if err := json.Unmarshal(body, &j); err != nil {
return "", err
}
var reasoning string
var content string
if choices, ok := j["choices"].([]interface{}); ok && len(choices) > 0 {
if first, ok := choices[0].(map[string]interface{}); ok {
// delta.reasoning_content
if delta, ok := first["delta"].(map[string]interface{}); ok {
if rc, ok := delta["reasoning_content"].(string); ok {
reasoning = rc
}
if c, ok := delta["content"].(string); ok {
content = c
}
}
// fallback: message.reasoning_content
if msg, ok := first["message"].(map[string]interface{}); ok {
if rc, ok := msg["reasoning_content"].(string); ok && reasoning == "" {
reasoning = rc
}
if c, ok := msg["content"].(string); ok && content == "" {
content = c
}
}
}
}
outBuf := &bytes.Buffer{}
if reasoning != "" {
fmt.Printf("\n%s\n", green+"[Begin of Assistant Reasoning]"+normal)
fmt.Print(reasoning)
fmt.Printf("\n%s\n\n", green+"[/End of Assistant Reasoning]"+normal)
outBuf.WriteString("[Begin of Assistant Reasoning]\n")
outBuf.WriteString(reasoning)
outBuf.WriteString("\n[End of Assistant Reasoning]\n\n")
}
if content != "" {
fmt.Print(content)
outBuf.WriteString(content)
}
if outBuf.Len() == 0 {
// no assistant content parsed; print raw
fmt.Printf("%s\n", string(body))
return "", errors.New("no assistant content parsed from response")
}
return outBuf.String(), nil
}
// processMessage sends the given userInput as a user message, calls the API (stream or non-stream),
// prints the assistant output and persists the assistant message to convFile.
func processMessage(userInput, convFile string, cfg map[string]string, sysPromptContent, accessToken string) error {
// append user message
if err := appendMessage(convFile, "user", userInput); err != nil {
return fmt.Errorf("append user message: %w", err)
}
// re-check limit
count, err := messageCount(convFile)
if err != nil {
return fmt.Errorf("message count: %w", err)
}
limit, _ := strconv.Atoi(cfg["HISTORY_LIMIT"])
if count > limit {
return fmt.Errorf("after adding your message, the conversation file exceeded the limit (%d)", limit)
}
// Determine effective system prompt: precedence -s content > persisted .system in file > none
effectiveSystem := sysPromptContent
if effectiveSystem == "" {
cf, err := readConversation(convFile)
if err == nil {
effectiveSystem = cf.System
}
}
// Build messages: prepend system prompt if non-empty, then .messages
cf2, err := readConversation(convFile)
if err != nil {
return fmt.Errorf("read conversation: %w", err)
}
var messages []Message
// Handle special thinking-related system messages
modelDef := GetModelDefinition(cfg["MODEL"])
if modelDef.PrependedSystemMessageOnThinking != "" {
thinkingEnabled, _ := strconv.ParseBool(cfg["THINKING"])
if thinkingEnabled {
messages = append(messages, Message{Role: "system", Content: modelDef.PrependedSystemMessageOnThinking})
} else if cfg["MODEL"] == "nvidia/llama-3.3-nemotron-super-49b-v1.5" { // Special case for disabling
messages = append(messages, Message{Role: "system", Content: "/no_think"})
}
}
if effectiveSystem != "" {
messages = append(messages, Message{Role: "system", Content: effectiveSystem})
}
messages = append(messages, cf2.Messages...)
// Build payload
payloadBytes, err := buildPayload(cfg, messages)
if err != nil {
return fmt.Errorf("build payload: %w", err)
}
// Prepare HTTP request
url := cfg["BASE_URL"] + "/chat/completions"
req, _ := http.NewRequest("POST", url, bytes.NewReader(payloadBytes))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 0}
if cfg["STREAM"] == "true" {
// streaming mode
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
if resp.StatusCode >= 400 {
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
return fmt.Errorf("api error: %s\n%s", resp.Status, string(body))
}
assistantText, err := handleStream(resp.Body, convFile)
resp.Body.Close()
if assistantText != "" {
if err2 := appendMessage(convFile, "assistant", assistantText); err2 != nil {
// non-fatal append error, but surface it
return fmt.Errorf("append assistant message: %w", err2)
}
}
return err
} else {
// non-streaming mode
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode >= 400 {
return fmt.Errorf("api error: %s\n%s", resp.Status, string(body))
}
assistantText, _ := handleNonStream(body)
if assistantText != "" {
if err := appendMessage(convFile, "assistant", assistantText); err != nil {
return fmt.Errorf("append assistant message: %w", err)
}
}
return nil
}
}
func getAPIKeyFromEnv() string {
for _, n := range apiEnvNames {
if v := os.Getenv(n); v != "" {
return v
}
}
return ""
}
func readSingleLine(reader io.Reader, delimiters []string, trimDelimiter bool) (string, error) {
if reader == nil {
reader = os.Stdin
}
if len(delimiters) == 0 {
delimiters = []string{"\r\n", "\r", "\n"}
}
br := bufio.NewReader(reader)
var line bytes.Buffer
for {
b, err := br.ReadByte()
if err != nil {
if err == io.EOF {
// If no data was read, propagate EOF
if line.Len() == 0 {
return "", io.EOF
}
// Return last partial line along with EOF
return line.String(), io.EOF
}
return "", err
}
line.WriteByte(b)
for _, delim := range delimiters {
delimBytes := []byte(delim)
if bytes.HasSuffix(line.Bytes(), delimBytes) {
resultBytes := line.Bytes()
if trimDelimiter {
resultBytes = bytes.TrimSuffix(resultBytes, delimBytes)
}
return string(resultBytes), nil
}
}
}
}
func readLines(reader io.Reader, delimiters []string, trimDelimiter bool) ([]string, error) {
if reader == nil {
reader = os.Stdin
}
if len(delimiters) == 0 {
delimiters = []string{"\r\n", "\r", "\n"}
}
lines := make([]string, 0)
var lastErr error
for {
line, err := readSingleLine(reader, delimiters, trimDelimiter)
if err != nil {
lastErr = err
if err == io.EOF {
if line != "" {
lines = append(lines, line)
}
break
}
return nil, err
}
if line != "" || lastErr != io.EOF {
lines = append(lines, line)
}
}
if lastErr != nil && lastErr != io.EOF {
return nil, lastErr
}
return lines, nil
}
func main() {
rand.Seed(time.Now().UnixNano())
// Default cfg map
cfg := map[string]string{
"BASE_URL": defaultBaseURL,
"MODEL": defaultModel,
"TEMPERATURE": defaultTemperature,
"TOP_P": defaultTopP,
"FREQUENCY_PENALTY": defaultFrequency,
"PRESENCE_PENALTY": defaultPresence,
"MAX_TOKENS": defaultMaxTokens,
"STREAM": defaultStream,
"REASONING_EFFORT": defaultReasoning,
"STOP": defaultStop,
"HISTORY_DIR": filepath.Join(os.Getenv("HOME"), defaultHistorySubdir),
"HISTORY_LIMIT": fmt.Sprintf("%d", defaultHistoryLimit),
}
// -----------------------
// Parse options (robust)
// -----------------------
provided := map[string]bool{}
rawArgs := os.Args[1:]
var positionalArgs []string
ACCESS_TOKEN := ""
SYS_PROMPT_FILE := ""
PERSIST_SYSTEM := false
SAVE_SETTINGS := false
LIST_ONLY := false
PROMPT_MODE := "" // for --prompt
MODEL_INFO_FLAG := "" // for --modelinfo
// helper to get next argument (used when flag and its value are separate tokens)
nextArg := func(i *int) (string, error) {
*i++
if *i >= len(rawArgs) {
return "", fmt.Errorf("missing value for %s", rawArgs[*i-1])
}
return rawArgs[*i], nil
}
i := 0
for i < len(rawArgs) {
a := rawArgs[i]
if a == "--" {
// stop parsing flags; remaining args are positional
positionalArgs = append(positionalArgs, rawArgs[i+1:]...)
break
}
if !strings.HasPrefix(a, "-") {
positionalArgs = append(positionalArgs, a)
i++
continue
}
// at this point, 'a' is a flag
key := a
val := ""
// handle --flag=value and -f=value
if strings.Contains(a, "=") {
parts := strings.SplitN(a, "=", 2)
key = parts[0]
val = parts[1]
}
switch key {
// flags that take a value
case "-m", "--model":
if val == "" {
v, err := nextArg(&i)
if err != nil {
fmt.Fprintf(os.Stderr, "%s%s%s\n", red, err.Error(), normal)
os.Exit(1)
}
val = v
}
cfg["MODEL"] = val
provided["MODEL"] = true
case "-T", "--temperature":
if val == "" {
v, err := nextArg(&i)
if err != nil {
fmt.Fprintf(os.Stderr, "%s%s%s\n", red, err.Error(), normal)
os.Exit(1)
}
val = v
}
cfg["TEMPERATURE"] = val
provided["TEMPERATURE"] = true
case "-P", "--top-p":
if val == "" {
v, err := nextArg(&i)
if err != nil {
fmt.Fprintf(os.Stderr, "%s%s%s\n", red, err.Error(), normal)
os.Exit(1)
}
val = v
}
cfg["TOP_P"] = val
provided["TOP_P"] = true
case "-f", "--frequency-penalty":
if val == "" {
v, err := nextArg(&i)
if err != nil {
fmt.Fprintf(os.Stderr, "%s%s%s\n", red, err.Error(), normal)
os.Exit(1)
}
val = v
}
cfg["FREQUENCY_PENALTY"] = val
provided["FREQUENCY_PENALTY"] = true
case "-r", "--presence-penalty":
if val == "" {
v, err := nextArg(&i)
if err != nil {
fmt.Fprintf(os.Stderr, "%s%s%s\n", red, err.Error(), normal)
os.Exit(1)
}
val = v
}
cfg["PRESENCE_PENALTY"] = val
provided["PRESENCE_PENALTY"] = true
case "-M", "--max-tokens":
if val == "" {
v, err := nextArg(&i)
if err != nil {
fmt.Fprintf(os.Stderr, "%s%s%s\n", red, err.Error(), normal)
os.Exit(1)
}
val = v
}