Skip to content

Commit 0565cd7

Browse files
authoredJun 20, 2024··
feat (ai/core): add toJsonResponse to generateObject result. (#2033)
1 parent ba679f8 commit 0565cd7

File tree

6 files changed

+62
-2
lines changed

6 files changed

+62
-2
lines changed
 

‎.changeset/shy-turkeys-jump.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'ai': patch
3+
---
4+
5+
feat (ai/core): add toJsonResponse to generateObject result.

‎content/docs/07-reference/ai-sdk-core/03-generate-object.mdx

+6
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,12 @@ console.log(JSON.stringify(object, null, 2));
373373
description:
374374
'Warnings from the model provider (e.g. unsupported settings).',
375375
},
376+
{
377+
name: 'toJsonResponse',
378+
type: '(init?: ResponseInit) => Response',
379+
description:
380+
'Converts the object to a JSON response. The response will have a status code of 200 and a content type of `application/json; charset=utf-8`.',
381+
},
376382
]}
377383
/>
378384

‎content/examples/02-next-pages/01-basics/03-generating-object.mdx

+2-2
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ import { z } from 'zod';
8686
export async function POST(req: Request) {
8787
const { prompt }: { prompt: string } = await req.json();
8888

89-
const { object } = await generateObject({
89+
const result = await generateObject({
9090
model: openai('gpt-4'),
9191
system: 'You generate three notifications for a messages app.',
9292
prompt,
@@ -101,7 +101,7 @@ export async function POST(req: Request) {
101101
}),
102102
});
103103

104-
return Response.json({ object });
104+
return result.toJsonResponse();
105105
}
106106
```
107107

‎packages/core/core/generate-object/generate-object.test.ts

+34
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { convertReadableStreamToArray } from '@ai-sdk/provider-utils/test';
12
import assert from 'node:assert';
23
import { z } from 'zod';
34
import { MockLanguageModelV1 } from '../test/mock-language-model-v1';
@@ -84,3 +85,36 @@ describe('result.object', () => {
8485
assert.deepStrictEqual(result.object, { content: 'Hello, world!' });
8586
});
8687
});
88+
89+
describe('result.toJsonResponse', () => {
90+
it('should return JSON response', async () => {
91+
const result = await generateObject({
92+
model: new MockLanguageModelV1({
93+
doGenerate: async ({ prompt, mode }) => {
94+
return {
95+
...dummyResponseValues,
96+
text: `{ "content": "Hello, world!" }`,
97+
};
98+
},
99+
}),
100+
schema: z.object({ content: z.string() }),
101+
mode: 'json',
102+
prompt: 'prompt',
103+
});
104+
105+
const response = result.toJsonResponse();
106+
107+
assert.strictEqual(response.status, 200);
108+
assert.strictEqual(
109+
response.headers.get('Content-Type'),
110+
'application/json; charset=utf-8',
111+
);
112+
113+
assert.deepStrictEqual(
114+
await convertReadableStreamToArray(
115+
response.body!.pipeThrough(new TextDecoderStream()),
116+
),
117+
['{"content":"Hello, world!"}'],
118+
);
119+
});
120+
});

‎packages/core/core/generate-object/generate-object.ts

+14
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { CallWarning, FinishReason, LanguageModel, LogProbs } from '../types';
1111
import { convertZodToJSONSchema } from '../util/convert-zod-to-json-schema';
1212
import { retryWithExponentialBackoff } from '../util/retry-with-exponential-backoff';
1313
import { injectJsonSchemaIntoSystem } from './inject-json-schema-into-system';
14+
import { prepareResponseHeaders } from '../util/prepare-response-headers';
1415

1516
/**
1617
Generate a structured, typed object for a given prompt and schema using a language model.
@@ -288,6 +289,19 @@ Logprobs for the completion.
288289
this.rawResponse = options.rawResponse;
289290
this.logprobs = options.logprobs;
290291
}
292+
293+
/**
294+
Converts the object to a JSON response.
295+
The response will have a status code of 200 and a content type of `application/json; charset=utf-8`.
296+
*/
297+
toJsonResponse(init?: ResponseInit): Response {
298+
return new Response(JSON.stringify(this.object), {
299+
status: init?.status ?? 200,
300+
headers: prepareResponseHeaders(init, {
301+
contentType: 'application/json; charset=utf-8',
302+
}),
303+
});
304+
}
291305
}
292306

293307
/**

‎packages/core/core/generate-object/stream-object.ts

+1
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,7 @@ writes each text delta as a separate chunk.
580580

581581
/**
582582
Creates a simple text stream response.
583+
The response has a `Content-Type` header set to `text/plain; charset=utf-8`.
583584
Each text delta is encoded as UTF-8 and sent as a separate chunk.
584585
Non-text-delta events are ignored.
585586

0 commit comments

Comments
 (0)
Please sign in to comment.