Skip to content

Instantly share code, notes, and snippets.

@sepulworld
Created December 4, 2022 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sepulworld/daa293da64ea76cf0b88714e4b5a7a88 to your computer and use it in GitHub Desktop.
Save sepulworld/daa293da64ea76cf0b88714e4b5a7a88 to your computer and use it in GitHub Desktop.
chat with openai
package main
import (
"bufio"
"fmt"
"os"
"time"
"github.com/openai/api-client-go/openai"
)
func main() {
// Read API key from command line
if len(os.Args) != 2 {
fmt.Println("Usage: go run main.go <api-key>")
os.Exit(1)
}
apiKey := os.Args[1]
// Set up API client
openai.APIKey = apiKey
// Start conversation session
sessionID, err := openai.CreateSession(
"text-davinci-002",
"",
"",
"",
"",
)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
scanner := bufio.NewScanner(os.Stdin)
for {
// Read input from command line
fmt.Print("You: ")
scanner.Scan()
input := scanner.Text()
// Check if user wants to exit
if input == "exit" {
break
}
// Send message to Assistant and print response
response, err := openai.Completion(
"text-davinci-002",
input,
"",
1,
1,
0,
"",
sessionID,
"",
"",
)
if err != nil {
fmt.Println(err)
continue
}
fmt.Print("Assistant: ")
fmt.Println(response.Choices[0].Text)
}
// End conversation session and save conversation to file
openai.DeleteSession(sessionID)
conversation := ""
events, err := openai.ListEvents(sessionID)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, event := range events.Data {
conversation += event.Text + "\n"
}
filename := "conversation-" + time.Now().Format("2006-01-02-15-04-05") + ".txt"
err = ioutil.WriteFile(filename, []byte(conversation), 0644)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Conversation saved to " + filename)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment