@@ -7,8 +7,9 @@ import { APIPromise } from '../core/api-promise';
77import { Stream } from '../core/streaming' ;
88import { RequestOptions } from '../internal/request-options' ;
99import { ToolCall } from './shared' ;
10+ import { ResponseFormatJSONSchema } from './shared' ;
1011import { ChatCompletionStream , ChatCompletionStreamParams } from '../lib/ChatCompletionStream' ;
11- import { ExtractParsedContentFromParams } from '../lib/parser' ;
12+ import { validateInputTools , maybeParseChatCompletion , ExtractParsedContentFromParams } from '../lib/parser' ;
1213
1314export class Chat extends APIResource {
1415 /**
@@ -31,6 +32,57 @@ export class Chat extends APIResource {
3132 | APIPromise < Stream < ChatCompletionChunk > > ;
3233 }
3334
35+ /**
36+ * Create a completion and also parse the response
37+ *
38+ * This method automatically parses the response content into a structured format
39+ * based on the provided response_format. It uses either:
40+ *
41+ * 1. A Zod schema provided with zodResponseFormat() to validate and parse the output
42+ * 2. The raw JSON schema response if json_schema is specified directly
43+ *
44+ * For tools, it will parse function arguments into structured objects if the tools
45+ * are created using zodFunction().
46+ *
47+ * ```ts
48+ * const completion = await client.chat.parse({
49+ * model: 'palmyra-x-004',
50+ * messages: [
51+ * { role: 'system', content: 'You are a helpful math tutor.' },
52+ * { role: 'user', content: 'solve 8x + 31 = 2' },
53+ * ],
54+ * response_format: zodResponseFormat(
55+ * z.object({
56+ * steps: z.array(z.object({
57+ * explanation: z.string(),
58+ * answer: z.string(),
59+ * })),
60+ * final_answer: z.string(),
61+ * }),
62+ * 'math_answer',
63+ * ),
64+ * });
65+ *
66+ * const message = completion.choices[0]?.message;
67+ * if (message?.parsed) {
68+ * console.log(message.parsed);
69+ * console.log(message.parsed.final_answer);
70+ * }
71+ * ```
72+ */
73+ parse < Params extends ChatCompletionParseParams , ParsedT = ExtractParsedContentFromParams < Params > > (
74+ body : Params ,
75+ options ?: RequestOptions ,
76+ ) : APIPromise < ParsedChatCompletion < ParsedT > > {
77+ if ( body . tools ) {
78+ validateInputTools ( body . tools ) ;
79+ }
80+
81+ return this . chat ( body , options ) . _thenUnwrap ( ( completion ) =>
82+ maybeParseChatCompletion ( completion , body ) ,
83+ ) as APIPromise < ParsedChatCompletion < ParsedT > > ;
84+ }
85+
3486 /**
3587 * Creates a chat completion stream
3688 */
@@ -644,7 +696,9 @@ export interface ParsedChatCompletion<ParsedT> extends ChatCompletion {
644696 choices : Array < ParsedChoice < ParsedT > > ;
645697}
646698
647- export type ChatCompletionParseParams = ChatChatParamsNonStreaming ;
699+ export interface ChatCompletionParseParams extends ChatChatParamsNonStreaming {
700+ response_format ?: ResponseFormatJSONSchema ;
701+ }
648702
649703export declare namespace Chat {
650704 export {
0 commit comments