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鈥檒l 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 1 commit
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",
},
});

// 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
*/
1 change: 1 addition & 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" };
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
response_format?: { type: "json" };
response_format?: { type: "json_object" };

api docs

}

/**
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",
jacoblee93 marked this conversation as resolved.
Show resolved Hide resolved
},
});
const message = new HumanMessage("Hello!");
const res = await chat.invoke([["system", "Only return JSON"], message]);
console.log(JSON.stringify(res));
});
Loading