|
| 1 | +import { ChatCohere } from "@langchain/cohere"; |
| 2 | +import { HumanMessage } from "@langchain/core/messages"; |
| 3 | +import { z } from "zod"; |
| 4 | +import { DynamicStructuredTool } from "@langchain/core/tools"; |
| 5 | + |
| 6 | +const model = new ChatCohere({ |
| 7 | + apiKey: process.env.COHERE_API_KEY, // Default |
| 8 | +}); |
| 9 | + |
| 10 | +const magicFunctionTool = new DynamicStructuredTool({ |
| 11 | + name: "magic_function", |
| 12 | + description: "Apply a magic function to the input number", |
| 13 | + schema: z.object({ |
| 14 | + num: z.number().describe("The number to apply the magic function for"), |
| 15 | + }), |
| 16 | + func: async ({ num }) => { |
| 17 | + return `The magic function of ${num} is ${num + 5}`; |
| 18 | + }, |
| 19 | +}); |
| 20 | + |
| 21 | +const tools = [magicFunctionTool]; |
| 22 | +const modelWithTools = model.bindTools(tools); |
| 23 | + |
| 24 | +const messages = [new HumanMessage("What is the magic function of number 5?")]; |
| 25 | +const response = await modelWithTools.invoke(messages); |
| 26 | +/* |
| 27 | + AIMessage { |
| 28 | + content: 'I will use the magic_function tool to answer this question.', |
| 29 | + name: undefined, |
| 30 | + additional_kwargs: { |
| 31 | + response_id: 'd0b189e5-3dbf-493c-93f8-99ed4b01d96d', |
| 32 | + generationId: '8982a68f-c64c-48f8-bf12-0b4bea0018b6', |
| 33 | + chatHistory: [ [Object], [Object] ], |
| 34 | + finishReason: 'COMPLETE', |
| 35 | + meta: { apiVersion: [Object], billedUnits: [Object], tokens: [Object] }, |
| 36 | + toolCalls: [ [Object] ] |
| 37 | + }, |
| 38 | + response_metadata: { |
| 39 | + estimatedTokenUsage: { completionTokens: 54, promptTokens: 920, totalTokens: 974 }, |
| 40 | + response_id: 'd0b189e5-3dbf-493c-93f8-99ed4b01d96d', |
| 41 | + generationId: '8982a68f-c64c-48f8-bf12-0b4bea0018b6', |
| 42 | + chatHistory: [ [Object], [Object] ], |
| 43 | + finishReason: 'COMPLETE', |
| 44 | + meta: { apiVersion: [Object], billedUnits: [Object], tokens: [Object] }, |
| 45 | + toolCalls: [ [Object] ] |
| 46 | + }, |
| 47 | + tool_calls: [ |
| 48 | + { |
| 49 | + name: 'magic_function', |
| 50 | + args: [Object], |
| 51 | + id: '4ec98550-ba9a-4043-adfe-566230e5' |
| 52 | + } |
| 53 | + ], |
| 54 | + invalid_tool_calls: [], |
| 55 | + usage_metadata: { input_tokens: 920, output_tokens: 54, total_tokens: 974 } |
| 56 | + } |
| 57 | +*/ |
0 commit comments