Skip to content

Instantly share code, notes, and snippets.

@wangjohn
Created January 9, 2025 17:55
Show Gist options
  • Select an option

  • Save wangjohn/8f0658898597924119efd96a1ebc6951 to your computer and use it in GitHub Desktop.

Select an option

Save wangjohn/8f0658898597924119efd96a1ebc6951 to your computer and use it in GitHub Desktop.
import (
"github.com/sashabaranov/go-openai"
"github.com/sashabaranov/go-openai/jsonschema"
)
type SupportResponse struct {
Answer string `json:"answer"`
RelatedDocs []string `json:"related_docs"`
}
func GetSupportResponse(messages []openai.ChatCompletionMessage) (*SupportResponse, error) {
var supportResponse SupportResponse
schema, err := jsonschema.GenerateSchemaForType(supportResponse)
if err != nil {
return nil, err
}
resp, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
Messages: messages,
ResponseFormat: &openai.ChatCompletionResponseFormat{
Type: openai.ChatCompletionResponseFormatTypeJSONSchema,
JSONSchema: &openai.ChatCompletionResponseFormatJSONSchema{
Name: "support_response",
Schema: schema,
Strict: true,
},
},
})
if err != nil {
return nil, err
}
err = schema.Unmarshal(resp.Choices[0].Message.Content, &supportResponse)
if err != nil {
return nil, err
}
return &supportResponse, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment