Spaces:
Running
Running
File size: 6,994 Bytes
564e576 6e18e46 564e576 719022a 564e576 6e18e46 564e576 baa4992 719022a baa4992 6e18e46 baa4992 6e18e46 baa4992 564e576 6e18e46 564e576 719022a 564e576 719022a 564e576 6e18e46 564e576 6e18e46 719022a 564e576 |
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 |
import { ToolResultStatus, type ToolCall, type ToolResult } from "$lib/types/Tool";
import { v4 as uuidV4 } from "uuid";
import JSON5 from "json5";
import type { BackendTool, BackendToolContext } from "../tools";
import {
MessageToolUpdateType,
MessageUpdateStatus,
MessageUpdateType,
type MessageUpdate,
} from "$lib/types/MessageUpdate";
import type { TextGenerationContext } from "./types";
import { allTools } from "../tools";
import directlyAnswer from "../tools/directlyAnswer";
import websearch from "../tools/web/search";
import { z } from "zod";
import { logger } from "../logger";
import { toolHasName } from "../tools/utils";
import type { MessageFile } from "$lib/types/Message";
import { mergeAsyncGenerators } from "$lib/utils/mergeAsyncGenerators";
import { MetricsServer } from "../metrics";
function makeFilesPrompt(files: MessageFile[], fileMessageIndex: number): string {
if (files.length === 0) {
return "The user has not uploaded any files. Do not attempt to use any tools that require files";
}
const stringifiedFiles = files
.map(
(file, fileIndex) =>
` - fileMessageIndex ${fileMessageIndex} | fileIndex ${fileIndex} | ${file.name} (${file.mime})`
)
.join("\n");
return `Attached ${files.length} file${files.length === 1 ? "" : "s"}:\n${stringifiedFiles}`;
}
export function pickTools(
toolsPreference: Record<string, boolean>,
isAssistant: boolean
): BackendTool[] {
// if it's an assistant, only support websearch for now
if (isAssistant) return [directlyAnswer, websearch];
// filter based on tool preferences, add the tools that are on by default
return allTools.filter((el) => {
if (el.isLocked && el.isOnByDefault) return true;
return toolsPreference?.[el.name] ?? el.isOnByDefault;
});
}
async function* runTool(
ctx: BackendToolContext,
tools: BackendTool[],
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 {
try {
const toolResult = yield* tool.call(call.parameters, ctx);
if (toolResult.status === ToolResultStatus.Error) {
yield {
type: MessageUpdateType.Tool,
subtype: MessageToolUpdateType.Error,
uuid,
message: toolResult.message,
};
} else {
yield {
type: MessageUpdateType.Tool,
subtype: MessageToolUpdateType.Result,
uuid,
result: { ...toolResult, call } as ToolResult,
};
}
MetricsServer.getMetrics().tool.toolUseDuration.observe(
{ tool: call.name },
Date.now() - startTime
);
return { ...toolResult, call } as ToolResult;
} catch (e) {
MetricsServer.getMetrics().tool.toolUseCountError.inc({ tool: call.name });
yield {
type: MessageUpdateType.Tool,
subtype: MessageToolUpdateType.Error,
uuid,
message: e instanceof Error ? e.message : String(e),
};
}
} catch (cause) {
MetricsServer.getMetrics().tool.toolUseCountError.inc({ tool: call.name });
console.error(Error(`Failed while running tool ${call.name}`), { cause });
return {
call,
status: ToolResultStatus.Error,
message: cause instanceof Error ? cause.message : String(cause),
};
}
}
export async function* runTools(
ctx: TextGenerationContext,
tools: BackendTool[],
preprompt?: string
): AsyncGenerator<MessageUpdate, ToolResult[], undefined> {
const { endpoint, conv, messages, assistant, ip, username } = ctx;
const calls: ToolCall[] = [];
const messagesWithFilesPrompt = messages.map((message, idx) => {
if (!message.files?.length) return message;
return {
...message,
content: `${message.content}\n${makeFilesPrompt(message.files, idx)}`,
};
});
const pickToolStartTime = Date.now();
// do the function calling bits here
for await (const output of await endpoint({
messages: messagesWithFilesPrompt,
preprompt,
generateSettings: assistant?.generateSettings,
tools,
})) {
// model natively supports tool calls
if (output.token.toolCalls) {
calls.push(...output.token.toolCalls);
continue;
}
// 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) {
const codeBlocks = Array.from(output.generated_text.matchAll(/```json\n(.*?)```/gs));
if (codeBlocks.length === 0) continue;
// grab only the capture group from the regex match
for (const [, block] of codeBlocks) {
try {
calls.push(
...JSON5.parse(block).filter(isExternalToolCall).map(externalToToolCall).filter(Boolean)
);
} catch (cause) {
// error parsing the calls
yield {
type: MessageUpdateType.Status,
status: MessageUpdateStatus.Error,
message: cause instanceof Error ? cause.message : String(cause),
};
}
}
}
}
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) => runTool(toolContext, tools, call))
);
return toolResults.filter((result): result is ToolResult => result !== undefined);
}
const externalToolCall = z.object({
tool_name: z.string(),
parameters: z.record(z.any()),
});
type ExternalToolCall = z.infer<typeof externalToolCall>;
function isExternalToolCall(call: unknown): call is ExternalToolCall {
return externalToolCall.safeParse(call).success;
}
function externalToToolCall(call: ExternalToolCall): ToolCall | undefined {
// Convert - to _ since some models insist on using _ instead of -
const tool = allTools.find((tool) => toolHasName(call.tool_name, tool));
if (!tool) {
logger.debug(`Model requested tool that does not exist: "${call.tool_name}". Skipping tool...`);
return;
}
const parametersWithDefaults: Record<string, string> = {};
for (const [key, definition] of Object.entries(tool.parameterDefinitions)) {
const value = call.parameters[key];
// Required so ensure it's there, otherwise return undefined
if (definition.required) {
if (value === undefined) {
logger.debug(
`Model requested tool "${call.tool_name}" but was missing required parameter "${key}". Skipping tool...`
);
return;
}
parametersWithDefaults[key] = value;
continue;
}
// Optional so use default if not there
parametersWithDefaults[key] = value ?? definition.default;
}
return {
name: call.tool_name,
parameters: parametersWithDefaults,
};
}
|