Datasets:
File size: 10,056 Bytes
8d88d9b |
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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
import { ToolResultStatus, type ToolCall, type Tool, type ToolResult } from "$lib/types/Tool";
import { v4 as uuidV4 } from "uuid";
import { getCallMethod, toolFromConfigs, type BackendToolContext } from "../tools";
import {
MessageToolUpdateType,
MessageUpdateStatus,
MessageUpdateType,
type MessageUpdate,
} from "$lib/types/MessageUpdate";
import type { TextGenerationContext } from "./types";
import directlyAnswer from "../tools/directlyAnswer";
import websearch from "../tools/web/search";
import { z } from "zod";
import { logger } from "../logger";
import { extractJson, toolHasName } from "../tools/utils";
import { mergeAsyncGenerators } from "$lib/utils/mergeAsyncGenerators";
import { MetricsServer } from "../metrics";
import { stringifyError } from "$lib/utils/stringifyError";
import { collections } from "../database";
import { ObjectId } from "mongodb";
import type { Message } from "$lib/types/Message";
import type { Assistant } from "$lib/types/Assistant";
import { assistantHasWebSearch } from "./assistant";
export async function getTools(
toolsPreference: Array<string>,
assistant: Pick<Assistant, "rag" | "tools"> | undefined
): Promise<Tool[]> {
let preferences = toolsPreference;
if (assistant) {
if (assistant?.tools?.length) {
preferences = assistant.tools;
if (assistantHasWebSearch(assistant)) {
preferences.push(websearch._id.toString());
}
} else {
if (assistantHasWebSearch(assistant)) {
return [websearch, directlyAnswer];
}
return [directlyAnswer];
}
}
// filter based on tool preferences, add the tools that are on by default
const activeConfigTools = toolFromConfigs.filter((el) => {
if (el.isLocked && el.isOnByDefault && !assistant) return true;
return preferences?.includes(el._id.toString()) ?? (el.isOnByDefault && !assistant);
});
// find tool where the id is in preferences
const activeCommunityTools = await collections.tools
.find({
_id: { $in: preferences.map((el) => new ObjectId(el)) },
})
.toArray()
.then((el) => el.map((el) => ({ ...el, call: getCallMethod(el) })));
return [...activeConfigTools, ...activeCommunityTools];
}
async function* callTool(
ctx: BackendToolContext,
tools: Tool[],
call: ToolCall
): AsyncGenerator<MessageUpdate, ToolResult | undefined, undefined> {
const uuid = uuidV4();
const tool = tools.find((el) => toolHasName(call.name, el));
if (!tool) {
return { call, status: ToolResultStatus.Error, message: `Could not find tool "${call.name}"` };
}
// Special case for directly_answer tool where we ignore
if (toolHasName(directlyAnswer.name, tool)) return;
const startTime = Date.now();
MetricsServer.getMetrics().tool.toolUseCount.inc({ tool: call.name });
yield {
type: MessageUpdateType.Tool,
subtype: MessageToolUpdateType.Call,
uuid,
call,
};
try {
const toolResult = yield* tool.call(call.parameters, ctx, uuid);
yield {
type: MessageUpdateType.Tool,
subtype: MessageToolUpdateType.Result,
uuid,
result: { ...toolResult, call, status: ToolResultStatus.Success },
};
MetricsServer.getMetrics().tool.toolUseDuration.observe(
{ tool: call.name },
Date.now() - startTime
);
await collections.tools.findOneAndUpdate({ _id: tool._id }, { $inc: { useCount: 1 } });
return { ...toolResult, call, status: ToolResultStatus.Success };
} catch (error) {
MetricsServer.getMetrics().tool.toolUseCountError.inc({ tool: call.name });
logger.error(error, `Failed while running tool ${call.name}. ${stringifyError(error)}`);
yield {
type: MessageUpdateType.Tool,
subtype: MessageToolUpdateType.Error,
uuid,
message:
"An error occurred while calling the tool " + call.name + ": " + stringifyError(error),
};
return {
call,
status: ToolResultStatus.Error,
message:
"An error occurred while calling the tool " + call.name + ": " + stringifyError(error),
};
}
}
export async function* runTools(
ctx: TextGenerationContext,
tools: Tool[],
preprompt?: string
): AsyncGenerator<MessageUpdate, ToolResult[], undefined> {
const { endpoint, conv, messages, assistant, ip, username } = ctx;
const calls: ToolCall[] = [];
const pickToolStartTime = Date.now();
// append a message with the list of all available files
const files = messages.reduce((acc, curr, idx) => {
if (curr.files) {
const prefix = (curr.from === "user" ? "input" : "ouput") + "_" + idx;
acc.push(
...curr.files.map(
(file, fileIdx) => `${prefix}_${fileIdx}.${file?.name?.split(".")?.pop()?.toLowerCase()}`
)
);
}
return acc;
}, [] as string[]);
let formattedMessages = messages.map((message, msgIdx) => {
let content = message.content;
if (message.files && message.files.length > 0) {
content +=
"\n\nAdded files: \n - " +
message.files
.map((file, fileIdx) => {
const prefix = message.from === "user" ? "input" : "output";
const fileName = file.name.split(".").pop()?.toLowerCase();
return `${prefix}_${msgIdx}_${fileIdx}.${fileName}`;
})
.join("\n - ");
}
return {
...message,
content,
} satisfies Message;
});
const fileMsg = {
id: crypto.randomUUID(),
from: "system",
content:
"Here is the list of available filenames that can be used as input for tools. Use the filenames that are in this list. \n The filename structure is as follows : {input for user|output for tool}_{message index in the conversation}_{file index in the list of files}.{file extension} \n - " +
files.join("\n - ") +
"\n\n\n",
} satisfies Message;
// put fileMsg before last if files.length > 0
formattedMessages = files.length
? [...formattedMessages.slice(0, -1), fileMsg, ...formattedMessages.slice(-1)]
: messages;
let rawText = "";
const mappedTools = tools.map((tool) => ({
...tool,
inputs: tool.inputs.map((input) => ({
...input,
type: input.type === "file" ? "str" : input.type,
})),
}));
// do the function calling bits here
for await (const output of await endpoint({
messages: formattedMessages,
preprompt,
generateSettings: { temperature: 0.1, ...assistant?.generateSettings },
tools: mappedTools,
conversationId: conv._id,
})) {
// model natively supports tool calls
if (output.token.toolCalls) {
calls.push(...output.token.toolCalls);
continue;
}
if (output.token.text) {
rawText += output.token.text;
}
// if we dont see a tool call in the first 25 chars, something is going wrong and we abort
if (rawText.length > 100 && !(rawText.includes("```json") || rawText.includes("{"))) {
return [];
}
// if we see a directly_answer tool call, we skip the rest
if (
rawText.includes("directly_answer") ||
rawText.includes("directlyAnswer") ||
rawText.includes("directly-answer")
) {
return [];
}
// look for a code blocks of ```json and parse them
// if they're valid json, add them to the calls array
if (output.generated_text) {
try {
const rawCalls = await extractJson(output.generated_text);
const newCalls = rawCalls
.map((call) => externalToToolCall(call, tools))
.filter((call) => call !== undefined) as ToolCall[];
calls.push(...newCalls);
} catch (e) {
logger.warn({ rawCall: output.generated_text, error: e }, "Error while parsing tool calls");
// error parsing the calls
yield {
type: MessageUpdateType.Status,
status: MessageUpdateStatus.Error,
message: "Error while parsing tool calls.",
};
}
}
}
MetricsServer.getMetrics().tool.timeToChooseTools.observe(
{ model: conv.model },
Date.now() - pickToolStartTime
);
const toolContext: BackendToolContext = { conv, messages, preprompt, assistant, ip, username };
const toolResults: (ToolResult | undefined)[] = yield* mergeAsyncGenerators(
calls.map((call) => callTool(toolContext, tools, call))
);
return toolResults.filter((result): result is ToolResult => result !== undefined);
}
function externalToToolCall(call: unknown, tools: Tool[]): ToolCall | undefined {
// Early return if invalid input
if (!isValidCallObject(call)) {
return undefined;
}
const parsedCall = parseExternalCall(call);
if (!parsedCall) return undefined;
const tool = tools.find((tool) => toolHasName(parsedCall.tool_name, tool));
if (!tool) {
logger.debug(
`Model requested tool that does not exist: "${parsedCall.tool_name}". Skipping tool...`
);
return undefined;
}
const parametersWithDefaults: Record<string, string> = {};
for (const input of tool.inputs) {
const value = parsedCall.parameters[input.name];
// Required so ensure it's there, otherwise return undefined
if (input.paramType === "required") {
if (value === undefined) {
logger.debug(
`Model requested tool "${parsedCall.tool_name}" but was missing required parameter "${input.name}". Skipping tool...`
);
return;
}
parametersWithDefaults[input.name] = value;
continue;
}
// Optional so use default if not there
parametersWithDefaults[input.name] = value;
if (input.paramType === "optional") {
parametersWithDefaults[input.name] ??= input.default.toString();
}
}
return {
name: parsedCall.tool_name,
parameters: parametersWithDefaults,
};
}
// Helper functions
function isValidCallObject(call: unknown): call is Record<string, unknown> {
return typeof call === "object" && call !== null;
}
function parseExternalCall(callObj: Record<string, unknown>) {
const nameFields = ["tool_name", "name"] as const;
const parametersFields = ["parameters", "arguments", "parameter_definitions"] as const;
const groupedCall = {
tool_name: "" as string,
parameters: undefined as Record<string, string> | undefined,
};
for (const name of nameFields) {
if (callObj[name]) {
groupedCall.tool_name = callObj[name] as string;
}
}
for (const name of parametersFields) {
if (callObj[name]) {
groupedCall.parameters = callObj[name] as Record<string, string>;
}
}
return z
.object({
tool_name: z.string(),
parameters: z.record(z.any()),
})
.parse(groupedCall);
}
|