|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/tmc/langchaingo/llms" |
| 6 | + "github.com/tmc/langchaingo/llms/openai" |
| 7 | + "log" |
| 8 | +) |
| 9 | + |
| 10 | +type User struct { |
| 11 | + Name string `json:"name"` |
| 12 | + Age int `json:"age"` |
| 13 | +} |
| 14 | + |
| 15 | +func main() { |
| 16 | + fomat := &openai.ResponseFormat{ |
| 17 | + Type: "json_schema", |
| 18 | + JSONSchema: &openai.ResponseFormatJSONSchema{ |
| 19 | + Name: "object", |
| 20 | + Schema: &openai.ResponseFormatJSONSchemaProperty{ |
| 21 | + Type: "object", |
| 22 | + Properties: map[string]*openai.ResponseFormatJSONSchemaProperty{ |
| 23 | + "name": { |
| 24 | + Type: "string", |
| 25 | + Description: "The name of the user", |
| 26 | + }, |
| 27 | + "age": { |
| 28 | + Type: "integer", |
| 29 | + Description: "The age of the user", |
| 30 | + }, |
| 31 | + "role": { |
| 32 | + Type: "string", |
| 33 | + Description: "The role of the user", |
| 34 | + }, |
| 35 | + }, |
| 36 | + AdditionalProperties: false, |
| 37 | + Required: []string{"name", "age", "role"}, |
| 38 | + }, |
| 39 | + Strict: true, |
| 40 | + }, |
| 41 | + } |
| 42 | + llm, err := openai.New(openai.WithModel("gpt-4o"), openai.WithResponseFormat(fomat)) |
| 43 | + if err != nil { |
| 44 | + log.Fatal(err) |
| 45 | + } |
| 46 | + ctx := context.Background() |
| 47 | + |
| 48 | + content := []llms.MessageContent{ |
| 49 | + llms.TextParts(llms.ChatMessageTypeSystem, "You are an expert at structured data extraction. You will be given unstructured text from a research paper and should convert it into the given structure."), |
| 50 | + llms.TextParts(llms.ChatMessageTypeHuman, "please tell me the most famous people in history"), |
| 51 | + } |
| 52 | + |
| 53 | + completion, err := llm.GenerateContent(ctx, content, llms.WithJSONMode()) |
| 54 | + if err != nil { |
| 55 | + log.Fatal(err) |
| 56 | + } |
| 57 | + log.Fatal(completion.Choices[0].Content) |
| 58 | +} |
0 commit comments