xonecas.io
53129
Pa

PAT / commit f5752f4

fix: types cleanup

xonecas2025-12-18 f5752f4ffd21b03b41f6903f9a55b294852fe662 parent 528d87c

14 files changed

app/api/chat/route.ts+5−8
@@ -1,9 +1,6 @@
11 import { NextResponse } from "next/server";
2-import type {
3- OllamaMessageInput,
4- OllamaMessageRole,
5- MaxPromptLength,
6-} from "@/src/lib/ollama/types";
2+import type { MaxPromptLength } from "@/src/lib/ollama/types";
3+import type { Message } from "ollama";
74 import { db } from "@/src/lib/db";
85 import { messages, threads } from "@/src/lib/db/schema";
96 import { eq, asc } from "drizzle-orm";
@@ -55,10 +52,10 @@ export async function POST(request: Request) {
5552 });
5653
5754 // 4. Build messages array for Ollama
58- const ollamaMessages: OllamaMessageInput[] = previousMessages.map((msg) => ({
59- role: msg.role as OllamaMessageRole,
55+ // Note: tool_calls are not needed for conversation history, only stored for display
56+ const ollamaMessages: Message[] = previousMessages.map((msg) => ({
57+ role: msg.role as Message["role"],
6058 content: msg.content,
61- toolCalls: msg.toolCalls || undefined,
6259 }));
6360
6461 // Add the new user message
app/api/settings/route.ts+3−3
@@ -54,14 +54,14 @@ export async function POST(request: Request) {
5454 // Get existing settings and merge, prefering the ones in the request
5555 const existingSettings = await getCache<Settings>(SETTINGS_CACHE_KEY);
5656 if (existingSettings) {
57- settings = {...existingSettings, ...settings}
57+ settings = { ...existingSettings, ...settings };
5858 }
5959
6060 if (!settings.selectedModel) {
6161 const firstModel = await getFirstAvailableModel();
62- settings.selectedModel = firstModel
62+ settings.selectedModel = firstModel;
6363 }
64-
64+
6565 // Update the cache with new settings.
6666 await setCache(SETTINGS_CACHE_KEY, settings);
6767
app/api/threads/route.ts+1−1
@@ -24,7 +24,7 @@ export async function POST(request: Request) {
2424 await db.insert(messages).values({
2525 threadId,
2626 role: "system",
27- content: `You are PAT, a helpful assistant. Please follow these guidelines:
27+ content: `You are PAT, a helpful personal assistant. Please follow these guidelines:
2828 - Tool calls should not be used more than once per user request
2929 - Use simple and concise language
3030 - Reply with markdown whenever possible
src/components/MessageList/AssistantMessage.tsx+5−12
@@ -25,22 +25,15 @@ export default function AssistantMessage({ message }: AssistantMessageProps) {
2525 const formatToolCalls = (toolCallsJson: string | null): string | null => {
2626 if (!toolCallsJson) return null;
2727 try {
28- const toolCalls = JSON.parse(toolCallsJson);
29- if (!Array.isArray(toolCalls) || toolCalls.length === 0) return null;
30-
31- // Count occurrences of each tool name
32- const toolCounts: Record<string, number> = {};
33- toolCalls.forEach((tc: { function?: { name?: string } }) => {
34- const toolName = tc.function?.name || "unknown";
35- toolCounts[toolName] = (toolCounts[toolName] || 0) + 1;
36- });
28+ const toolCounts: Record<string, number> = JSON.parse(toolCallsJson);
29+ if (typeof toolCounts !== "object" || toolCounts === null) return null;
3730
3831 // Format as "toolName x count"
3932 const formatted = Object.entries(toolCounts)
4033 .map(([name, count]) => `${name} x ${count}`)
4134 .join(", ");
4235
43- return formatted;
36+ return formatted || null;
4437 } catch {
4538 return null;
4639 }
@@ -69,8 +62,8 @@ export default function AssistantMessage({ message }: AssistantMessageProps) {
6962 {message.generationTimeMs && (
7063 <span className="ml-1">• in {formatGenerationTime(message.generationTimeMs)}</span>
7164 )}
72- {formatToolCalls(message.toolCalls) && (
73- <span className="ml-1">• tools: {formatToolCalls(message.toolCalls)}</span>
65+ {formatToolCalls(message.toolCallCounts) && (
66+ <span className="ml-1">• tools: {formatToolCalls(message.toolCallCounts)}</span>
7467 )}
7568 </div>
7669 </div>
src/hooks/useMessages.ts+2−2
@@ -92,7 +92,7 @@ export function useMessages(threadId: number | null, onError?: (error: string) =
9292 model: null,
9393 maxPromptLength: null,
9494 generationTimeMs: null,
95- toolCalls: null,
95+ toolCallCounts: null,
9696 };
9797 setMessages((prev) => [...prev, userMsg]);
9898
@@ -107,7 +107,7 @@ export function useMessages(threadId: number | null, onError?: (error: string) =
107107 model: null,
108108 maxPromptLength: null,
109109 generationTimeMs: null,
110- toolCalls: null,
110+ toolCallCounts: null,
111111 };
112112 setMessages((prev) => [...prev, botMsg]);
113113 setStreamingMessageId(assistantMsgId);
src/lib/chat.ts+40−57
@@ -1,16 +1,29 @@
11 /* personal-assistant-thing/src/lib/chat.ts */
22 import { fetchOllamaResponse } from "@/src/lib/ollama";
3-import type {
4- OllamaMessageInput,
5- MaxPromptLength,
6- ToolCall,
7-} from "@/src/lib/ollama/types";
3+import type { MaxPromptLength } from "@/src/lib/ollama/types";
4+import type { Message, ToolCall } from "ollama";
85 import { db } from "@/src/lib/db";
96 import { messages, threads } from "@/src/lib/db/schema";
107 import { eq } from "drizzle-orm";
118
9+/**
10+ * Extracts tool name counts from an array of tool calls.
11+ * Returns a JSON string of the format: {"tool_name": count, ...}
12+ */
13+function extractToolCounts(toolCalls: ToolCall[]): string | null {
14+ if (toolCalls.length === 0) return null;
15+
16+ const toolCounts: Record<string, number> = {};
17+ for (const toolCall of toolCalls) {
18+ const toolName = toolCall.function.name;
19+ toolCounts[toolName] = (toolCounts[toolName] || 0) + 1;
20+ }
21+
22+ return JSON.stringify(toolCounts);
23+}
24+
1225 export interface StreamAssistantResponseParams {
13- ollamaMessages: OllamaMessageInput[];
26+ ollamaMessages: Message[];
1427 threadId: number;
1528 threadModel: string | null;
1629 threadMaxPromptLength: MaxPromptLength;
@@ -46,10 +59,10 @@ export function streamAssistantResponse({
4659 }
4760 };
4861
49- const safeEnqueue = (data: Uint8Array) => {
62+ const safeEnqueue = (data: unknown) => {
5063 if (!isControllerClosed) {
5164 try {
52- controller.enqueue(data);
65+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
5366 } catch {
5467 // Controller may be closed, ignore
5568 }
@@ -75,36 +88,18 @@ export function streamAssistantResponse({
7588
7689 if (chunk.content) {
7790 accumulatedContent += chunk.content;
78- safeEnqueue(
79- encoder.encode(
80- `data: ${JSON.stringify({ type: "content", content: chunk.content })}\n\n`
81- )
82- );
83- }
84- if (chunk.thinking) {
85- safeEnqueue(
86- encoder.encode(
87- `data: ${JSON.stringify({ type: "thinking", thinking: chunk.thinking })}\n\n`
88- )
89- );
91+ safeEnqueue({ type: "content", content: chunk.content });
9092 }
93+
9194 if (chunk.toolCalls) {
9295 allToolCalls.push(...chunk.toolCalls);
93- safeEnqueue(
94- encoder.encode(
95- `data: ${JSON.stringify({ type: "toolCalls", toolCalls: chunk.toolCalls })}\n\n`
96- )
97- );
96+ safeEnqueue({ type: "toolCalls", toolCalls: chunk.toolCalls });
9897 }
9998 };
10099
101100 // Set up abort handler
102101 const abortHandler = () => {
103- safeEnqueue(
104- encoder.encode(
105- `data: ${JSON.stringify({ type: "error", error: "Generation stopped" })}\n\n`
106- )
107- );
102+ safeEnqueue({ type: "error", error: "Generation stopped" });
108103 safeClose();
109104 };
110105 signal.addEventListener("abort", abortHandler);
@@ -145,21 +140,17 @@ export function streamAssistantResponse({
145140 maxPromptLength: threadMaxPromptLength === "none" ? null : threadMaxPromptLength, // null means "none" (no limit), otherwise 1024 or 4096
146141 createdAt: new Date(),
147142 generationTimeMs: null,
148- toolCalls: allToolCalls.length > 0 ? JSON.stringify(allToolCalls) : null,
143+ toolCallCounts: extractToolCounts(allToolCalls),
149144 });
150145 await db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, threadId));
151146
152147 // Send done message with metadata for aborted generation
153- safeEnqueue(
154- encoder.encode(
155- `data: ${JSON.stringify({
156- type: "done",
157- answer: accumulatedContent,
158- model: threadModel,
159- maxPromptLength: threadMaxPromptLength,
160- })}\n\n`
161- )
162- );
148+ safeEnqueue({
149+ type: "done",
150+ answer: accumulatedContent,
151+ model: threadModel,
152+ maxPromptLength: threadMaxPromptLength,
153+ });
163154 }
164155 safeClose();
165156 return;
@@ -174,30 +165,22 @@ export function streamAssistantResponse({
174165 maxPromptLength: threadMaxPromptLength === "none" ? null : threadMaxPromptLength, // null means "none" (no limit), otherwise 1024 or 4096
175166 createdAt: new Date(),
176167 generationTimeMs,
177- toolCalls: toolCalls ? JSON.stringify(toolCalls) : null,
168+ toolCallCounts: toolCalls ? extractToolCounts(toolCalls) : null,
178169 });
179170
180171 // Update thread's updatedAt timestamp
181172 await db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, threadId));
182173
183174 // Send final message with metadata
184- safeEnqueue(
185- encoder.encode(
186- `data: ${JSON.stringify({
187- type: "done",
188- answer: accumulatedContent,
189- model: threadModel,
190- maxPromptLength: threadMaxPromptLength,
191- })}\n\n`
192- )
193- );
175+ safeEnqueue({
176+ type: "done",
177+ answer: accumulatedContent,
178+ model: threadModel,
179+ maxPromptLength: threadMaxPromptLength,
180+ });
194181 safeClose();
195182 } catch {
196- safeEnqueue(
197- encoder.encode(
198- `data: ${JSON.stringify({ type: "error", error: "Sorry, something went wrong." })}\n\n`
199- )
200- );
183+ safeEnqueue({ type: "error", error: "Sorry, something went wrong." });
201184 safeClose();
202185 }
203186 },
src/lib/db/schema.ts+1−1
@@ -22,7 +22,7 @@ export const messages = pgTable("messages", {
2222 maxPromptLength: integer("max_prompt_length"), // Prompt size used to generate this message (for assistant messages) - null, 1024, or 4096
2323 createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2424 generationTimeMs: integer("generation_time_ms"), // Time taken to generate response (for assistant messages)
25- toolCalls: text("tool_calls"), // JSON string of tool calls made to generate this message (for assistant messages)
25+ toolCallCounts: text("tool_call_counts"), // JSON string of tool name counts, e.g. {"query_weather": 2, "query_web_search": 1}
2626 });
2727
2828 // Define relations
src/lib/ollama/duckduckgo.ts+1−10
@@ -5,11 +5,6 @@ import { getCache, setCache } from "../cache";
55 import { createRateLimiter } from "../ratelimit";
66
77 const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
8-
9-/**
10- * Rate limiter for DuckDuckGo API requests.
11- * Tracks requests per 24-hour rolling window.
12- */
138 const duckDuckGoRateLimiter = createRateLimiter({
149 maxRequests: 500,
1510 windowMs: 24 * 60 * 60 * 1000, // 24 hours in milliseconds
@@ -21,13 +16,9 @@ const duckDuckGoRateLimiter = createRateLimiter({
2116 * Results are cached for 6 hours.
2217 *
2318 * @param query - The search query to send to DuckDuckGo.
24- * @returns A formatted string containing the instant answer information.
19+ * @returns A formatted string containing the instant answer information or an error message.
2520 */
2621 export async function queryDuckDuckGo(query: string): Promise<string> {
27- if (!query || typeof query !== "string") {
28- return `Error: Invalid query parameter. Expected a non-empty string, got: ${typeof query}`;
29- }
30-
3122 // Check cache first
3223 const cacheKey = `duckduckgo:${query.toLowerCase().trim()}`;
3324 const cached = await getCache<string>(cacheKey);
src/lib/ollama/index.ts+34−91
@@ -1,21 +1,12 @@
11 /* personal-assistant-thing/src/lib/ollama/index.ts */
22 // Wrapper using the official Ollama npm package.
33
4-import ollama from "ollama";
4+import ollama, { type Message, type ToolCall } from "ollama";
55 import { debug } from "@/src/lib/debug";
66 import { duckDuckGoTool, queryDuckDuckGo } from "@/src/lib/ollama/duckduckgo";
77 import { queryWeather, weatherTool } from "@/src/lib/ollama/weather";
88 import { queryWebSearch, webSearchTool } from "@/src/lib/ollama/websearch";
9-import type {
10- OllamaMessage,
11- OllamaMessageInput,
12- OllamaChunk,
13- OllamaResponse,
14- MaxPromptLength,
15- ToolCall,
16- OllamaChatMessage,
17-} from "@/src/lib/ollama/types";
18-
9+import type { OllamaChunk, OllamaResponse, MaxPromptLength } from "@/src/lib/ollama/types";
1910
2011 /**
2112 * Executes a tool call and returns the result.
@@ -23,41 +14,25 @@ import type {
2314 * @param toolCall - The tool call from Ollama.
2415 * @returns The tool response with the execution result.
2516 */
26-async function executeToolCall(toolCall: ToolCall): Promise<OllamaMessage> {
17+async function executeToolCall(toolCall: ToolCall): Promise<Message> {
2718 const { name, arguments: args } = toolCall.function;
28- const parsedArgs = typeof args === "string" ? JSON.parse(args) : args;
19+ const { query } = args as { query: string };
2920
30- debug(`[Tool] Executing: ${name}`, parsedArgs);
21+ const tools = {
22+ query_web_search: queryWebSearch,
23+ query_weather: queryWeather,
24+ query_duckduckgo: queryDuckDuckGo,
25+ };
3126
3227 let result: string;
33- switch (name) {
34- case "query_duckduckgo":
35- if (!parsedArgs.query || typeof parsedArgs.query !== "string") {
36- result = `Error: Missing or invalid "query" parameter for query_duckduckgo`;
37- } else {
38- result = await queryDuckDuckGo(parsedArgs.query);
39- }
40- break;
41- case "query_weather":
42- if (!parsedArgs.location || typeof parsedArgs.location !== "string") {
43- result = `Error: Missing or invalid "location" parameter for query_weather`;
44- } else {
45- result = await queryWeather(parsedArgs.location);
46- }
47- break;
48- case "query_web_search":
49- if (!parsedArgs.query || typeof parsedArgs.query !== "string") {
50- result = `Error: Missing or invalid "query" parameter for query_web_search`;
51- } else {
52- result = await queryWebSearch(parsedArgs.query);
53- }
54- break;
55- default:
56- debug(`[Tool] Unknown tool: ${name}`);
57- result = `Error: Unknown tool "${name}"`;
28+ try {
29+ result = tools[name](query);
30+ debug(`[Tool] ${name} completed, result length: ${result.length} chars`);
31+ } catch (error) {
32+ debug("[Tool] call failed: " + error.message || "Unknown error")
33+ result = `Error executing tool call: ${error.message || "Unknown error"}`;
5834 }
5935
60- debug(`[Tool] ${name} completed, result length: ${result.length} chars`);
6136 return {
6237 role: "tool",
6338 tool_name: name,
@@ -73,36 +48,22 @@ async function executeToolCall(toolCall: ToolCall): Promise<OllamaMessage> {
7348 *
7449 * @param messages - Array of messages in the conversation history.
7550 * @param onChunk - Optional callback function to receive streaming chunks (content, thinking, toolCalls).
76- * @param model - The Ollama model to use. Defaults to 'gpt-oss'.
51+ * @param model - The Ollama model to use..
7752 * @param signal - Optional AbortSignal to cancel the request.
7853 * @param maxPromptLength - Optional maximum prompt length in tokens. Can be "none", 1024, or 4096.
7954 * @returns Object containing the response content and generation time in milliseconds.
8055 * @throws If the request fails.
8156 */
8257 export async function fetchOllamaResponse(
83- messages: OllamaMessageInput[],
58+ messages: Message[],
8459 onChunk?: (chunk: OllamaChunk) => void,
85- model = "gpt-oss",
60+ model = "",
8661 signal?: AbortSignal,
8762 maxPromptLength?: MaxPromptLength
8863 ): Promise<OllamaResponse> {
8964 const tools = [duckDuckGoTool, weatherTool, webSearchTool];
9065 let totalDuration = 0;
91- const currentMessages: OllamaMessage[] = messages.map((msg) => {
92- const message: OllamaMessage = {
93- role: msg.role,
94- content: msg.content,
95- };
96- // Include tool_calls if they exist (from database)
97- if (msg.toolCalls) {
98- try {
99- message.tool_calls = JSON.parse(msg.toolCalls);
100- } catch {
101- // If parsing fails, ignore tool_calls
102- }
103- }
104- return message;
105- });
66+ const currentMessages: Message[] = messages;
10667 const allToolCalls: ToolCall[] = [];
10768
10869 // Build options object with num_ctx if maxPromptLength is set
@@ -122,31 +83,12 @@ export async function fetchOllamaResponse(
12283 throw new Error("Request aborted");
12384 }
12485
125- // Ensure all messages have content as a string and tool_calls have proper format (required by ollama.chat)
126- const messagesForOllama: OllamaChatMessage[] = currentMessages.map((msg) => {
127- const { tool_calls, ...msgWithoutToolCalls } = msg;
128- const message: OllamaChatMessage = {
129- ...msgWithoutToolCalls,
130- content: msg.content ?? "",
131- };
132-
133- // Transform tool_calls to ensure arguments is always an object
134- if (tool_calls) {
135- message.tool_calls = tool_calls.map((tc) => ({
136- id: tc.id,
137- type: tc.type,
138- function: {
139- name: tc.function.name,
140- arguments:
141- typeof tc.function.arguments === "string"
142- ? JSON.parse(tc.function.arguments)
143- : tc.function.arguments,
144- },
145- }));
146- }
147-
148- return message;
149- });
86+ // Ensure all messages have content as a string (required by ollama.chat)
87+ // currentMessages is already Message[], just ensure content is not empty
88+ const messagesForOllama: Message[] = currentMessages.map((msg) => ({
89+ ...msg,
90+ content: msg.content ?? "",
91+ }));
15092
15193 const stream = await ollama.chat({
15294 model,
@@ -184,22 +126,23 @@ export async function fetchOllamaResponse(
184126 // Accumulate tool calls from chunks
185127 if (chunk.message?.tool_calls?.length) {
186128 for (const toolCall of chunk.message.tool_calls) {
187- // If tool call has an ID, check if we already have it
129+ // If tool call has an ID (present in streaming but not in type), check if we already have it
188130 const toolCallWithId = toolCall as ToolCall & { id?: string };
189131 if (toolCallWithId.id) {
190132 const existingIndex = toolCalls.findIndex(
191- (tc: ToolCall) => tc.id === toolCallWithId.id
133+ (tc: ToolCall & { id?: string }) =>
134+ (tc as ToolCall & { id?: string }).id === toolCallWithId.id
192135 );
193136 if (existingIndex >= 0) {
194- toolCalls[existingIndex] = toolCall as ToolCall;
137+ toolCalls[existingIndex] = toolCall;
195138 } else {
196- toolCalls.push(toolCall as ToolCall);
139+ toolCalls.push(toolCall);
197140 }
198141 } else {
199- toolCalls.push(toolCall as ToolCall);
142+ toolCalls.push(toolCall);
200143 }
201144 }
202- onChunk?.({ toolCalls: chunk.message.tool_calls as ToolCall[] });
145+ onChunk?.({ toolCalls: chunk.message.tool_calls });
203146 }
204147 }
205148
@@ -241,9 +184,9 @@ export async function fetchOllamaResponse(
241184 // Execute tool calls and add results to messages
242185 debug(
243186 `[Ollama] Tool calls detected:`,
244- toolCalls.map((tc: ToolCall) => ({
187+ toolCalls.map((tc: ToolCall & { id?: string }) => ({
245188 name: tc.function.name,
246- id: tc.id,
189+ id: (tc as ToolCall & { id?: string }).id,
247190 }))
248191 );
249192
src/lib/ollama/models.ts+0−1
@@ -16,4 +16,3 @@ export async function getFirstAvailableModel(): Promise<string | null> {
1616 return null;
1717 }
1818 }
19-
src/lib/ollama/types.ts+11−50
@@ -1,60 +1,21 @@
11 /* personal-assistant-thing/src/lib/ollama/types.ts */
22 // Type definitions for Ollama integration
3+// We use ollama package types directly where possible, only defining project-specific types here
34
4-export interface OllamaMessage {
5- role: "user" | "assistant" | "system" | "tool";
6- content?: string;
7- thinking?: string;
8- tool_calls?: ToolCall[];
9- tool_name?: string;
10-}
5+import type { Message, ToolCall } from "ollama";
116
12-export type OllamaMessageRole = "user" | "assistant" | "system";
13-
14-export interface ToolCall {
15- id?: string;
16- type?: "function";
17- function: {
18- name: string;
19- arguments: string | { [key: string]: unknown };
20- };
21-}
22-
23-// Tool call format required by ollama.chat() - arguments must be an object
24-export interface OllamaChatToolCall {
25- id?: string;
26- type?: "function";
27- function: {
28- name: string;
29- arguments: { [key: string]: unknown };
30- };
31-}
32-
33-// Message format required by ollama.chat() - content is required and tool_calls use OllamaChatToolCall
34-export interface OllamaChatMessage {
35- role: "user" | "assistant" | "system" | "tool";
36- content: string;
37- thinking?: string;
38- tool_calls?: OllamaChatToolCall[];
39- tool_name?: string;
40-}
41-
42-export interface OllamaMessageInput {
43- role: OllamaMessageRole;
44- content: string;
45- toolCalls?: string; // Optional JSON string of tool calls (from database)
46-}
47-
48-export interface OllamaResponse {
49- content: string;
7+// Response type from fetchOllamaResponse (includes generation time)
8+// Based on Message content with additional metadata
9+export type OllamaResponse = Pick<Message, "content"> & {
5010 generationTimeMs: number;
5111 toolCalls?: ToolCall[]; // Array of tool calls made during the conversation
52-}
12+};
5313
54-export interface OllamaChunk {
55- content?: string;
56- thinking?: string;
14+// Streaming chunk type for onChunk callback
15+// Based on Message fields for streaming updates (all optional)
16+export type OllamaChunk = Partial<Pick<Message, "content" | "thinking">> & {
5717 toolCalls?: ToolCall[];
58-}
18+};
5919
20+// Project-specific type for max prompt length setting
6021 export type MaxPromptLength = "none" | 1024 | 4096 | null;
src/lib/ollama/weather.ts+2−6
@@ -59,14 +59,10 @@ function getWeatherDescription(code: number): string {
5959 * Queries Open-Meteo's weather API for current weather and forecast information.
6060 * Results are cached for 6 hours.
6161 *
62- * @param location - The location name (e.g., "New York", "London", "Tokyo").
63- * @returns A formatted string containing weather information.
62+ * @param location - The location name (e.g., 'New York', 'London', 'Tokyo').
63+ * @returns A formatted string containing weather information or an error message.
6464 */
6565 export async function queryWeather(location: string): Promise<string> {
66- if (!location || typeof location !== "string") {
67- return `Error: Invalid location parameter. Expected a non-empty string, got: ${typeof location}`;
68- }
69-
7066 // Check cache first
7167 const cacheKey = `weather:${location.toLowerCase().trim()}`;
7268 const cached = await getCache<string>(cacheKey);
src/lib/ollama/websearch.ts+2−6
@@ -22,14 +22,10 @@ const webSearchRateLimiter = createRateLimiter({
2222 * Enforces a rate limit of 100 requests per 24 hours.
2323 * Results are cached for 6 hours.
2424 *
25- * @param query - The search query to execute.
26- * @returns A formatted string containing search results.
25+ * @param query - The search query to execute on the web.
26+ * @returns A formatted string containing search results or an error message.
2727 */
2828 export async function queryWebSearch(query: string): Promise<string> {
29- if (!query || typeof query !== "string") {
30- return `Error: Invalid query parameter. Expected a non-empty string, got: ${typeof query}`;
31- }
32-
3329 // Check cache first
3430 const cacheKey = `websearch:${query.toLowerCase().trim()}`;
3531 const cached = await getCache<string>(cacheKey);
tsconfig.tsbuildinfo+1−1
@@ -1 +1 @@
1-{"fileNames":["./node_modules/typescript/lib/lib.es5.d.ts","./node_modules/typescript/lib/lib.es2015.d.ts","./node_modules/typescript/lib/lib.es2016.d.ts","./node_modules/typescript/lib/lib.es2017.d.ts","./node_modules/typescript/lib/lib.es2018.d.ts","./node_modules/typescript/lib/lib.es2019.d.ts","./node_modules/typescript/lib/lib.es2020.d.ts","./node_modules/typescript/lib/lib.es2021.d.ts","./node_modules/typescript/lib/lib.es2022.d.ts","./node_modules/typescript/lib/lib.es2023.d.ts","./node_m …
1+{"fileNames":["./node_modules/typescript/lib/lib.es5.d.ts","./node_modules/typescript/lib/lib.es2015.d.ts","./node_modules/typescript/lib/lib.es2016.d.ts","./node_modules/typescript/lib/lib.es2017.d.ts","./node_modules/typescript/lib/lib.es2018.d.ts","./node_modules/typescript/lib/lib.es2019.d.ts","./node_modules/typescript/lib/lib.es2020.d.ts","./node_modules/typescript/lib/lib.es2021.d.ts","./node_modules/typescript/lib/lib.es2022.d.ts","./node_modules/typescript/lib/lib.es2023.d.ts","./node_m …