2023-11-04 12:20:13 -06:00
|
|
|
package cli
|
2023-10-30 15:23:07 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2023-11-25 17:55:18 -07:00
|
|
|
"database/sql"
|
|
|
|
"encoding/json"
|
2023-10-30 15:45:21 -06:00
|
|
|
"errors"
|
2023-11-25 17:55:18 -07:00
|
|
|
"fmt"
|
2023-10-30 15:45:21 -06:00
|
|
|
"io"
|
2023-11-23 20:45:43 -07:00
|
|
|
"strings"
|
2023-11-04 16:56:22 -06:00
|
|
|
|
2023-10-30 15:23:07 -06:00
|
|
|
openai "github.com/sashabaranov/go-openai"
|
|
|
|
)
|
|
|
|
|
2023-11-08 23:07:52 -07:00
|
|
|
func CreateChatCompletionRequest(model string, messages []Message, maxTokens int) openai.ChatCompletionRequest {
|
2023-11-05 01:54:12 -06:00
|
|
|
chatCompletionMessages := []openai.ChatCompletionMessage{}
|
2023-11-04 16:56:22 -06:00
|
|
|
for _, m := range messages {
|
2023-11-25 17:55:18 -07:00
|
|
|
message := openai.ChatCompletionMessage{
|
2023-11-28 21:43:53 -07:00
|
|
|
Role: string(m.Role),
|
2023-10-30 15:23:07 -06:00
|
|
|
Content: m.OriginalContent,
|
2023-11-25 17:55:18 -07:00
|
|
|
}
|
|
|
|
if m.ToolCallID.Valid {
|
|
|
|
message.ToolCallID = m.ToolCallID.String
|
|
|
|
}
|
|
|
|
if m.ToolCalls.Valid {
|
|
|
|
// unmarshal directly into chatMessage.ToolCalls
|
|
|
|
err := json.Unmarshal([]byte(m.ToolCalls.String), &message.ToolCalls)
|
|
|
|
if err != nil {
|
|
|
|
// TODO: handle, this shouldn't really happen since
|
|
|
|
// we only save the successfully marshal'd data to database
|
|
|
|
fmt.Printf("Error unmarshalling the tool_calls JSON: %v\n", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
chatCompletionMessages = append(chatCompletionMessages, message)
|
|
|
|
}
|
|
|
|
|
2023-11-28 22:27:58 -07:00
|
|
|
request := openai.ChatCompletionRequest{
|
|
|
|
Model: model,
|
|
|
|
Messages: chatCompletionMessages,
|
|
|
|
MaxTokens: maxTokens,
|
|
|
|
N: 1, // limit responses to 1 "choice". we use choices[0] to reference it
|
|
|
|
}
|
|
|
|
|
2023-11-25 17:55:18 -07:00
|
|
|
var tools []openai.Tool
|
2023-11-28 22:27:58 -07:00
|
|
|
for _, t := range config.OpenAI.EnabledTools {
|
|
|
|
tool, ok := AvailableTools[t]
|
|
|
|
if ok {
|
|
|
|
tools = append(tools, tool.Tool)
|
|
|
|
}
|
2023-10-30 15:23:07 -06:00
|
|
|
}
|
|
|
|
|
2023-11-28 22:27:58 -07:00
|
|
|
if len(tools) > 0 {
|
|
|
|
request.Tools = tools
|
|
|
|
request.ToolChoice = "auto"
|
2023-10-30 16:23:27 -06:00
|
|
|
}
|
2023-11-28 22:27:58 -07:00
|
|
|
|
|
|
|
return request
|
2023-10-30 16:23:27 -06:00
|
|
|
}
|
|
|
|
|
2023-11-05 11:19:30 -07:00
|
|
|
// CreateChatCompletion submits a Chat Completion API request and returns the
|
2023-11-25 17:55:18 -07:00
|
|
|
// response. CreateChatCompletion will recursively call itself in the case of
|
|
|
|
// tool calls, until a response is received with the final user-facing output.
|
2023-11-28 21:43:53 -07:00
|
|
|
func CreateChatCompletion(model string, messages []Message, maxTokens int, replies *[]Message) (string, error) {
|
2023-11-18 18:14:00 -07:00
|
|
|
client := openai.NewClient(*config.OpenAI.APIKey)
|
2023-11-08 23:07:52 -07:00
|
|
|
req := CreateChatCompletionRequest(model, messages, maxTokens)
|
2023-11-05 11:19:30 -07:00
|
|
|
resp, err := client.CreateChatCompletion(context.Background(), req)
|
2023-10-30 15:23:07 -06:00
|
|
|
if err != nil {
|
2023-11-04 16:07:06 -06:00
|
|
|
return "", err
|
2023-10-30 15:23:07 -06:00
|
|
|
}
|
|
|
|
|
2023-11-25 17:55:18 -07:00
|
|
|
choice := resp.Choices[0]
|
|
|
|
|
|
|
|
if len(choice.Message.ToolCalls) > 0 {
|
|
|
|
// Append the assistant's reply with its request for tool calls
|
|
|
|
toolCallJson, _ := json.Marshal(choice.Message.ToolCalls)
|
2023-11-28 21:43:53 -07:00
|
|
|
assistantReply := Message{
|
|
|
|
Role: MessageRoleAssistant,
|
2023-11-25 17:55:18 -07:00
|
|
|
ToolCalls: sql.NullString{String: string(toolCallJson), Valid: true},
|
2023-11-28 21:43:53 -07:00
|
|
|
}
|
2023-11-25 17:55:18 -07:00
|
|
|
|
|
|
|
toolReplies, err := ExecuteToolCalls(choice.Message.ToolCalls)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2023-11-28 21:43:53 -07:00
|
|
|
if replies != nil {
|
|
|
|
*replies = append(append(*replies, assistantReply), toolReplies...)
|
|
|
|
}
|
|
|
|
|
|
|
|
messages = append(append(messages, assistantReply), toolReplies...)
|
2023-11-25 17:55:18 -07:00
|
|
|
// Recurse into CreateChatCompletion with the tool call replies added
|
|
|
|
// to the original messages
|
2023-11-28 21:43:53 -07:00
|
|
|
return CreateChatCompletion(model, append(messages, toolReplies...), maxTokens, replies)
|
|
|
|
}
|
|
|
|
|
|
|
|
if replies != nil {
|
|
|
|
*replies = append(*replies, Message{
|
|
|
|
Role: MessageRoleAssistant,
|
|
|
|
OriginalContent: choice.Message.Content,
|
|
|
|
})
|
2023-11-25 17:55:18 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Return the user-facing message.
|
|
|
|
return choice.Message.Content, nil
|
2023-10-30 15:23:07 -06:00
|
|
|
}
|
2023-10-30 15:45:21 -06:00
|
|
|
|
2023-11-05 11:19:30 -07:00
|
|
|
// CreateChatCompletionStream submits a streaming Chat Completion API request
|
2023-11-23 20:45:43 -07:00
|
|
|
// and both returns and streams the response to the provided output channel.
|
|
|
|
// May return a partial response if an error occurs mid-stream.
|
2023-11-28 21:43:53 -07:00
|
|
|
func CreateChatCompletionStream(model string, messages []Message, maxTokens int, output chan<- string, replies *[]Message) (string, error) {
|
2023-11-18 18:14:00 -07:00
|
|
|
client := openai.NewClient(*config.OpenAI.APIKey)
|
2023-11-08 23:07:52 -07:00
|
|
|
req := CreateChatCompletionRequest(model, messages, maxTokens)
|
2023-10-30 15:45:21 -06:00
|
|
|
|
2023-11-05 11:19:30 -07:00
|
|
|
stream, err := client.CreateChatCompletionStream(context.Background(), req)
|
2023-10-30 15:45:21 -06:00
|
|
|
if err != nil {
|
2023-11-23 20:45:43 -07:00
|
|
|
return "", err
|
2023-10-30 15:45:21 -06:00
|
|
|
}
|
|
|
|
defer stream.Close()
|
|
|
|
|
2023-11-25 17:55:18 -07:00
|
|
|
content := strings.Builder{}
|
|
|
|
toolCalls := []openai.ToolCall{}
|
|
|
|
|
|
|
|
// Iterate stream segments
|
2023-10-30 15:45:21 -06:00
|
|
|
for {
|
2023-11-23 20:45:43 -07:00
|
|
|
response, e := stream.Recv()
|
|
|
|
if errors.Is(e, io.EOF) {
|
|
|
|
break
|
2023-10-30 15:45:21 -06:00
|
|
|
}
|
|
|
|
|
2023-11-23 20:45:43 -07:00
|
|
|
if e != nil {
|
|
|
|
err = e
|
|
|
|
break
|
2023-10-30 15:45:21 -06:00
|
|
|
}
|
2023-11-25 17:55:18 -07:00
|
|
|
|
|
|
|
delta := response.Choices[0].Delta
|
|
|
|
if len(delta.ToolCalls) > 0 {
|
|
|
|
// Construct streamed tool_call arguments
|
|
|
|
for _, tc := range delta.ToolCalls {
|
|
|
|
if tc.Index == nil {
|
|
|
|
return "", fmt.Errorf("Unexpected nil index for streamed tool call.")
|
|
|
|
}
|
|
|
|
if len(toolCalls) <= *tc.Index {
|
|
|
|
toolCalls = append(toolCalls, tc)
|
|
|
|
} else {
|
|
|
|
toolCalls[*tc.Index].Function.Arguments += tc.Function.Arguments
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
output <- delta.Content
|
|
|
|
content.WriteString(delta.Content)
|
|
|
|
}
|
2023-10-30 15:45:21 -06:00
|
|
|
}
|
2023-11-25 17:55:18 -07:00
|
|
|
|
|
|
|
if len(toolCalls) > 0 {
|
|
|
|
// Append the assistant's reply with its request for tool calls
|
|
|
|
toolCallJson, _ := json.Marshal(toolCalls)
|
2023-11-28 21:43:53 -07:00
|
|
|
|
|
|
|
assistantReply := Message{
|
|
|
|
Role: MessageRoleAssistant,
|
|
|
|
OriginalContent: content.String(),
|
|
|
|
ToolCalls: sql.NullString{String: string(toolCallJson), Valid: true},
|
|
|
|
}
|
2023-11-25 17:55:18 -07:00
|
|
|
|
|
|
|
toolReplies, err := ExecuteToolCalls(toolCalls)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2023-11-28 21:43:53 -07:00
|
|
|
if replies != nil {
|
|
|
|
*replies = append(append(*replies, assistantReply), toolReplies...)
|
|
|
|
}
|
|
|
|
|
2023-11-25 17:55:18 -07:00
|
|
|
// Recurse into CreateChatCompletionStream with the tool call replies
|
|
|
|
// added to the original messages
|
2023-11-28 21:43:53 -07:00
|
|
|
messages = append(append(messages, assistantReply), toolReplies...)
|
|
|
|
return CreateChatCompletionStream(model, messages, maxTokens, output, replies)
|
|
|
|
}
|
|
|
|
|
|
|
|
if replies != nil {
|
|
|
|
*replies = append(*replies, Message{
|
|
|
|
Role: MessageRoleAssistant,
|
|
|
|
OriginalContent: content.String(),
|
|
|
|
})
|
2023-11-25 17:55:18 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
return content.String(), err
|
2023-10-30 15:45:21 -06:00
|
|
|
}
|