Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat (ai/core): add toJsonResponse to generateObject result. #2033

Merged
merged 4 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/shy-turkeys-jump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'ai': patch
---

feat (ai/core): add toJsonResponse to generateObject result.
6 changes: 6 additions & 0 deletions content/docs/07-reference/ai-sdk-core/03-generate-object.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,12 @@ console.log(JSON.stringify(object, null, 2));
description:
'Warnings from the model provider (e.g. unsupported settings).',
},
{
name: 'toJsonResponse',
type: '(init?: ResponseInit) => Response',
description:
'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`.',
},
]}
/>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ import { z } from 'zod';
export async function POST(req: Request) {
const { prompt }: { prompt: string } = await req.json();

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

return Response.json({ object });
return result.toJsonResponse();
}
```

Expand Down
34 changes: 34 additions & 0 deletions packages/core/core/generate-object/generate-object.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { convertReadableStreamToArray } from '@ai-sdk/provider-utils/test';
import assert from 'node:assert';
import { z } from 'zod';
import { MockLanguageModelV1 } from '../test/mock-language-model-v1';
Expand Down Expand Up @@ -84,3 +85,36 @@ describe('result.object', () => {
assert.deepStrictEqual(result.object, { content: 'Hello, world!' });
});
});

describe('result.toJsonResponse', () => {
it('should return JSON response', async () => {
const result = await generateObject({
model: new MockLanguageModelV1({
doGenerate: async ({ prompt, mode }) => {
return {
...dummyResponseValues,
text: `{ "content": "Hello, world!" }`,
};
},
}),
schema: z.object({ content: z.string() }),
mode: 'json',
prompt: 'prompt',
});

const response = result.toJsonResponse();

assert.strictEqual(response.status, 200);
assert.strictEqual(
response.headers.get('Content-Type'),
'application/json; charset=utf-8',
);

assert.deepStrictEqual(
await convertReadableStreamToArray(
response.body!.pipeThrough(new TextDecoderStream()),
),
['{"content":"Hello, world!"}'],
);
});
});
14 changes: 14 additions & 0 deletions packages/core/core/generate-object/generate-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { CallWarning, FinishReason, LanguageModel, LogProbs } from '../types';
import { convertZodToJSONSchema } from '../util/convert-zod-to-json-schema';
import { retryWithExponentialBackoff } from '../util/retry-with-exponential-backoff';
import { injectJsonSchemaIntoSystem } from './inject-json-schema-into-system';
import { prepareResponseHeaders } from '../util/prepare-response-headers';

/**
Generate a structured, typed object for a given prompt and schema using a language model.
Expand Down Expand Up @@ -288,6 +289,19 @@ Logprobs for the completion.
this.rawResponse = options.rawResponse;
this.logprobs = options.logprobs;
}

/**
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`.
*/
toJsonResponse(init?: ResponseInit): Response {
return new Response(JSON.stringify(this.object), {
status: init?.status ?? 200,
headers: prepareResponseHeaders(init, {
contentType: 'application/json; charset=utf-8',
}),
});
}
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/core/core/generate-object/stream-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,7 @@ writes each text delta as a separate chunk.

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

Expand Down
Loading