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 tool message docs #3198

Merged
merged 2 commits into from
Nov 8, 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
13 changes: 13 additions & 0 deletions docs/docs/integrations/chat/openai.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ import OpenAIVision from "@examples/models/chat/integration_openai_vision.ts";

<CodeBlock language="typescript">{OpenAIVision}</CodeBlock>

## Tool calling

:::info
This feature is currently only available for `gpt-3.5-turbo-1106` and `gpt-4-1106-preview` models.
:::

More recent OpenAI chat models support calling multiple functions to get all required data to answer a question.
Here's an example how a conversation turn with this functionality might look:

import OpenAITools from "@examples/models/chat/integration_openai_tool_calls.ts";

<CodeBlock language="typescript">{OpenAITools}</CodeBlock>

## Custom URLs

You can customize the base URL the SDK sends requests to by passing a `configuration` parameter like this:
Expand Down
109 changes: 109 additions & 0 deletions examples/src/models/chat/integration_openai_tool_calls.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { ChatOpenAI } from "langchain/chat_models/openai";
import { ToolMessage } from "langchain/schema";

// Mocked out function, could be a database/API call in production
function getCurrentWeather(location: string, _unit?: string) {
if (location.toLowerCase().includes("tokyo")) {
return JSON.stringify({ location, temperature: "10", unit: "celsius" });
} else if (location.toLowerCase().includes("san francisco")) {
return JSON.stringify({
location,
temperature: "72",
unit: "fahrenheit",
});
} else {
return JSON.stringify({ location, temperature: "22", unit: "celsius" });
}
}

// Bind function to the model as a tool
const chat = new ChatOpenAI({
modelName: "gpt-3.5-turbo-1106",
maxTokens: 128,
}).bind({
tools: [
{
type: "function",
function: {
name: "get_current_weather",
description: "Get the current weather in a given location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city and state, e.g. San Francisco, CA",
},
unit: { type: "string", enum: ["celsius", "fahrenheit"] },
},
required: ["location"],
},
},
},
],
tool_choice: "auto",
});

// Ask initial question that requires multiple tool calls
const res = await chat.invoke([
["human", "What's the weather like in San Francisco, Tokyo, and Paris?"],
]);
console.log(res.additional_kwargs.tool_calls);
/*
[
{
id: 'call_IiOsjIZLWvnzSh8iI63GieUB',
type: 'function',
function: {
name: 'get_current_weather',
arguments: '{"location": "San Francisco", "unit": "celsius"}'
}
},
{
id: 'call_blQ3Oz28zSfvS6Bj6FPEUGA1',
type: 'function',
function: {
name: 'get_current_weather',
arguments: '{"location": "Tokyo", "unit": "celsius"}'
}
},
{
id: 'call_Kpa7FaGr3F1xziG8C6cDffsg',
type: 'function',
function: {
name: 'get_current_weather',
arguments: '{"location": "Paris", "unit": "celsius"}'
}
}
]
*/

// Format the results from calling the tool calls back to OpenAI as ToolMessages
const toolMessages = res.additional_kwargs.tool_calls?.map((toolCall) => {
const toolCallResult = getCurrentWeather(
JSON.parse(toolCall.function.arguments).location
);
return new ToolMessage({
tool_call_id: toolCall.id,
name: toolCall.function.name,
content: toolCallResult,
});
});

// Send the results back as the next step in the conversation
const finalResponse = await chat.invoke([
["human", "What's the weather like in San Francisco, Tokyo, and Paris?"],
res,
...(toolMessages ?? []),
]);

console.log(finalResponse);
/*
AIMessage {
content: 'The current weather in:\n' +
'- San Francisco is 72°F\n' +
'- Tokyo is 10°C\n' +
'- Paris is 22°C',
additional_kwargs: { function_call: undefined, tool_calls: undefined }
}
*/