diff --git a/libs/langchain-openai/src/chat_models.ts b/libs/langchain-openai/src/chat_models.ts index 1c27f516926b..f44f33166065 100644 --- a/libs/langchain-openai/src/chat_models.ts +++ b/libs/langchain-openai/src/chat_models.ts @@ -1001,8 +1001,9 @@ export class ChatOpenAI< openAIFunctionDefinition = schema as FunctionDefinition; functionName = schema.name; } else { + functionName = schema.title ?? functionName; openAIFunctionDefinition = { - name: schema.title ?? functionName, + name: functionName, description: schema.description ?? "", parameters: schema, }; diff --git a/libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts b/libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts index 79d41b67a08b..7b2c4961bf59 100644 --- a/libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts +++ b/libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts @@ -172,6 +172,46 @@ Respond with a JSON object containing three keys: expect("number2" in result).toBe(true); }); +test("withStructuredOutput JSON schema", async () => { + const model = new ChatOpenAI({ + temperature: 0, + modelName: "gpt-4-turbo-preview", + }); + + const jsonSchema = { + title: "calculator", + description: "A simple calculator", + type: "object", + properties: { + operation: { + type: "string", + enum: ["add", "subtract", "multiply", "divide"], + }, + number1: { type: "number" }, + number2: { type: "number" }, + }, + }; + const modelWithStructuredOutput = model.withStructuredOutput(jsonSchema); + + const prompt = ChatPromptTemplate.fromMessages([ + "system", + `You are VERY bad at math and must always use a calculator. +Respond with a JSON object containing three keys: +'operation': the type of operation to execute, either 'add', 'subtract', 'multiply' or 'divide', +'number1': the first number to operate on, +'number2': the second number to operate on. +`, + "human", + "Please help me!! What is 2 + 2?", + ]); + const chain = prompt.pipe(modelWithStructuredOutput); + const result = await chain.invoke({}); + console.log(result); + expect("operation" in result).toBe(true); + expect("number1" in result).toBe(true); + expect("number2" in result).toBe(true); +}); + test("withStructuredOutput includeRaw true", async () => { const model = new ChatOpenAI({ temperature: 0,