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

Adds JSON mode support #3175

Merged
merged 3 commits into from
Nov 7, 2023
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
26 changes: 26 additions & 0 deletions examples/src/models/chat/integration_openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,29 @@ AIMessage {
}
}
*/

// Coerce response type with JSON mode.
// Requires "gpt-4-1106-preview" or later
const jsonModeModel = new ChatOpenAI({
modelName: "gpt-4-1106-preview",
maxTokens: 128,
}).bind({
response_format: {
type: "json_object",
},
});

// Must be invoked with a system message containing the string "JSON":
// https://platform.openai.com/docs/guides/text-generation/json-mode
const res = await jsonModeModel.invoke([
["system", "Only return JSON"],
["human", "Hi there!"],
]);
console.log(res);

/*
AIMessage {
content: '```json\n{\n "response": "Hello! How can I assist you today?"\n}\n```',
additional_kwargs: { function_call: undefined }
}
jacoblee93 marked this conversation as resolved.
Show resolved Hide resolved
*/
3 changes: 3 additions & 0 deletions langchain/src/chat_models/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ export interface ChatOpenAICallOptions
BaseFunctionCallOptions {
tools?: StructuredTool[];
promptIndex?: number;
response_format?: { type: "json_object" };
}

/**
Expand Down Expand Up @@ -194,6 +195,7 @@ export class ChatOpenAI<
"functions",
"tools",
"promptIndex",
"response_format",
];
}

Expand Down Expand Up @@ -373,6 +375,7 @@ export class ChatOpenAI<
? options?.tools.map(formatToOpenAIFunction)
: undefined),
function_call: options?.function_call,
response_format: options?.response_format,
...this.modelKwargs,
};
}
Expand Down
14 changes: 14 additions & 0 deletions langchain/src/chat_models/tests/chatopenai.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -775,3 +775,17 @@ test("Test ChatOpenAI token usage reporting for streaming calls", async () => {
expect(streamingTokenUsed).toEqual(nonStreamingTokenUsed);
}
});

test("Test ChatOpenAI JSON mode", async () => {
const chat = new ChatOpenAI({
modelName: "gpt-4-1106-preview",
maxTokens: 128,
}).bind({
response_format: {
type: "json_object",
},
});
const message = new HumanMessage("Hello!");
const res = await chat.invoke([["system", "Only return JSON"], message]);
console.log(JSON.stringify(res));
});