code cleanup of early drafts of code from Gemini AI

This commit is contained in:
Jeff Carr 2025-08-30 15:15:43 -05:00
parent 7f8f5e3b9b
commit c7896e47f9
12 changed files with 53 additions and 226 deletions

1
.gitignore vendored
View File

@ -4,3 +4,4 @@ go.sum
/resources/*.so /resources/*.so
/files/* /files/*
regex regex
/tmp/*

View File

@ -2,7 +2,7 @@ VERSION = $(shell git describe --tags)
BUILDTIME = $(shell date +%Y.%m.%d_%H%M) BUILDTIME = $(shell date +%Y.%m.%d_%H%M)
default: install default: install
regex --json /tmp/regex.55128216-e93b-4339-8854-622ca11af890.gemini-api-request.99.json connect regex --json /tmp/regex.55128216-e93b-4339-8854-622ca11af890.gemini-api-request.128.json
vet: vet:
@GO111MODULE=off go vet @GO111MODULE=off go vet
@ -55,5 +55,5 @@ playback:
regex playback regex playback
# regex playback --uuid a1b2c3d4-e5f6-4a5b-8c9d-1e2f3a4b5c6d # regex playback --uuid a1b2c3d4-e5f6-4a5b-8c9d-1e2f3a4b5c6d
tmp: tmpfiles:
ls -tl /tmp/regex.* |head ls -tl /tmp/regex.* |head

27
argv.go
View File

@ -10,24 +10,15 @@ package main
var argv args var argv args
type args struct { type args struct {
Add string `arg:"--add" help:"add a new chat"` Uuid string `arg:"--uuid" help:"look at this uuid"`
Format *EmptyCmd `arg:"subcommand:format" help:"add a conversation"` JsonFile string `arg:"--json" help:"import a JSON file from gemini-cli"`
Connect *EmptyCmd `arg:"subcommand:connect" help:"connect to gemini AI"` Interact *EmptyCmd `arg:"subcommand:interact" help:"open env EDITOR"`
Playback *PlaybackCmd `arg:"subcommand:playback" help:"dump your prior conversations to the terminal'"` Playback *PlaybackCmd `arg:"subcommand:playback" help:"dump your prior conversations to the terminal'"`
Output string `arg:"--output" help:"should get a string from regex-cli"` Stats string `arg:"--stats" help:"add stats to a chat"`
Input string `arg:"--input" help:"should get a string from regex-cli"` Force bool `arg:"--force" help:"try to strong arm things"`
Editor *EmptyCmd `arg:"subcommand:interact" help:"open env EDITOR"` Verbose bool `arg:"--verbose" help:"show more output"`
ImportFile string `arg:"--import" help:"import a file from regex-cli"` Bash bool `arg:"--bash" help:"generate bash completion"`
JsonFile string `arg:"--json" help:"import a JSON file from gemini-cli"` BashAuto []string `arg:"--auto-complete" help:"todo: move this to go-arg"`
Uuid string `arg:"--uuid" help:"look at this uuid"`
Topic string `arg:"--topic" help:"the topic"`
Stats []string `arg:"--stats" help:"add stats to a chat"`
NewChat *EmptyCmd `arg:"subcommand:newchat" help:"create a new chat"`
GetNextAutoTopic bool `arg:"--get-next-auto-topic" help:"get the next auto topic name"`
Force bool `arg:"--force" help:"try to strong arm things"`
Verbose bool `arg:"--verbose" help:"show more output"`
Bash bool `arg:"--bash" help:"generate bash completion"`
BashAuto []string `arg:"--auto-complete" help:"todo: move this to go-arg"`
} }
type EmptyCmd struct { type EmptyCmd struct {

View File

@ -21,7 +21,7 @@ func deleteMatch() {
} }
func (args) doBashAuto() { func (args) doBashAuto() {
argv.doBashHelp() // argv.doBashHelp()
switch argv.BashAuto[0] { switch argv.BashAuto[0] {
case "playback": case "playback":
fmt.Println("long --uuid") fmt.Println("long --uuid")
@ -30,7 +30,7 @@ func (args) doBashAuto() {
default: default:
if argv.BashAuto[0] == ARGNAME { if argv.BashAuto[0] == ARGNAME {
// list the subcommands here // list the subcommands here
fmt.Println("--add connect format interact playback") fmt.Println("--json interact playback")
} }
} }
os.Exit(0) os.Exit(0)

View File

@ -10,42 +10,23 @@ import (
) )
// doConnect initializes the Gemini client and handles the request flow. // doConnect initializes the Gemini client and handles the request flow.
func doConnect() error { func doConnect() (*genai.Client, error) {
apiKey := os.Getenv("GEMINI_API_KEY") apiKey := os.Getenv("GEMINI_API_KEY")
if apiKey == "" { if apiKey == "" {
return log.Errorf("GEMINI_API_KEY environment variable not set") return nil, log.Errorf("GEMINI_API_KEY environment variable not set")
} }
ctx := context.Background() ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{APIKey: apiKey}) client, err := genai.NewClient(ctx, &genai.ClientConfig{APIKey: apiKey})
if err != nil { if err != nil {
return log.Errorf("failed to create new genai client: %w", err) return nil, log.Errorf("failed to create new genai client: %w", err)
} }
if argv.JsonFile != "" { return client, err
req, err := parseJSON(argv.JsonFile)
if err != nil {
return err
}
log.Info("parseJSON() ok. model =", req.Model)
genaiContent, err := convertToGenai(req)
if err != nil {
return log.Errorf("failed to convert to genai.Content: %w", err)
}
log.Info("Successfully converted JSON to genai.Content")
// Here you would now use the 'genaiContent' to send to the API
_ = genaiContent // Prevent unused variable error for now
return nil
}
log.Info("doing sampleHello()")
return sampleHello(client)
} }
// sampleHello sends a hardcoded prompt to the model and prints the response. // sampleHello sends a hardcoded prompt to the model and prints the response.
func sampleHello(client *genai.Client) error { func simpleHello(client *genai.Client) error {
log.Info("Sending 'hello, how are you' to the Gemini API...") log.Info("Sending 'hello, how are you' to the Gemini API...")
ctx := context.Background() ctx := context.Background()
@ -56,7 +37,7 @@ func sampleHello(client *genai.Client) error {
content := []*genai.Content{{Parts: parts}} content := []*genai.Content{{Parts: parts}}
resp, err := client.Models.GenerateContent(ctx, "gemini-1.5-flash-latest", content, nil) resp, err := client.Models.GenerateContent(ctx, "gemini-2.5-flash", content, nil)
if err != nil { if err != nil {
return log.Errorf("error sending message: %v", err) return log.Errorf("error sending message: %v", err)
} }

View File

@ -8,9 +8,6 @@ import (
) )
func doGetNextAutoTopic() { func doGetNextAutoTopic() {
if err := me.chats.ConfigLoad(); err != nil {
badExit(err)
}
max := 0 max := 0
for _, chat := range me.chats.GetChats() { for _, chat := range me.chats.GetChats() {
if strings.HasPrefix(chat.GetChatName(), "Auto ") { if strings.HasPrefix(chat.GetChatName(), "Auto ") {

View File

@ -1,56 +0,0 @@
package main
import (
"io/ioutil"
"time"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
"google.golang.org/protobuf/types/known/timestamppb"
)
func doImport(filename string) {
content, err := ioutil.ReadFile(filename)
if err != nil {
log.Warn("Error reading import file:", err)
return
}
s := string(content)
// Load the existing chats.
all := chatpb.NewChats()
if err := all.ConfigLoad(); err != nil {
log.Warn("Error loading config, can't add to auto chat:", err)
return
}
// Find the "auto" chat.
var autoChat *chatpb.Chat
for _, chat := range all.GetChats() {
if chat.GetChatName() == "auto" {
autoChat = chat
break
}
}
// If the "auto" chat is found, add the new entry.
if autoChat != nil {
newEntry := &chatpb.ChatEntry{
From: chatpb.Who_REGEX,
Ctime: timestamppb.New(time.Now()),
ToolCalls: []*chatpb.ToolCall{
{
Name: "Shell",
Input: s,
},
},
}
autoChat.Entries = append(autoChat.Entries, newEntry)
if err := all.ConfigSave(); err != nil {
log.Warn("Error saving config after adding to auto chat:", err)
} else {
log.Info("Added new entry to 'auto' chat.")
}
}
}

View File

@ -1,56 +0,0 @@
package main
import (
"os"
"time"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
"google.golang.org/protobuf/types/known/timestamppb"
)
func doInput(s string) {
filename := "/tmp/regex-input.log"
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
return
}
defer f.Close()
if _, err := f.WriteString(s + "\n"); err != nil {
log.Println(err)
}
log.Info("INPUT LOGGED TO", filename)
// Load the existing chats.
all := chatpb.NewChats()
if err := all.ConfigLoad(); err != nil {
log.Warn("Error loading config, can't add to auto chat:", err)
return
}
// Find the "auto" chat.
var autoChat *chatpb.Chat
for _, chat := range all.GetChats() {
if chat.GetChatName() == "auto" {
autoChat = chat
break
}
}
// If the "auto" chat is found, add the new entry.
if autoChat != nil {
newEntry := &chatpb.ChatEntry{
From: chatpb.Who_USER,
Content: s,
Ctime: timestamppb.New(time.Now()),
}
autoChat.Entries = append(autoChat.Entries, newEntry)
if err := all.ConfigSave(); err != nil {
log.Warn("Error saving config after adding to auto chat:", err)
} else {
log.Info("Added new entry to 'auto' chat.")
}
}
}

View File

@ -10,7 +10,7 @@ import (
"go.wit.com/log" "go.wit.com/log"
) )
func doEditor() error { func doInteract() error {
for { for {
filename, err := doEditorOnce() filename, err := doEditorOnce()
if err != nil { if err != nil {

View File

@ -9,7 +9,7 @@ import (
func doNewChat() { func doNewChat() {
chat := &chatpb.Chat{ chat := &chatpb.Chat{
Uuid: argv.Uuid, Uuid: argv.Uuid,
ChatName: argv.Topic, ChatName: "todo: set this",
Ctime: timestamppb.Now(), Ctime: timestamppb.Now(),
} }

View File

@ -9,12 +9,8 @@ import (
) )
func doStats() { func doStats() {
if len(argv.Stats) != 2 { sessionUuid := argv.Uuid
log.Warn("expected 2 arguments for --stats") statsString := "todo: set this somehow"
return
}
sessionUuid := argv.Stats[0]
statsString := argv.Stats[1]
// Find the "auto" chat, or create it if it doesn't exist. // Find the "auto" chat, or create it if it doesn't exist.
var autoChat *chatpb.Chat var autoChat *chatpb.Chat

85
main.go
View File

@ -47,73 +47,57 @@ func main() {
os.Exit(0) os.Exit(0)
} }
// load the default chat protobuf
me.chats = chatpb.NewChats() me.chats = chatpb.NewChats()
if err := me.chats.ConfigLoad(); err != nil { if err := me.chats.ConfigLoad(); err != nil {
badExit(err) badExit(err)
} }
// verify all the chats have Uuid's
if verifyUuids(me.chats) { if verifyUuids(me.chats) {
me.chats.ConfigSave() me.chats.ConfigSave()
} }
if argv.GetNextAutoTopic { aiClient, err := doConnect()
doGetNextAutoTopic() if err != nil {
okExit("") badExit(err)
} }
_ = aiClient
if argv.Connect != nil { if argv.JsonFile != "" {
err := doConnect() req, err := parseJSON(argv.JsonFile)
if err != nil { if err != nil {
badExit(err) badExit(err)
} }
log.Info("parseJSON() ok. model =", req.Model)
genaiContent, err := convertToGenai(req)
if err != nil {
badExit(err)
}
log.Info("Successfully converted JSON to genai.Content")
// Here you would now use the 'genaiContent' to send to the API
_ = genaiContent // Prevent unused variable error for now
okExit("") okExit("")
} }
if argv.Editor != nil { if argv.Interact != nil {
doEditor() log.Info("testing AI client with simpleHello()")
err = simpleHello(aiClient)
if err != nil {
badExit(err)
}
doInteract()
okExit("") okExit("")
} }
if argv.NewChat != nil { if argv.Stats != "" {
doNewChat()
okExit("")
}
if argv.Stats != nil {
doStats() doStats()
okExit("") okExit("")
} }
if argv.Output != "" {
doOutput(argv.Output)
okExit("")
}
if argv.Input != "" {
doInput(argv.Input)
okExit("")
}
if argv.ImportFile != "" {
doImport(argv.ImportFile)
okExit("")
}
if argv.Add != "" {
newChats, err := addFile(argv.Add)
if err != nil {
badExit(err)
}
verifyUuids(newChats)
for _, newChat := range newChats.GetChats() {
me.chats.AppendByUuid(newChat)
log.Info("Attempting to add chat", newChat.ChatName)
}
me.chats.ConfigSave()
okExit("")
}
if argv.Playback != nil { if argv.Playback != nil {
if argv.Uuid != "" { if argv.Uuid != "" {
showChat(argv.Uuid) showChat(argv.Uuid)
@ -123,21 +107,10 @@ func main() {
okExit("") okExit("")
} }
/*
// if opening the GUI, always check git for dirty repos
log.Info("look for 'auto' here")
// Find the "auto" chat.
for _, chat := range me.chats.GetChats() {
if chat.GetChatName() == "auto" {
prettyFormatChat(chat)
okExit("")
}
}
*/
// doGui() // doGui()
// by default, start interacting with gemini-cli // by default, start interacting with gemini-cli
doEditor() me.pp.WriteHelp(os.Stdout)
okExit("") okExit("")
} }