forked from langchain-ai/langchainjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtools.ts
67 lines (62 loc) · 2.25 KB
/
tools.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { OpenAI as OpenAIClient } from "openai";
import { ToolDefinition } from "@langchain/core/language_models/base";
import { BindToolsInput } from "@langchain/core/language_models/chat_models";
import {
convertToOpenAIFunction,
isLangChainTool,
} from "@langchain/core/utils/function_calling";
import { zodFunction } from "openai/helpers/zod";
/**
* Formats a tool in either OpenAI format, or LangChain structured tool format
* into an OpenAI tool format. If the tool is already in OpenAI format, return without
* any changes. If it is in LangChain structured tool format, convert it to OpenAI tool format
* using OpenAI's `zodFunction` util, falling back to `convertToOpenAIFunction` if the parameters
* returned from the `zodFunction` util are not defined.
*
* @param {BindToolsInput} tool The tool to convert to an OpenAI tool.
* @param {Object} [fields] Additional fields to add to the OpenAI tool.
* @returns {ToolDefinition} The inputted tool in OpenAI tool format.
*/
export function _convertToOpenAITool(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tool: BindToolsInput,
fields?: {
/**
* If `true`, model output is guaranteed to exactly match the JSON Schema
* provided in the function definition.
*/
strict?: boolean;
}
): OpenAIClient.ChatCompletionTool {
let toolDef: OpenAIClient.ChatCompletionTool | undefined;
if (isLangChainTool(tool)) {
const oaiToolDef = zodFunction({
name: tool.name,
parameters: tool.schema,
description: tool.description,
});
if (!oaiToolDef.function.parameters) {
// Fallback to the `convertToOpenAIFunction` util if the parameters are not defined.
toolDef = {
type: "function",
function: convertToOpenAIFunction(tool, fields),
};
} else {
toolDef = {
type: oaiToolDef.type,
function: {
name: oaiToolDef.function.name,
description: oaiToolDef.function.description,
parameters: oaiToolDef.function.parameters,
...(fields?.strict !== undefined ? { strict: fields.strict } : {}),
},
};
}
} else {
toolDef = tool as ToolDefinition;
}
if (fields?.strict !== undefined) {
toolDef.function.strict = fields.strict;
}
return toolDef;
}