@librechat/agents 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/cjs/common/enum.cjs +0 -1
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/llm/providers.cjs +0 -2
  4. package/dist/cjs/llm/providers.cjs.map +1 -1
  5. package/dist/cjs/main.cjs +2 -0
  6. package/dist/cjs/main.cjs.map +1 -1
  7. package/dist/cjs/tools/Calculator.cjs +45 -0
  8. package/dist/cjs/tools/Calculator.cjs.map +1 -0
  9. package/dist/esm/common/enum.mjs +0 -1
  10. package/dist/esm/common/enum.mjs.map +1 -1
  11. package/dist/esm/llm/providers.mjs +0 -2
  12. package/dist/esm/llm/providers.mjs.map +1 -1
  13. package/dist/esm/main.mjs +1 -0
  14. package/dist/esm/main.mjs.map +1 -1
  15. package/dist/esm/tools/Calculator.mjs +24 -0
  16. package/dist/esm/tools/Calculator.mjs.map +1 -0
  17. package/dist/types/common/enum.d.ts +0 -1
  18. package/dist/types/index.d.ts +1 -0
  19. package/dist/types/tools/Calculator.d.ts +8 -0
  20. package/dist/types/types/llm.d.ts +1 -6
  21. package/package.json +5 -3
  22. package/src/common/enum.ts +0 -1
  23. package/src/index.ts +1 -0
  24. package/src/llm/providers.ts +0 -2
  25. package/src/scripts/abort.ts +34 -15
  26. package/src/scripts/cli.ts +25 -20
  27. package/src/scripts/cli2.ts +23 -15
  28. package/src/scripts/cli3.ts +35 -29
  29. package/src/scripts/cli4.ts +1 -2
  30. package/src/scripts/cli5.ts +1 -2
  31. package/src/scripts/code_exec.ts +1 -2
  32. package/src/scripts/code_exec_simple.ts +1 -2
  33. package/src/scripts/content.ts +33 -15
  34. package/src/scripts/simple.ts +1 -2
  35. package/src/scripts/stream.ts +33 -15
  36. package/src/scripts/test-tools-before-handoff.ts +17 -28
  37. package/src/scripts/tools.ts +4 -6
  38. package/src/specs/anthropic.simple.test.ts +1 -1
  39. package/src/specs/azure.simple.test.ts +1 -1
  40. package/src/specs/openai.simple.test.ts +1 -1
  41. package/src/specs/openrouter.simple.test.ts +1 -1
  42. package/src/tools/Calculator.ts +25 -0
  43. package/src/types/llm.ts +0 -6
  44. package/dist/types/tools/example.d.ts +0 -78
  45. package/src/proto/CollabGraph.ts +0 -269
  46. package/src/proto/TaskManager.ts +0 -243
  47. package/src/proto/collab.ts +0 -200
  48. package/src/proto/collab_design.ts +0 -184
  49. package/src/proto/collab_design_v2.ts +0 -224
  50. package/src/proto/collab_design_v3.ts +0 -255
  51. package/src/proto/collab_design_v4.ts +0 -220
  52. package/src/proto/collab_design_v5.ts +0 -251
  53. package/src/proto/collab_graph.ts +0 -181
  54. package/src/proto/collab_original.ts +0 -123
  55. package/src/proto/example.ts +0 -93
  56. package/src/proto/example_new.ts +0 -68
  57. package/src/proto/example_old.ts +0 -201
  58. package/src/proto/example_test.ts +0 -152
  59. package/src/proto/example_test_anthropic.ts +0 -100
  60. package/src/proto/log_stream.ts +0 -202
  61. package/src/proto/main_collab_community_event.ts +0 -133
  62. package/src/proto/main_collab_design_v2.ts +0 -96
  63. package/src/proto/main_collab_design_v4.ts +0 -100
  64. package/src/proto/main_collab_design_v5.ts +0 -135
  65. package/src/proto/main_collab_global_analysis.ts +0 -122
  66. package/src/proto/main_collab_hackathon_event.ts +0 -153
  67. package/src/proto/main_collab_space_mission.ts +0 -153
  68. package/src/proto/main_philosophy.ts +0 -210
  69. package/src/proto/original_script.ts +0 -126
  70. package/src/proto/standard.ts +0 -100
  71. package/src/proto/stream.ts +0 -56
  72. package/src/proto/tasks.ts +0 -118
  73. package/src/proto/tools/global_analysis_tools.ts +0 -86
  74. package/src/proto/tools/space_mission_tools.ts +0 -60
  75. package/src/proto/vertexai.ts +0 -54
  76. package/src/tools/example.ts +0 -129
@@ -1,126 +0,0 @@
1
- // src/main.ts
2
- import dotenv from 'dotenv';
3
- import { TavilySearchResults } from '@langchain/community/tools/tavily_search';
4
- import type * as t from '@/types';
5
- import {
6
- ChatModelStreamHandler,
7
- LLMStreamHandler,
8
- } from '@/stream';
9
- import { GraphEvents, Providers } from '@/common';
10
- import { Processor } from '@/processor';
11
-
12
- dotenv.config();
13
-
14
- const userName = 'Jo';
15
- const location = 'New York';
16
- const currentDate = new Date().toLocaleString();
17
-
18
- async function testStreaming() {
19
- const conversationHistory: string[][] = [];
20
-
21
- const customHandlers = {
22
- [GraphEvents.LLM_STREAM]: new LLMStreamHandler(),
23
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
24
- [GraphEvents.LLM_START]: {
25
- handle: (event: string, data: t.StreamEventData) => {
26
- console.dir(data, { depth: null });
27
- }
28
- },
29
- [GraphEvents.LLM_END]: {
30
- handle: (event: string, data: t.StreamEventData) => {
31
- console.dir(data, { depth: null });
32
-
33
- const response = data.output.generations[0][0].message.content;
34
-
35
- if (response.trim() !== '') {
36
- conversationHistory.push(['assistant', response]);
37
- console.log('Updated conversation history:', conversationHistory);
38
- }
39
- }
40
- },
41
- [GraphEvents.CHAT_MODEL_END]: {
42
- handle: (event: string, data: t.StreamEventData) => {
43
- const response = data?.output?.content;
44
-
45
- if (Array.isArray(response)) {
46
- console.dir(response, { depth: null });
47
- } else if (typeof response === 'string' && response.trim() !== '') {
48
- conversationHistory.push(['assistant', response]);
49
- console.log('Updated conversation history:', conversationHistory);
50
- }
51
- }
52
- },
53
- [GraphEvents.TOOL_END]: {
54
- handle: (event: string, data: t.StreamEventData) => {
55
- console.dir(data, { depth: null });
56
- }
57
- },
58
- };
59
-
60
- const llmConfig: t.LLMConfig = {
61
- provider: Providers.OPENAI,
62
- model: 'gpt-4o',
63
- temperature: 0.7,
64
- };
65
-
66
- // const llmConfig: t.LLMConfig = {
67
- // provider: Providers.ANTHROPIC,
68
- // model: 'claude-3-haiku-20240307',
69
- // streaming: true,
70
- // };
71
-
72
- // const llmConfig: t.LLMConfig = {
73
- // provider: Providers.MISTRALAI,
74
- // model: 'mistral-large-latest',
75
- // };
76
-
77
- // const llmConfig: t.LLMConfig = {
78
- // provider: Providers.VERTEXAI,
79
- // modelName: 'gemini-1.5-flash-001',
80
- // streaming: true,
81
- // };
82
-
83
- // const llmConfig: t.LLMConfig = {
84
- // provider: Providers.BEDROCK,
85
- // model: 'anthropic.claude-3-sonnet-20240229-v1:0',
86
- // region: process.env.BEDROCK_AWS_REGION,
87
- // credentials: {
88
- // accessKeyId: process.env.BEDROCK_AWS_ACCESS_KEY_ID!,
89
- // secretAccessKey: process.env.BEDROCK_AWS_SECRET_ACCESS_KEY!,
90
- // },
91
- // };
92
-
93
- const processor = new Processor({
94
- llmConfig,
95
- customHandlers,
96
- tools: [new TavilySearchResults({})],
97
- });
98
-
99
- const config = {
100
- configurable: { thread_id: 'conversation-num-1' },
101
- streamMode: 'values',
102
- version: 'v2' as const,
103
- };
104
-
105
- console.log('\nTest 1: Initial greeting');
106
-
107
- conversationHistory.push(['user', `Hi I'm ${userName}.`]);
108
- let inputs = { messages: conversationHistory };
109
- await processor.processStream(inputs, config);
110
-
111
- console.log('\nTest 2: Weather query');
112
-
113
- const userMessage = `
114
- Make a search for the weather in ${location} today, which is ${currentDate}.
115
- Make sure to always refer to me by name.
116
- After giving me a thorough summary, tell me a joke about the weather forecast we went over.
117
- `;
118
-
119
- conversationHistory.push(['user', userMessage]);
120
-
121
- inputs = { messages: conversationHistory };
122
- await processor.processStream(inputs, config);
123
-
124
- }
125
-
126
- testStreaming();
@@ -1,100 +0,0 @@
1
- // src/main_standard.ts
2
- import dotenv from 'dotenv';
3
- import { TavilySearchResults } from '@langchain/community/tools/tavily_search';
4
- import type * as t from '@/types';
5
- import {
6
- ChatModelStreamHandler,
7
- LLMStreamHandler,
8
- } from '@/stream';
9
- import { GraphEvents, Providers } from '@/common';
10
- import { Processor } from '@/processor';
11
- import { HumanMessage, BaseMessage } from '@langchain/core/messages';
12
-
13
- dotenv.config();
14
-
15
- const userName = 'Jo';
16
- const location = 'New York';
17
- const currentDate = new Date().toLocaleString();
18
-
19
- async function testStandardStreaming() {
20
- const conversationHistory: BaseMessage[] = [];
21
-
22
- const customHandlers = {
23
- [GraphEvents.LLM_STREAM]: new LLMStreamHandler(),
24
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
25
- [GraphEvents.LLM_START]: {
26
- handle: (event: string, data: t.StreamEventData) => {
27
- console.dir(data, { depth: null });
28
- }
29
- },
30
- [GraphEvents.LLM_END]: {
31
- handle: (event: string, data: t.StreamEventData) => {
32
- console.dir(data, { depth: null });
33
-
34
- const response = data.output.generations[0][0].message.content;
35
-
36
- if (response.trim() !== '') {
37
- conversationHistory.push(new HumanMessage(response));
38
- console.log('Updated conversation history:', conversationHistory);
39
- }
40
- }
41
- },
42
- [GraphEvents.CHAT_MODEL_END]: {
43
- handle: (event: string, data: t.StreamEventData) => {
44
- const response = data?.output?.content;
45
-
46
- if (Array.isArray(response)) {
47
- console.dir(response, { depth: null });
48
- } else if (typeof response === 'string' && response.trim() !== '') {
49
- conversationHistory.push(new HumanMessage(response));
50
- console.log('Updated conversation history:', conversationHistory);
51
- }
52
- }
53
- },
54
- [GraphEvents.TOOL_END]: {
55
- handle: (event: string, data: t.StreamEventData) => {
56
- console.dir(data, { depth: null });
57
- }
58
- },
59
- };
60
-
61
- const processor = await Processor.create<t.IState>({
62
- graphConfig: {
63
- type: 'standard',
64
- llmConfig: {
65
- provider: Providers.OPENAI,
66
- model: 'gpt-4',
67
- temperature: 0.7,
68
- },
69
- tools: [new TavilySearchResults({})],
70
- },
71
- customHandlers,
72
- });
73
-
74
- const config = {
75
- configurable: { thread_id: 'conversation-num-1' },
76
- streamMode: 'values',
77
- version: 'v2' as const,
78
- };
79
-
80
- console.log('\nTest 1: Initial greeting');
81
-
82
- conversationHistory.push(new HumanMessage(`Hi I'm ${userName}.`));
83
- let inputs = { messages: conversationHistory };
84
- await processor.processStream(inputs, config);
85
-
86
- console.log('\nTest 2: Weather query');
87
-
88
- const userMessage = `
89
- Make a search for the weather in ${location} today, which is ${currentDate}.
90
- Make sure to always refer to me by name.
91
- After giving me a thorough summary, tell me a joke about the weather forecast we went over.
92
- `;
93
-
94
- conversationHistory.push(new HumanMessage(userMessage));
95
-
96
- inputs = { messages: conversationHistory };
97
- await processor.processStream(inputs, config);
98
- }
99
-
100
- testStandardStreaming();
@@ -1,56 +0,0 @@
1
- import type { ChatGenerationChunk } from '@langchain/core/outputs';
2
- import type { RunnableConfig } from '@langchain/core/runnables';
3
- import type { AIMessageChunk } from '@langchain/core/messages';
4
- import type * as t from '@/types/graph';
5
-
6
- export interface EventHandler {
7
- handle(event: string, data: t.StreamEventData): void;
8
- }
9
-
10
- export class HandlerRegistry {
11
- private handlers: Map<string, EventHandler> = new Map();
12
-
13
- register(eventType: string, handler: EventHandler) {
14
- this.handlers.set(eventType, handler);
15
- }
16
-
17
- getHandler(eventType: string): EventHandler | undefined {
18
- return this.handlers.get(eventType);
19
- }
20
- }
21
-
22
- export class LLMStreamHandler implements EventHandler {
23
- handle(event: string, data: t.StreamEventData) {
24
- const chunk: ChatGenerationChunk = data?.chunk;
25
- const msg = chunk.message as AIMessageChunk;
26
- if (msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {
27
- console.log(msg.tool_call_chunks);
28
- } else {
29
- const content = msg.content || '';
30
- if (typeof content === 'string') {
31
- process.stdout.write(content);
32
- }
33
- }
34
- }
35
- }
36
-
37
- export class GraphStreamProcessor {
38
- private handlerRegistry: HandlerRegistry;
39
-
40
- constructor(handlerRegistry: HandlerRegistry) {
41
- this.handlerRegistry = handlerRegistry;
42
- }
43
-
44
- async processStream<RunInput>(
45
- graph: t.Graph,
46
- inputs: RunInput,
47
- config: Partial<RunnableConfig> & { version: 'v1' | 'v2' },
48
- ) {
49
- for await (const event of graph.streamEvents(inputs, config)) {
50
- const handler = this.handlerRegistry.getHandler(event.event);
51
- if (handler) {
52
- handler.handle(event.event, event.data);
53
- }
54
- }
55
- }
56
- }
@@ -1,118 +0,0 @@
1
- import fs from 'fs';
2
- import util from 'util';
3
- import dotenv from 'dotenv';
4
- import { HumanMessage } from '@langchain/core/messages';
5
- import type * as t from '@/types';
6
- import {
7
- ChatModelStreamHandler,
8
- } from '@/stream';
9
- import { Processor } from '@/processor';
10
- import { taskManagerPrompt } from '@/prompts/taskmanager';
11
- import { tavilyTool, chartTool } from '@/tools/example';
12
- import { GraphEvents, Providers } from '@/common';
13
-
14
- dotenv.config();
15
-
16
- // Create a write stream
17
- const logFile = fs.createWriteStream('output.log', { flags: 'a' });
18
-
19
- // Redirect console.log and console.error
20
- const originalConsoleLog = console.log;
21
- const originalConsoleError = console.error;
22
-
23
- console.log = function(...args) {
24
- logFile.write(util.format.apply(null, args) + '\n');
25
- originalConsoleLog.apply(console, args);
26
- };
27
-
28
- console.error = function(...args) {
29
- logFile.write(util.format.apply(null, args) + '\n');
30
- originalConsoleError.apply(console, args);
31
- };
32
-
33
- async function testTaskManagerStreaming() {
34
- const customHandlers = {
35
- [GraphEvents.LLM_STREAM]: new LLMStreamHandler(),
36
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
37
- [GraphEvents.LLM_START]: {
38
- handle: (event: string, data: t.StreamEventData) => {
39
- console.log('LLM Start:', event);
40
- }
41
- },
42
- [GraphEvents.LLM_END]: {
43
- handle: (event: string, data: t.StreamEventData) => {
44
- console.log('LLM End:', event);
45
- }
46
- },
47
- [GraphEvents.CHAT_MODEL_END]: {
48
- handle: (event: string, data: t.StreamEventData) => {
49
- console.log('Chat Model End:', event);
50
- }
51
- },
52
- [GraphEvents.TOOL_END]: {
53
- handle: (event: string, data: t.StreamEventData) => {
54
- console.log('Tool End:', event);
55
- console.dir(data, { depth: null });
56
- }
57
- },
58
- };
59
-
60
- const processor = await Processor.create<TaskManagerStateChannels>({
61
- graphConfig: {
62
- type: 'taskmanager',
63
- members: [
64
- {
65
- name: 'researcher',
66
- systemPrompt: 'You are a web researcher. You may use the Tavily search engine to search the web for important information, so the Chart Generator in your team can make useful plots.',
67
- tools: [tavilyTool],
68
- llmConfig: {
69
- provider: Providers.OPENAI,
70
- model: 'gpt-4o',
71
- temperature: 0,
72
- },
73
- },
74
- {
75
- name: 'chart_generator',
76
- systemPrompt: 'You excel at generating bar charts. Use the researcher\'s information to generate the charts.',
77
- tools: [chartTool],
78
- llmConfig: {
79
- provider: Providers.OPENAI,
80
- model: 'gpt-4o',
81
- temperature: 0.2,
82
- },
83
- },
84
- ],
85
- supervisorConfig: {
86
- systemPrompt: taskManagerPrompt,
87
- llmConfig: {
88
- provider: Providers.OPENAI,
89
- model: 'gpt-4o',
90
- temperature: 0,
91
- },
92
- },
93
- },
94
- customHandlers,
95
- });
96
-
97
- const config = {
98
- configurable: { thread_id: 'taskmanager-conversation-1' },
99
- streamMode: 'values',
100
- version: 'v2' as const,
101
- };
102
-
103
- console.log('\nTaskManager Test: Create a chart');
104
-
105
- const input = {
106
- messages: [new HumanMessage('Create a chart showing the population growth of the top 5 most populous countries over the last 50 years.')],
107
- };
108
-
109
- await processor.processStream(input, config);
110
- }
111
-
112
- async function main() {
113
- await testTaskManagerStreaming();
114
- }
115
-
116
- main().catch(console.error).finally(() => {
117
- logFile.end();
118
- });
@@ -1,86 +0,0 @@
1
- // src/tools/global_analysis_tools.ts
2
- import { DynamicStructuredTool } from '@langchain/core/tools';
3
- import { z } from 'zod';
4
- import fetch from 'node-fetch';
5
-
6
- export const WeatherDataTool = new DynamicStructuredTool({
7
- name: 'get_weather_data',
8
- description: 'Fetches current weather data for a given city.',
9
- schema: z.object({
10
- city: z.string(),
11
- }),
12
- func: async ({ city }) => {
13
- try {
14
- // Try OpenMeteo API first (doesn't require API key)
15
- const url = 'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current_weather=true';
16
- const response = await fetch(url);
17
- const data = await response.json();
18
-
19
- if (data.error) {
20
- throw new Error(data.reason);
21
- }
22
-
23
- return JSON.stringify(data);
24
- } catch (error) {
25
- console.error(`Error fetching weather data: ${(error as Error).message}`);
26
- // Implement fallback or return error message
27
- return JSON.stringify({ error: 'Unable to fetch weather data. Please try again later.' });
28
- }
29
- }
30
- });
31
-
32
- // Time Zone Tool
33
- export const TimeZoneTool = new DynamicStructuredTool({
34
- name: 'get_time_zone_info',
35
- description: 'Fetches time zone information for a given location.',
36
- schema: z.object({
37
- latitude: z.number(),
38
- longitude: z.number(),
39
- }),
40
- func: async ({ latitude, longitude }) => {
41
- const url = `http://api.geonames.org/timezoneJSON?lat=${latitude}&lng=${longitude}&username=demo`;
42
- const response = await fetch(url);
43
- const data = await response.json();
44
- return JSON.stringify(data);
45
- }
46
- });
47
-
48
- // Currency Conversion Tool
49
- export const CurrencyConversionTool = new DynamicStructuredTool({
50
- name: 'convert_currency',
51
- description: 'Converts an amount from one currency to another.',
52
- schema: z.object({
53
- from: z.string(),
54
- to: z.string(),
55
- amount: z.number(),
56
- }),
57
- func: async ({ from, to, amount }) => {
58
- const url = `https://api.exchangerate-api.com/v4/latest/${from}`;
59
- const response = await fetch(url);
60
- const data = await response.json();
61
- const rate = data.rates[to];
62
- const convertedAmount = amount * rate;
63
- return JSON.stringify({
64
- from,
65
- to,
66
- amount,
67
- convertedAmount,
68
- rate,
69
- });
70
- }
71
- });
72
-
73
- // IP Geolocation Tool
74
- export const IPGeolocationTool = new DynamicStructuredTool({
75
- name: 'get_ip_geolocation',
76
- description: 'Fetches geolocation information for a given IP address.',
77
- schema: z.object({
78
- ip: z.string(),
79
- }),
80
- func: async ({ ip }) => {
81
- const url = `http://ip-api.com/json/${ip}`;
82
- const response = await fetch(url);
83
- const data = await response.json();
84
- return JSON.stringify(data);
85
- }
86
- });
@@ -1,60 +0,0 @@
1
- // src/tools/space_mission_tools.ts
2
- import { DynamicStructuredTool } from '@langchain/core/tools';
3
- import { z } from 'zod';
4
- import fetch from 'node-fetch';
5
- import { createHash } from 'crypto';
6
-
7
- // NASA APOD (Astronomy Picture of the Day) Tool
8
- export const NasaAPODTool = new DynamicStructuredTool({
9
- name: 'get_nasa_apod',
10
- description: 'Fetches NASA\'s Astronomy Picture of the Day.',
11
- schema: z.object({
12
- date: z.string().optional(),
13
- }),
14
- func: async ({ date }) => {
15
- const apiKey = process.env.NASA_API_KEY;
16
- const url = `https://api.nasa.gov/planetary/apod?api_key=${apiKey}${date ? `&date=${date}` : ''}`;
17
- const response = await fetch(url);
18
- const data = await response.json();
19
- return JSON.stringify(data);
20
- }
21
- });
22
-
23
- // ISS Location Tool
24
- export const ISSLocationTool = new DynamicStructuredTool({
25
- name: 'get_iss_location',
26
- description: 'Fetches the current location of the International Space Station.',
27
- schema: z.object({}),
28
- func: async () => {
29
- const url = 'http://api.open-notify.org/iss-now.json';
30
- const response = await fetch(url);
31
- const data = await response.json();
32
- return JSON.stringify(data);
33
- }
34
- });
35
-
36
- // Space Launch Schedule Tool
37
- export const LaunchScheduleTool = new DynamicStructuredTool({
38
- name: 'get_launch_schedule',
39
- description: 'Fetches upcoming space launches.',
40
- schema: z.object({
41
- limit: z.number().optional(),
42
- }),
43
- func: async ({ limit = 5 }) => {
44
- const url = `https://ll.thespacedevs.com/2.2.0/launch/upcoming/?limit=${limit}`;
45
- const response = await fetch(url);
46
- const data = await response.json();
47
- return JSON.stringify(data);
48
- }
49
- });
50
-
51
- // Mission ID Generator Tool
52
- export const MissionIDGenerator = new DynamicStructuredTool({
53
- name: 'generate_mission_id',
54
- description: 'Generates a unique ID for space missions.',
55
- schema: z.object({}),
56
- func: async () => {
57
- const uniqueID = createHash('sha256').update(Date.now().toString()).digest('hex');
58
- return `MISSION-${uniqueID.substring(0, 8)}`;
59
- }
60
- });
@@ -1,54 +0,0 @@
1
- import { AgentExecutor , createToolCallingAgent } from 'langchain/agents';
2
- import { StructuredTool } from '@langchain/core/tools';
3
- import { BaseMessage } from '@langchain/core/messages';
4
- import { ChatPromptTemplate } from '@langchain/core/prompts';
5
- import { ChatVertexAI, ChatVertexAIInput } from '@langchain/google-vertexai';
6
- import { RunnableSequence, RunnablePassthrough } from '@langchain/core/runnables';
7
-
8
- type VertexAIToolCallingAgentInput = {
9
- vertexAIConfig: ChatVertexAIInput;
10
- tools: StructuredTool[];
11
- chatHistory: BaseMessage[];
12
- };
13
-
14
- export function createVertexAgent({
15
- vertexAIConfig,
16
- tools,
17
- chatHistory,
18
- }: VertexAIToolCallingAgentInput) {
19
- // Define the LLM
20
- const llm = new ChatVertexAI(vertexAIConfig);
21
-
22
- // Define the prompt template
23
- const prompt = ChatPromptTemplate.fromMessages([
24
- ['system', 'You are a helpful assistant'],
25
- ['human', '{input}'],
26
- ['human', 'Current conversation:\n{chat_history}'],
27
- ['human', 'Human: {input}'],
28
- ['assistant', '{agent_scratchpad}'],
29
- ]);
30
-
31
- // Create the agent
32
- const agent = createToolCallingAgent({
33
- llm,
34
- tools,
35
- prompt,
36
- });
37
-
38
- // Create the agent executor
39
- const agentExecutor = new AgentExecutor({
40
- agent,
41
- tools,
42
- });
43
-
44
- // Create the runnable
45
- const runnable = RunnableSequence.from([
46
- {
47
- input: new RunnablePassthrough(),
48
- chat_history: () => chatHistory,
49
- },
50
- agentExecutor,
51
- ]);
52
-
53
- return runnable;
54
- }