First commit
This commit is contained in:
47
openai/client.go
Normal file
47
openai/client.go
Normal file
@ -0,0 +1,47 @@
|
||||
package openai
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"matrix-gpt-bot/config"
|
||||
|
||||
goai "github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
// Message represents a single message in the conversation.
|
||||
type Message struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Ask sends the provided messages to the OpenAI API and returns the assistant's reply.
|
||||
func Ask(messages []Message) (string, error) {
|
||||
// Load OpenAI key from configuration
|
||||
conf := config.Load()
|
||||
client := goai.NewClient(conf.OpenAIKey)
|
||||
|
||||
// Build the chat history in the format expected by the API
|
||||
var chatHistory []goai.ChatCompletionMessage
|
||||
for _, m := range messages {
|
||||
chatHistory = append(chatHistory, goai.ChatCompletionMessage{
|
||||
Role: m.Role,
|
||||
Content: m.Content,
|
||||
})
|
||||
}
|
||||
|
||||
// Create the chat completion request
|
||||
resp, err := client.CreateChatCompletion(
|
||||
context.Background(),
|
||||
goai.ChatCompletionRequest{
|
||||
Model: "gpt-4.1",
|
||||
Messages: chatHistory,
|
||||
MaxTokens: 600,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Return the content of the first choice
|
||||
return resp.Choices[0].Message.Content, nil
|
||||
}
|
Reference in New Issue
Block a user