[Show Off] Google AI Gemini-Pro in Command/Terminal #3727
H0llyW00dzZ
started this conversation in
Show and tell
Replies: 3 comments
-
updated code: // Author: https://github.com/H0llyW00dzZ
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"
"time"
typing "github.com/H0llyW00dzZ/ChatGPT-Next-Web-Session-Exporter/bannercli"
genai "github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
type ChatHistory struct {
Messages []string
}
func (h *ChatHistory) AddMessage(user, text string) {
h.Messages = append(h.Messages, fmt.Sprintf("%s: %s", user, text))
}
func (h *ChatHistory) PrintHistory() {
for _, msg := range h.Messages {
fmt.Println(msg)
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
log.Fatal("API_KEY environment variable is not set")
}
client, err := genai.NewClient(ctx, option.WithAPIKey(apiKey))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-pro")
cs := model.StartChat()
reader := bufio.NewReader(os.Stdin) // Create a new bufio.Reader
chatHistory := ChatHistory{} // Initialize chat history
chatHistory.PrintHistory()
// Set up channel to listen for interrupt signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
// Goroutine to handle graceful shutdown
go func() {
<-sigChan // Block until a signal is received
fmt.Println("\nReceived an interrupt, shutting down gracefully...")
cancel() // Cancel the context to cleanup resources
client.Close()
os.Exit(0)
}()
for {
fmt.Print("You: ")
userInput, err := reader.ReadString('\n') // Read the input until a newline
if err != nil {
log.Fatal(err)
}
userInput = strings.TrimSpace(userInput) // Remove the newline character
chatHistory.AddMessage("You", userInput) // Add user input to history
resp, err := cs.SendMessage(ctx, genai.Text(userInput))
if err != nil {
log.Fatal(err)
}
aiResponse := printResponse(resp)
chatHistory.AddMessage("AI", aiResponse) // Add AI response to history
}
}
func printResponse(resp *genai.GenerateContentResponse) string {
aiResponse := ""
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
// Print "AI:" prefix directly without typing effect
fmt.Print("AI: ")
// Assuming 'part' can be printed directly and is of type string or has a String() method
// Use the typing banner effect only for the part content
typing.PrintTypingBanner(fmt.Sprint(part), 100*time.Millisecond)
aiResponse += fmt.Sprint(part) // Collect AI response
}
}
}
fmt.Println("---")
return aiResponse
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
better one code: // Author: https://github.com/H0llyW00dzZ - Modified to include chat history in AI requests
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"
"time"
typing "github.com/H0llyW00dzZ/ChatGPT-Next-Web-Session-Exporter/bannercli"
genai "github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
type ChatHistory struct {
Messages []string
}
func (h *ChatHistory) AddMessage(user, text string) {
h.Messages = append(h.Messages, fmt.Sprintf("%s: %s", user, text))
}
func (h *ChatHistory) GetHistory() string {
return strings.Join(h.Messages, "\n")
}
func (h *ChatHistory) PrintHistory() {
for _, msg := range h.Messages {
fmt.Println(msg)
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
log.Fatal("API_KEY environment variable is not set")
}
client, err := genai.NewClient(ctx, option.WithAPIKey(apiKey))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-pro")
cs := model.StartChat()
reader := bufio.NewReader(os.Stdin)
chatHistory := ChatHistory{}
// Print the chat history before starting the conversation
chatHistory.PrintHistory()
// Set up channel to listen for interrupt signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
// Goroutine to handle graceful shutdown
go func() {
<-sigChan // Block until a signal is received
fmt.Println("\nReceived an interrupt, shutting down gracefully...")
cancel() // Cancel the context to cleanup resources
client.Close()
os.Exit(0)
}()
for {
fmt.Print("You: ")
userInput, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
userInput = strings.TrimSpace(userInput)
chatHistory.AddMessage("You", userInput)
// Pass the entire chat history as context for the AI's response
chatContext := chatHistory.GetHistory()
resp, err := cs.SendMessage(ctx, genai.Text(chatContext))
if err != nil {
log.Fatal(err)
}
aiResponse := printResponse(resp)
chatHistory.AddMessage("AI", aiResponse)
}
}
func printResponse(resp *genai.GenerateContentResponse) string {
aiResponse := ""
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
// Print "AI:" prefix directly without typing effect
fmt.Print("AI: ")
// Assuming 'part' can be printed directly and is of type string or has a String() method
// Use the typing banner effect only for the part content
typing.PrintTypingBanner(fmt.Sprint(part), 100*time.Millisecond)
aiResponse += fmt.Sprint(part) // Collect AI response
}
}
}
fmt.Println("---")
return aiResponse
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
INFONote Now it's move here https://github.com/H0llyW00dzZ/GoGenAI-Terminal-Chat Currently work on progress: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
code:
Untitled.video.-.Made.with.Clipchamp.15.mp4
Beta Was this translation helpful? Give feedback.
All reactions