-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
220 lines (196 loc) · 6.47 KB
/
Copy pathindex.js
File metadata and controls
220 lines (196 loc) · 6.47 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import {DynamicStructuredTool} from '@langchain/core/tools';
import {ToolMessage} from '@langchain/core/messages';
import {loadMcpTools} from '@langchain/mcp-adapters';
import {Client} from '@modelcontextprotocol/sdk/client/index.js';
import {StreamableHTTPClientTransport} from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import {z} from 'zod';
import textLD from 'text-ld';
import debug from 'debug';
import _pkg from './package.json' with {type: 'json'};
import AgentService from './agent.js';
const metadataSchema = z.record(z.string(), z.unknown()).optional();
const MIN_QUERY_LENGTH = 2;
const MAX_QUERY_LENGTH = 256;
export default class SecretaryAI {
#client = new Client({
name: _pkg.name,
version: _pkg.version,
});
constructor(mcpServerUrl, serverName, model, db) {
this.url = mcpServerUrl;
this.serverName = serverName;
if (!model.bindTools) {
throw new Error('Missing model bindTools');
}
this.model = model;
this.tools = [];
this._isConnected = false;
this.db = db;
}
get client() {
return this.#client;
}
get timeZone() {
return process.env.TZ ?? 'UTC';
}
get currentDate() {
return new Intl.DateTimeFormat('ru', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour12: false,
timeZone: this.timeZone,
}).format(new Date());
}
get systemPrompt() {
return `
Ты — Виртуальный Секретарь
:: Инструкции:
- Если данных недостаточно — уточни их у пользователя. НЕ выдумывай информацию
:: Контекст:
- Дата клиента: ${this.currentDate}
- Таймзона: ${this.timeZone}
:: Используй только доступные инструменты согласно allowed_tools. Не совершай разрушительных действий без подтверждения пользователя.
`
.replace(/\s+/g, ' ')
.trim();
}
static getDescriptionWithTags(input) {
const match = input.match(/^\[(.*?)\]\s*(.*)$/);
if (match) {
return {
tags: match[1].split(',').map(tag => tag.trim()),
description: match[2],
}
}
return {
tags: [],
description: input,
}
}
async #loadTools() {
const tools = await loadMcpTools(this.serverName, this.client, {
throwOnLoadError: true,
prefixToolNameWithServerName: false,
additionalToolNamePrefix: '',
useStandardContentBlocks: false,
});
for (const tool of tools) {
const {description, tags} = SecretaryAI.getDescriptionWithTags(tool.description);
const t = new DynamicStructuredTool({
name: tool.name,
description: description,
schema: new z.Schema(tool.schema),
returnDirect: false,
tags: tags,
verbose: tool.verbose,
func: async (args) => {
let data;
try {
data = await this.client.callTool({
name: tool.name,
arguments: args,
});
} catch (error) {
if ([401, 407, 451].includes(error.code)) {
this._isConnected = false;
}
return new ToolMessage({
name: tool.name,
content: 'Произошла ошибка сети. Попробуйте заново',
status: 'error',
artifact: [],
});
}
const {content, isError, artifact = []} = data;
if (isError) {
/**
* @type {import("@langchain/core/messages").InvalidToolCall}
*/
const brokenToolCall = {
type: 'invalid_tool_call',
args: JSON.stringify(args),
error: content,
};
return new ToolMessage({
name: tool.name,
tool_call_id: brokenToolCall.id,
metadata: args,
status: 'error',
content: 'Произошла ошибка',
artifact: artifact,
});
}
return new ToolMessage({
name: tool.name,
content: content?.[0]?.text || 'Нет данных',
status: 'success',
artifact: artifact,
});
},
});
this.tools.push(t);
}
}
get isConnected() {
return this._isConnected;
}
async connect(headers = new Headers()) {
debug.log('connecting... headers:', [...headers.keys()]);
await this.client.close();
this._isConnected = false;
headers.set('User-Agent', `${_pkg.name}/${_pkg.version}`);
headers.set('Accept', 'text/markdown;q=0.9,text/plain;q=0.8,text/html;q=0.7,*/*;q=0.5');
headers.set('Content-Type', 'application/json');
const transport = new StreamableHTTPClientTransport(this.url, {
requestInit: {
headers,
},
});
try {
await this.client.connect(transport);
await this.#loadTools();
} catch (error) {
debug.log(error);
this._isConnected = false;
throw error;
}
this._agent = new AgentService(this.model, this.tools, this.systemPrompt, this.db);
this._isConnected = true;
}
get agent() {
return this._agent;
}
async clear(config) {
await this.agent.clearState(config);
}
async chat(query, config = {}) {
if (query.length <= MIN_QUERY_LENGTH) {
throw new Error('Запрос не должен быть пустым');
}
if (query.length > MAX_QUERY_LENGTH) {
throw new Error(`Запрос должен быть не более ${MAX_QUERY_LENGTH} символов`);
}
const {text} = textLD.creativeWork(query);
if (!this.isConnected) {
await this.connect(config.headers);
}
const { messages, artifact } = await this.agent.execute({
input: text,
}, {
recursionLimit: 10,
configurable: config.configurable,
callbacks: [], // todo - настроить consoleHandler и Debug для логов и подсчета стоимости
tags: [], // todo - настроить тегов для экспериментов или указания например что это telegram
metadata: metadataSchema.parse(config.metadata),
});
const lastMessage = messages[messages.length - 1];
return {
content: [{
type: 'text',
text: lastMessage.content,
}],
artifact: artifact || [],
};
}
}