Skip to content

Commit 0d94927

Browse files
authored
make it good (cloudflare#20332)
1 parent f99009d commit 0d94927

File tree

2 files changed

+149
-2
lines changed

2 files changed

+149
-2
lines changed
Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,70 @@
11
---
2-
title: Workers AI JSON Mode
2+
title: Workers AI now supports structured JSON outputs.
33
description: Workers AI JSON Mode adds structured outputs support
44
date: 2025-02-25T15:00:00Z
55
---
66

7-
We've updated the Workers AI to support [JSON mode](/workers-ai/json-mode/), enabling applications to request a structured output response when interacting with AI models.
7+
import { TypeScriptExample } from "~/components";
8+
9+
Workers AI now supports structured JSON outputs with [JSON mode](/workers-ai/json-mode/), which allows you to request a structured output response when interacting with AI models.
10+
11+
This makes it much easier to retrieve structured data from your AI models, and avoids the (error prone!) need to parse large unstructured text responses to extract your data.
12+
13+
JSON mode in Workers AI is compatible with the OpenAI SDK's [structured outputs](https://platform.openai.com/docs/guides/structured-outputs) `response_format` API, which can be used directly in a Worker:
14+
15+
<TypeScriptExample>
16+
17+
```ts
18+
import { OpenAI } from "openai";
19+
20+
interface Env {
21+
OPENAI_API_KEY: string;
22+
}
23+
24+
// Define your JSON schema for a calendar event
25+
const CalendarEventSchema = {
26+
type: 'object',
27+
properties: {
28+
name: { type: 'string' },
29+
date: { type: 'string' },
30+
participants: { type: 'array', items: { type: 'string' } },
31+
},
32+
required: ['name', 'date', 'participants']
33+
};
34+
35+
export default {
36+
async fetch(request: Request, env: Env) {
37+
const client = new OpenAI({
38+
apiKey: env.OPENAI_API_KEY,
39+
// Optional: use AI Gateway to bring logs, evals & caching to your AI requests
40+
// https://developers.cloudflare.com/ai-gateway/providers/openai/
41+
// baseUrl: "https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai"
42+
});
43+
44+
const response = await client.chat.completions.create({
45+
model: 'gpt-4o-2024-08-06',
46+
messages: [
47+
{ role: 'system', content: 'Extract the event information.' },
48+
{ role: 'user', content: 'Alice and Bob are going to a science fair on Friday.' },
49+
],
50+
// Use the `response_format` option to request a structured JSON output
51+
response_format: {
52+
// Set json_schema and provide ra schema, or json_object and parse it yourself
53+
type: 'json_schema',
54+
schema: CalendarEventSchema, // provide a schema
55+
},
56+
});
57+
58+
// This will be of type CalendarEventSchema
59+
const event = response.choices[0].message.parsed;
60+
61+
return Response.json({
62+
"calendar_event": event,
63+
})
64+
}
65+
}
66+
```
67+
68+
</TypeScriptExample>
69+
70+
To learn more about JSON mode and structured outputs, visit the [Workers AI documentation](/workers-ai/json-mode/).

src/content/docs/workers/get-started/prompting.mdx

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1256,6 +1256,90 @@ function StateInterface() {
12561256
</configuration>
12571257
<key_points>
12581258

1259+
- Imports the `Agent` class from the `agents-sdk` package
1260+
- Extends the `Agent` class and implements the methods exposed by the `Agent`, including `onRequest` for HTTP requests, or `onConnect` and `onMessage` for WebSockets.
1261+
- Uses the `this.schedule` scheduling API to schedule future tasks.
1262+
- Uses the `this.setState` API within the Agent for syncing state, and uses type parameters to ensure the state is typed.
1263+
- Uses the `this.sql` as a lower-level query API.
1264+
- For frontend applications, uses the optional `useAgent` hook to connect to the Agent via WebSockets
1265+
1266+
</key_points>
1267+
</example>
1268+
1269+
<example id="workers-ai-structured-outputs-json">
1270+
<description>
1271+
Workers AI supports structured JSON outputs with JSON mode, which supports the `response_format` API provided by the OpenAI SDK.
1272+
</description>
1273+
<code language="typescript">
1274+
import { OpenAI } from "openai";
1275+
1276+
interface Env {
1277+
OPENAI_API_KEY: string;
1278+
}
1279+
1280+
// Define your JSON schema for a calendar event
1281+
const CalendarEventSchema = {
1282+
type: 'object',
1283+
properties: {
1284+
name: { type: 'string' },
1285+
date: { type: 'string' },
1286+
participants: { type: 'array', items: { type: 'string' } },
1287+
},
1288+
required: ['name', 'date', 'participants']
1289+
};
1290+
1291+
export default {
1292+
async fetch(request: Request, env: Env) {
1293+
const client = new OpenAI({
1294+
apiKey: env.OPENAI_API_KEY,
1295+
// Optional: use AI Gateway to bring logs, evals & caching to your AI requests
1296+
// https://developers.cloudflare.com/ai-gateway/providers/openai/
1297+
// baseUrl: "https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai"
1298+
});
1299+
1300+
const response = await client.chat.completions.create({
1301+
model: 'gpt-4o-2024-08-06',
1302+
messages: [
1303+
{ role: 'system', content: 'Extract the event information.' },
1304+
{ role: 'user', content: 'Alice and Bob are going to a science fair on Friday.' },
1305+
],
1306+
// Use the `response_format` option to request a structured JSON output
1307+
response_format: {
1308+
// Set json_schema and provide ra schema, or json_object and parse it yourself
1309+
type: 'json_schema',
1310+
schema: CalendarEventSchema, // provide a schema
1311+
},
1312+
});
1313+
1314+
// This will be of type CalendarEventSchema
1315+
const event = response.choices[0].message.parsed;
1316+
1317+
return Response.json({
1318+
"calendar_event": event,
1319+
})
1320+
}
1321+
}
1322+
</code>
1323+
<configuration>
1324+
{
1325+
"name": "my-app",
1326+
"main": "src/index.ts",
1327+
"compatibility_date": "$CURRENT_DATE",
1328+
"observability": {
1329+
"enabled": true
1330+
}
1331+
}
1332+
</configuration>
1333+
<key_points>
1334+
1335+
- Defines a JSON Schema compatible object that represents the structured format requested from the model
1336+
- Sets `response_format` to `json_schema` and provides a schema to parse the response
1337+
- This could also be `json_object`, which can be parsed after the fact.
1338+
- Optionally uses AI Gateway to cache, log and instrument requests and responses between a client and the AI provider/API.
1339+
1340+
</key_points>
1341+
</example>
1342+
12591343
</code_examples>
12601344

12611345
<api_patterns>

0 commit comments

Comments
 (0)