Created
December 4, 2022 04:53
-
-
Save sepulworld/daa293da64ea76cf0b88714e4b5a7a88 to your computer and use it in GitHub Desktop.
chat with openai
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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