๐Ÿ“ฆ Kong / volcano-sdk

๐Ÿ“„ 04-structured-outputs.ts ยท 47 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47import { agent, llmOpenAIResponses } from "../dist/volcano-sdk.js";

// Use OpenAI Responses API for guaranteed structured outputs
const llm = llmOpenAIResponses({ 
  apiKey: process.env.OPENAI_API_KEY!, 
  model: "gpt-4o-mini",
  options: {
    jsonSchema: {
      name: 'order',
      description: 'Customer order information',
      schema: {
        type: 'object',
        properties: {
          customerName: { type: 'string' },
          items: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                product: { type: 'string' },
                quantity: { type: 'number' },
                price: { type: 'number' }
              },
              required: ['product', 'quantity', 'price'],
              additionalProperties: false  // Required for nested objects
            }
          },
          total: { type: 'number' }
        },
        required: ['customerName', 'items', 'total'],
        additionalProperties: false
      }
    }
  }
});

const results = await agent({ llm })
  .then({
    prompt: "Extract order info: 'Sarah ordered 2 cappuccinos at $4.50 each and 1 croissant for $3.25'"
  })
  .run();

const order = JSON.parse(results[results.length - 1]?.llmOutput || "{}");
console.log("Order:", order);
console.log("Total:", `$${order.total}`);