xonecas.io
53129
Pa

PAT / commit e0a3c6b

feat: use less tokens with weather queries

xonecas2025-12-18 e0a3c6b8c0739658907fb08dc8730ac23cec1c54 parent f5752f4

15 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

app/api/chat/route.ts+4−2
@@ -4,7 +4,8 @@ import type { Message } from "ollama";
44 import { db } from "@/src/lib/db";
55 import { messages, threads } from "@/src/lib/db/schema";
66 import { eq, asc } from "drizzle-orm";
7-import { streamAssistantResponse } from "@/src/lib/chat";
7+import { streamAssistantResponse } from "@/src/lib/ollama/chat";
8+import { debug } from "@/src/lib/debug";
89
910 export async function POST(request: Request) {
1011 const { message, threadId: threadIdRaw } = await request.json();
@@ -80,7 +81,8 @@ export async function POST(request: Request) {
8081 Connection: "keep-alive",
8182 },
8283 });
83- } catch {
84+ } catch (err) {
85+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
8486 return NextResponse.json({ answer: "Sorry, something went wrong." }, { status: 500 });
8587 }
8688 }
app/api/models/route.ts+3−1
@@ -1,5 +1,6 @@
11 import { NextResponse } from "next/server";
22 import ollama from "ollama";
3+import { debug } from "@/src/lib/debug";
34
45 export async function GET() {
56 try {
@@ -9,7 +10,8 @@ export async function GET() {
910 model: model.name, // Use name as the model identifier
1011 }));
1112 return NextResponse.json({ models });
12- } catch {
13+ } catch (err) {
14+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
1315 return NextResponse.json({ error: "Failed to fetch models" }, { status: 500 });
1416 }
1517 }
app/api/settings/route.ts+5−2
@@ -1,6 +1,7 @@
11 import { NextResponse } from "next/server";
22 import { getCache, setCache } from "@/src/lib/cache";
33 import { getFirstAvailableModel } from "@/src/lib/ollama/models";
4+import { debug } from "@/src/lib/debug";
45
56 const SETTINGS_CACHE_KEY = "app_settings";
67
@@ -24,7 +25,8 @@ export async function GET() {
2425 };
2526
2627 return NextResponse.json({ settings: defaultSettings });
27- } catch {
28+ } catch (err) {
29+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
2830 return NextResponse.json({ error: "Failed to get settings" }, { status: 500 });
2931 }
3032 }
@@ -66,7 +68,8 @@ export async function POST(request: Request) {
6668 await setCache(SETTINGS_CACHE_KEY, settings);
6769
6870 return NextResponse.json({ settings: settings });
69- } catch {
71+ } catch (err) {
72+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
7073 return NextResponse.json({ error: "Failed to set settings" }, { status: 500 });
7174 }
7275 }
app/api/threads/[id]/messages/[messageId]/route.ts+3−1
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
22 import { db } from "@/src/lib/db";
33 import { messages } from "@/src/lib/db/schema";
44 import { eq, and } from "drizzle-orm";
5+import { debug } from "@/src/lib/debug";
56
67 export async function DELETE(
78 request: Request,
@@ -30,7 +31,8 @@ export async function DELETE(
3031 }
3132
3233 return NextResponse.json({ success: true });
33- } catch {
34+ } catch (err) {
35+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
3436 return NextResponse.json({ error: "Failed to delete message" }, { status: 500 });
3537 }
3638 }
app/api/threads/[id]/messages/route.ts+5−3
@@ -1,7 +1,8 @@
11 import { NextResponse } from "next/server";
22 import { db } from "@/src/lib/db";
33 import { messages } from "@/src/lib/db/schema";
4-import { eq, asc, ne, and } from "drizzle-orm";
4+import { eq, asc, and, notInArray } from "drizzle-orm";
5+import { debug } from "@/src/lib/debug";
56
67 export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
78 try {
@@ -14,11 +15,12 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
1415 const messagesList = await db
1516 .select()
1617 .from(messages)
17- .where(and(eq(messages.threadId, threadId), ne(messages.role, "system")))
18+ .where(and(eq(messages.threadId, threadId), notInArray(messages.role, ["system", "tool"])))
1819 .orderBy(asc(messages.createdAt));
1920
2021 return NextResponse.json({ messages: messagesList });
21- } catch {
22+ } catch (err) {
23+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
2224 return NextResponse.json({ error: "Failed to get messages" }, { status: 500 });
2325 }
2426 }
app/api/threads/[id]/route.ts+5−2
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
22 import { db } from "@/src/lib/db";
33 import { threads } from "@/src/lib/db/schema";
44 import { eq } from "drizzle-orm";
5+import { debug } from "@/src/lib/debug";
56
67 export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
78 try {
@@ -38,7 +39,8 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
3839 }
3940
4041 return NextResponse.json({ thread: updatedThread[0] });
41- } catch {
42+ } catch (err) {
43+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
4244 return NextResponse.json({ error: "Failed to update thread" }, { status: 500 });
4345 }
4446 }
@@ -59,7 +61,8 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ i
5961 }
6062
6163 return NextResponse.json({ success: true });
62- } catch {
64+ } catch (err) {
65+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
6366 return NextResponse.json({ error: "Failed to delete thread" }, { status: 500 });
6467 }
6568 }
app/api/threads/route.ts+8−5
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
22 import { db } from "@/src/lib/db";
33 import { threads, messages } from "@/src/lib/db/schema";
44 import { desc, count } from "drizzle-orm";
5+import { debug } from "@/src/lib/debug";
56
67 export async function POST(request: Request) {
78 try {
@@ -9,8 +10,8 @@ export async function POST(request: Request) {
910 const newThread = await db
1011 .insert(threads)
1112 .values({
12- title: title || "New Thread",
13- model: model || "gpt-oss",
13+ title: title,
14+ model: model,
1415 maxPromptLength:
1516 maxPromptLength === "none" || maxPromptLength === null ? null : maxPromptLength,
1617 createdAt: new Date(),
@@ -25,7 +26,7 @@ export async function POST(request: Request) {
2526 threadId,
2627 role: "system",
2728 content: `You are PAT, a helpful personal assistant. Please follow these guidelines:
28-- Tool calls should not be used more than once per user request
29+- Only repeat tool calls in case of errors
2930 - Use simple and concise language
3031 - Reply with markdown whenever possible
3132 - When asked for code or text return it in a markdown code block`,
@@ -33,7 +34,8 @@ export async function POST(request: Request) {
3334 });
3435
3536 return NextResponse.json({ thread: newThread[0] });
36- } catch {
37+ } catch (err) {
38+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
3739 return NextResponse.json({ error: "Failed to create thread" }, { status: 500 });
3840 }
3941 }
@@ -56,7 +58,8 @@ export async function GET(request: Request) {
5658 const hasMore = offset + limit < totalCount;
5759
5860 return NextResponse.json({ threads: threadsList, hasMore, totalCount });
59- } catch {
61+ } catch (err) {
62+ debug(`[API] Error: ${err instanceof Error ? err.message : "Unknown error"}`);
6063 return NextResponse.json({ error: "Failed to get threads" }, { status: 500 });
6164 }
6265 }
drizzle/meta/_journal.json+7−0
@@ -36,6 +36,13 @@
3636 "when": 1766021303746,
3737 "tag": "0004_regular_anthem",
3838 "breakpoints": true
39+ },
40+ {
41+ "idx": 5,
42+ "version": "7",
43+ "when": 1766093474935,
44+ "tag": "0005_harsh_wild_pack",
45+ "breakpoints": true
3946 }
4047 ]
4148 }
src/components/NoThreadSelected.tsx+3−1
@@ -19,11 +19,13 @@ export default function NoThreadSelected({
1919 onMaxPromptLengthChange,
2020 onError,
2121 }: NoThreadSelectedProps) {
22- const [currentTime, setCurrentTime] = useState<Date>(() => new Date());
22+ const [currentTime, setCurrentTime] = useState<Date | null>(null);
2323 const [models, setModels] = useState<Array<{ name: string; model: string }>>([]);
2424 const [isLoadingModels, setIsLoadingModels] = useState(false);
2525
2626 useEffect(() => {
27+ // Set initial time only on client after hydration
28+ setCurrentTime(new Date());
2729 const timer = setInterval(() => {
2830 setCurrentTime(new Date());
2931 }, 1000);
src/lib/chat.ts+0−190
@@ -1,190 +0,0 @@
1-/* personal-assistant-thing/src/lib/chat.ts */
2-import { fetchOllamaResponse } from "@/src/lib/ollama";
3-import type { MaxPromptLength } from "@/src/lib/ollama/types";
4-import type { Message, ToolCall } from "ollama";
5-import { db } from "@/src/lib/db";
6-import { messages, threads } from "@/src/lib/db/schema";
7-import { eq } from "drizzle-orm";
8-
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-
25-export interface StreamAssistantResponseParams {
26- ollamaMessages: Message[];
27- threadId: number;
28- threadModel: string | null;
29- threadMaxPromptLength: MaxPromptLength;
30- signal: AbortSignal;
31-}
32-
33-/**
34- * Streams assistant response and handles database persistence
35- */
36-export function streamAssistantResponse({
37- ollamaMessages,
38- threadId,
39- threadModel,
40- threadMaxPromptLength,
41- signal,
42-}: StreamAssistantResponseParams): ReadableStream<Uint8Array> {
43- let accumulatedContent = "";
44- const allToolCalls: ToolCall[] = [];
45-
46- const encoder = new TextEncoder();
47- const stream = new ReadableStream({
48- async start(controller) {
49- // Track if controller is closed to avoid double-close
50- let isControllerClosed = false;
51- const safeClose = () => {
52- if (!isControllerClosed) {
53- isControllerClosed = true;
54- try {
55- controller.close();
56- } catch {
57- // Controller may already be closed, ignore
58- }
59- }
60- };
61-
62- const safeEnqueue = (data: unknown) => {
63- if (!isControllerClosed) {
64- try {
65- controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
66- } catch {
67- // Controller may be closed, ignore
68- }
69- }
70- };
71-
72- try {
73- // Check if already aborted
74- if (signal.aborted) {
75- safeClose();
76- return;
77- }
78-
79- const onChunk = (chunk: {
80- content?: string;
81- thinking?: string;
82- toolCalls?: ToolCall[];
83- }) => {
84- // Check abort signal before each chunk
85- if (signal.aborted || isControllerClosed) {
86- return;
87- }
88-
89- if (chunk.content) {
90- accumulatedContent += chunk.content;
91- safeEnqueue({ type: "content", content: chunk.content });
92- }
93-
94- if (chunk.toolCalls) {
95- allToolCalls.push(...chunk.toolCalls);
96- safeEnqueue({ type: "toolCalls", toolCalls: chunk.toolCalls });
97- }
98- };
99-
100- // Set up abort handler
101- const abortHandler = () => {
102- safeEnqueue({ type: "error", error: "Generation stopped" });
103- safeClose();
104- };
105- signal.addEventListener("abort", abortHandler);
106-
107- let generationTimeMs: number | undefined;
108- let toolCalls: ToolCall[] | undefined;
109-
110- try {
111- const result = await fetchOllamaResponse(
112- ollamaMessages,
113- onChunk,
114- threadModel,
115- signal,
116- threadMaxPromptLength
117- );
118- generationTimeMs = result.generationTimeMs;
119- toolCalls = result.toolCalls;
120- } catch (error) {
121- // If aborted, don't throw - just close
122- if (signal.aborted || (error instanceof Error && error.message === "Request aborted")) {
123- safeClose();
124- return;
125- }
126- throw error;
127- } finally {
128- signal.removeEventListener("abort", abortHandler);
129- }
130-
131- // Check if aborted before saving
132- if (signal.aborted) {
133- // Save partial content if any was generated
134- if (accumulatedContent) {
135- await db.insert(messages).values({
136- threadId: threadId,
137- role: "assistant",
138- content: accumulatedContent,
139- model: threadModel,
140- maxPromptLength: threadMaxPromptLength === "none" ? null : threadMaxPromptLength, // null means "none" (no limit), otherwise 1024 or 4096
141- createdAt: new Date(),
142- generationTimeMs: null,
143- toolCallCounts: extractToolCounts(allToolCalls),
144- });
145- await db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, threadId));
146-
147- // Send done message with metadata for aborted generation
148- safeEnqueue({
149- type: "done",
150- answer: accumulatedContent,
151- model: threadModel,
152- maxPromptLength: threadMaxPromptLength,
153- });
154- }
155- safeClose();
156- return;
157- }
158-
159- // Store assistant message with model, maxPromptLength, generation time and tool calls
160- await db.insert(messages).values({
161- threadId: threadId,
162- role: "assistant",
163- content: accumulatedContent,
164- model: threadModel,
165- maxPromptLength: threadMaxPromptLength === "none" ? null : threadMaxPromptLength, // null means "none" (no limit), otherwise 1024 or 4096
166- createdAt: new Date(),
167- generationTimeMs,
168- toolCallCounts: toolCalls ? extractToolCounts(toolCalls) : null,
169- });
170-
171- // Update thread's updatedAt timestamp
172- await db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, threadId));
173-
174- // Send final message with metadata
175- safeEnqueue({
176- type: "done",
177- answer: accumulatedContent,
178- model: threadModel,
179- maxPromptLength: threadMaxPromptLength,
180- });
181- safeClose();
182- } catch {
183- safeEnqueue({ type: "error", error: "Sorry, something went wrong." });
184- safeClose();
185- }
186- },
187- });
188-
189- return stream;
190-}
src/lib/ollama/duckduckgo.ts+59−62
@@ -33,84 +33,81 @@ export async function queryDuckDuckGo(query: string): Promise<string> {
3333 const rateLimitCheck = await duckDuckGoRateLimiter.check();
3434 if (!rateLimitCheck.allowed) {
3535 const hoursRemaining = rateLimitCheck.hoursUntilReset || 0;
36- return `Error: DuckDuckGo API rate limit exceeded. Maximum of 500 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`;
36+ throw new Error(
37+ `DuckDuckGo API rate limit exceeded. Maximum of 500 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`
38+ );
3739 }
3840
39- try {
40- // Increment rate limit counter before making the request
41- // This ensures all API attempts are counted, not just successful ones
42- await duckDuckGoRateLimiter.increment();
43- const url = "https://api.duckduckgo.com/";
44- const params = new URLSearchParams({
45- q: query,
46- format: "json",
47- no_html: "1",
48- skip_disambig: "1",
49- });
50-
51- const response = await fetch(`${url}?${params.toString()}`);
52- if (!response.ok) {
53- debug(`[DuckDuckGo] Error: HTTP ${response.status}`);
54- return `Error: Failed to fetch data from DuckDuckGo (${response.status})`;
55- }
41+ // Increment rate limit counter before making the request
42+ // This ensures all API attempts are counted, not just successful ones
43+ await duckDuckGoRateLimiter.increment();
44+ const url = "https://api.duckduckgo.com/";
45+ const params = new URLSearchParams({
46+ q: query,
47+ format: "json",
48+ no_html: "1",
49+ skip_disambig: "1",
50+ });
51+
52+ const response = await fetch(`${url}?${params.toString()}`);
53+ if (!response.ok) {
54+ debug(`[DuckDuckGo] Error: HTTP ${response.status}`);
55+ throw new Error(`Failed to fetch data from DuckDuckGo (${response.status})`);
56+ }
5657
57- const data = await response.json();
58+ const data = await response.json();
5859
59- // Build a comprehensive response from available fields
60- const parts: string[] = [];
60+ // Build a comprehensive response from available fields
61+ const parts: string[] = [];
6162
62- if (data.Heading) {
63- parts.push(`Heading: ${data.Heading}`);
64- }
65-
66- if (data.AbstractText) {
67- parts.push(`Abstract: ${data.AbstractText}`);
68- }
63+ if (data.Heading) {
64+ parts.push(`Heading: ${data.Heading}`);
65+ }
6966
70- if (data.AbstractURL) {
71- parts.push(`Source: ${data.AbstractURL}`);
72- }
67+ if (data.AbstractText) {
68+ parts.push(`Abstract: ${data.AbstractText}`);
69+ }
7370
74- if (data.Answer) {
75- parts.push(`Answer: ${data.Answer}`);
76- }
71+ if (data.AbstractURL) {
72+ parts.push(`Source: ${data.AbstractURL}`);
73+ }
7774
78- if (data.Definition) {
79- parts.push(`Definition: ${data.Definition}`);
80- }
75+ if (data.Answer) {
76+ parts.push(`Answer: ${data.Answer}`);
77+ }
8178
82- if (data.Type) {
83- parts.push(`Type: ${data.Type}`);
84- }
79+ if (data.Definition) {
80+ parts.push(`Definition: ${data.Definition}`);
81+ }
8582
86- if (data.RelatedTopics && data.RelatedTopics.length > 0) {
87- const topics = data.RelatedTopics.slice(0, 3)
88- .map((topic: { Text?: string; FirstURL?: string }) => topic.Text || topic.FirstURL)
89- .filter(Boolean)
90- .join(", ");
91- if (topics) {
92- parts.push(`Related Topics: ${topics}`);
93- }
94- }
83+ if (data.Type) {
84+ parts.push(`Type: ${data.Type}`);
85+ }
9586
96- if (parts.length === 0) {
97- // DuckDuckGo Instant Answer API has limitations - it doesn't support all query types
98- // (e.g., weather forecasts, real-time data). This is expected behavior.
99- debug(`[DuckDuckGo] No instant answer data available for this query type`);
100- const result = `No instant answer available for query: "${query}". Note: DuckDuckGo Instant Answer API has limited coverage and may not support weather forecasts, real-time data, or certain query types.`;
101- // Cache even "no answer" responses to avoid repeated API calls
102- await setCache(cacheKey, result, CACHE_TTL_MS);
103- return result;
87+ if (data.RelatedTopics && data.RelatedTopics.length > 0) {
88+ const topics = data.RelatedTopics.slice(0, 3)
89+ .map((topic: { Text?: string; FirstURL?: string }) => topic.Text || topic.FirstURL)
90+ .filter(Boolean)
91+ .join(", ");
92+ if (topics) {
93+ parts.push(`Related Topics: ${topics}`);
10494 }
95+ }
10596
106- const result = parts.join("\n\n");
107- // Cache successful results
97+ if (parts.length === 0) {
98+ // DuckDuckGo Instant Answer API has limitations - it doesn't support all query types
99+ // (e.g., weather forecasts, real-time data). This is expected behavior.
100+ debug(`[DuckDuckGo] No instant answer data available for this query type`);
101+ const result = `No instant answer available for query: "${query}". Note: DuckDuckGo Instant Answer API has limited coverage and may not support weather forecasts, real-time data, or certain query types.`;
102+ // Cache even "no answer" responses to avoid repeated API calls
108103 await setCache(cacheKey, result, CACHE_TTL_MS);
109104 return result;
110- } catch (error) {
111- // Don't cache errors
112- return `Error querying DuckDuckGo: ${error instanceof Error ? error.message : "Unknown error"}`;
113105 }
106+
107+ const result = parts.join("\n\n");
108+ // Cache successful results
109+ await setCache(cacheKey, result, CACHE_TTL_MS);
110+ return result;
114111 }
115112
116113 /**
src/lib/ollama/index.ts+26−6
@@ -16,7 +16,11 @@ import type { OllamaChunk, OllamaResponse, MaxPromptLength } from "@/src/lib/oll
1616 */
1717 async function executeToolCall(toolCall: ToolCall): Promise<Message> {
1818 const { name, arguments: args } = toolCall.function;
19- const { query } = args as { query: string };
19+ const { query, timezone, forecastDays } = args as {
20+ query: string;
21+ timezone?: string;
22+ forecastDays?: number;
23+ };
2024
2125 const tools = {
2226 query_web_search: queryWebSearch,
@@ -26,11 +30,16 @@ async function executeToolCall(toolCall: ToolCall): Promise<Message> {
2630
2731 let result: string;
2832 try {
29- result = tools[name](query);
33+ if (name === "query_weather") {
34+ result = await queryWeather(query, timezone, forecastDays);
35+ } else {
36+ result = await tools[name](query);
37+ }
3038 debug(`[Tool] ${name} completed, result length: ${result.length} chars`);
3139 } catch (error) {
32- debug("[Tool] call failed: " + error.message || "Unknown error")
33- result = `Error executing tool call: ${error.message || "Unknown error"}`;
40+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
41+ debug(`[Tool] ${name} failed: ${errorMessage}`);
42+ result = `Error: ${errorMessage}`;
3443 }
3544
3645 return {
@@ -193,8 +202,19 @@ export async function fetchOllamaResponse(
193202 allToolCalls.push(...toolCalls);
194203
195204 for (const toolCall of toolCalls) {
196- const toolResponse = await executeToolCall(toolCall);
197- currentMessages.push(toolResponse);
205+ try {
206+ const toolResponse = await executeToolCall(toolCall);
207+ currentMessages.push(toolResponse);
208+ } catch (error) {
209+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
210+ debug(`[Ollama] Tool execution failed: ${errorMessage}`);
211+ // Add error message as tool response so the model can handle it
212+ currentMessages.push({
213+ role: "tool",
214+ tool_name: toolCall.function.name,
215+ content: `Error: ${errorMessage}`,
216+ });
217+ }
198218 }
199219
200220 debug(`[Ollama] Tool responses received, continuing conversation...`);
src/lib/ollama/weather.ts+123−143
@@ -16,172 +16,142 @@ const weatherRateLimiter = createRateLimiter({
1616 identifier: "weather",
1717 });
1818
19-/**
20- * Converts WMO weather code to human-readable description.
21- * Based on WMO Weather interpretation codes (WW).
22- */
23-function getWeatherDescription(code: number): string {
24- const descriptions: { [key: number]: string } = {
25- 0: "Clear sky",
26- 1: "Mainly clear",
27- 2: "Partly cloudy",
28- 3: "Overcast",
29- 45: "Foggy",
30- 48: "Depositing rime fog",
31- 51: "Light drizzle",
32- 53: "Moderate drizzle",
33- 55: "Dense drizzle",
34- 56: "Light freezing drizzle",
35- 57: "Dense freezing drizzle",
36- 61: "Slight rain",
37- 63: "Moderate rain",
38- 65: "Heavy rain",
39- 66: "Light freezing rain",
40- 67: "Heavy freezing rain",
41- 71: "Slight snow fall",
42- 73: "Moderate snow fall",
43- 75: "Heavy snow fall",
44- 77: "Snow grains",
45- 80: "Slight rain showers",
46- 81: "Moderate rain showers",
47- 82: "Violent rain showers",
48- 85: "Slight snow showers",
49- 86: "Heavy snow showers",
50- 95: "Thunderstorm",
51- 96: "Thunderstorm with slight hail",
52- 99: "Thunderstorm with heavy hail",
53- };
54-
55- return descriptions[code] || `Weather code ${code}`;
56-}
57-
5819 /**
5920 * Queries Open-Meteo's weather API for current weather and forecast information.
6021 * Results are cached for 6 hours.
6122 *
62- * @param location - The location name (e.g., 'New York', 'London', 'Tokyo').
23+ * @param query - The location name (e.g., 'New York', 'London', 'Tokyo').
24+ * @param timezone - Timezone (e.g., 'America/New_York', 'Europe/London', 'auto'). Defaults to 'auto'.
25+ * @param forecastDays - Number of forecast days (1-16). Defaults to 3.
6326 * @returns A formatted string containing weather information or an error message.
6427 */
65-export async function queryWeather(location: string): Promise<string> {
28+export async function queryWeather(
29+ query: string,
30+ timezone = "auto",
31+ forecastDays = 0
32+): Promise<string> {
33+ // Validate forecastDays (0 means no forecast, 1-16 for forecast days)
34+ const days = Math.max(0, Math.min(16, Math.round(forecastDays)));
35+
6636 // Check cache first
67- const cacheKey = `weather:${location.toLowerCase().trim()}`;
37+ const cacheKey = `weather:${query.toLowerCase().trim()}:${timezone}:${days}`;
6838 const cached = await getCache<string>(cacheKey);
6939 if (cached !== null) {
70- debug(`[Weather] Cache hit for: "${location}"`);
40+ debug(`[Weather] Cache hit for: "${query}"`);
7141 return cached;
7242 }
7343
74- debug(`[Weather] Querying weather for: "${location}"`);
44+ debug(
45+ `[Weather] Querying weather for: "${query}" (${days > 0 ? `${days} days` : "current only"}, ${timezone})`
46+ );
7547
7648 // Check rate limit before making the request
7749 const rateLimitCheck = await weatherRateLimiter.check();
7850 if (!rateLimitCheck.allowed) {
7951 const hoursRemaining = rateLimitCheck.hoursUntilReset || 0;
80- return `Error: Weather API rate limit exceeded. Maximum of 1000 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`;
52+ throw new Error(
53+ `Weather API rate limit exceeded. Maximum of 1000 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`
54+ );
8155 }
8256
83- try {
84- // Increment rate limit counter before making the request
85- // This ensures all API attempts are counted, not just successful ones
86- await weatherRateLimiter.increment();
87- // First, geocode the location to get coordinates
88- const geocodeUrl = "https://geocoding-api.open-meteo.com/v1/search";
89- const geocodeParams = new URLSearchParams({
90- name: location,
91- count: "1",
92- language: "en",
93- format: "json",
94- });
95-
96- const geocodeResponse = await fetch(`${geocodeUrl}?${geocodeParams.toString()}`);
97- if (!geocodeResponse.ok) {
98- debug(`[Weather] Geocoding error: HTTP ${geocodeResponse.status}`);
99- return `Error: Failed to geocode location "${location}" (${geocodeResponse.status})`;
100- }
57+ // Increment rate limit counter before making the request
58+ // This ensures all API attempts are counted, not just successful ones
59+ await weatherRateLimiter.increment();
60+ // First, geocode the location to get coordinates
61+ const geocodeUrl = "https://geocoding-api.open-meteo.com/v1/search";
62+ const geocodeParams = new URLSearchParams({
63+ name: query,
64+ count: "1",
65+ language: "en",
66+ format: "json",
67+ });
68+
69+ const geocodeResponse = await fetch(`${geocodeUrl}?${geocodeParams.toString()}`);
70+ if (!geocodeResponse.ok) {
71+ debug(`[Weather] Geocoding error: HTTP ${geocodeResponse.status}`);
72+ throw new Error(`Failed to geocode location "${query}" (${geocodeResponse.status})`);
73+ }
10174
102- const geocodeData = await geocodeResponse.json();
75+ const geocodeData = await geocodeResponse.json();
10376
104- if (!geocodeData.results || geocodeData.results.length === 0) {
105- return `Error: Could not find location "${location}". Please provide a more specific location name.`;
106- }
77+ if (!geocodeData.results || geocodeData.results.length === 0) {
78+ throw new Error(
79+ `Could not find location "${query}". Please provide a more specific location name.`
80+ );
81+ }
10782
108- const { latitude, longitude, name, country, admin1 } = geocodeData.results[0];
109- const locationName = `${name}${admin1 ? `, ${admin1}` : ""}${country ? `, ${country}` : ""}`;
110-
111- debug(`[Weather] Found location: ${locationName} (${latitude}, ${longitude})`);
112-
113- // Now fetch weather data
114- const weatherUrl = "https://api.open-meteo.com/v1/forecast";
115- const weatherParams = new URLSearchParams({
116- latitude: latitude.toString(),
117- longitude: longitude.toString(),
118- current: "temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m,wind_direction_10m",
119- hourly: "temperature_2m,weather_code,precipitation_probability",
120- daily: "temperature_2m_max,temperature_2m_min,weather_code,precipitation_sum",
121- forecast_days: "3",
122- timezone: "auto",
123- });
124-
125- const weatherResponse = await fetch(`${weatherUrl}?${weatherParams.toString()}`);
126- if (!weatherResponse.ok) {
127- debug(`[Weather] Weather API error: HTTP ${weatherResponse.status}`);
128- return `Error: Failed to fetch weather data for "${locationName}" (${weatherResponse.status})`;
129- }
83+ const { latitude, longitude, name, country, admin1 } = geocodeData.results[0];
84+ const locationName = `${name}${admin1 ? `, ${admin1}` : ""}${country ? `, ${country}` : ""}`;
13085
131- const weatherData = await weatherResponse.json();
132-
133- // Format the response
134- const parts: string[] = [];
135- parts.push(`Weather for ${locationName}:`);
136-
137- // Current conditions
138- if (weatherData.current) {
139- const current = weatherData.current;
140- parts.push(`\nCurrent Conditions:`);
141- parts.push(` Temperature: ${current.temperature_2m}°C`);
142- parts.push(` Humidity: ${current.relative_humidity_2m}%`);
143- parts.push(` Wind Speed: ${current.wind_speed_10m} km/h`);
144- if (current.wind_direction_10m !== undefined) {
145- parts.push(` Wind Direction: ${current.wind_direction_10m}°`);
146- }
147- if (current.weather_code !== undefined) {
148- const weatherDesc = getWeatherDescription(current.weather_code);
149- parts.push(` Conditions: ${weatherDesc}`);
150- }
86+ debug(`[Weather] Found location: ${locationName} (${latitude}, ${longitude})`);
87+
88+ // Now fetch weather data - focus on temperature and precipitation
89+ const weatherUrl = "https://api.open-meteo.com/v1/forecast";
90+ const weatherParams = new URLSearchParams({
91+ latitude: latitude.toString(),
92+ longitude: longitude.toString(),
93+ current: "temperature_2m,precipitation",
94+ timezone: timezone,
95+ });
96+
97+ // Only request daily forecast if forecastDays > 0
98+ if (days > 0) {
99+ weatherParams.append("daily", "temperature_2m_max,temperature_2m_min,precipitation_sum");
100+ weatherParams.append("forecast_days", days.toString());
101+ }
102+
103+ const weatherResponse = await fetch(`${weatherUrl}?${weatherParams.toString()}`);
104+ if (!weatherResponse.ok) {
105+ debug(`[Weather] Weather API error: HTTP ${weatherResponse.status}`);
106+ throw new Error(
107+ `Failed to fetch weather data for "${locationName}" (${weatherResponse.status})`
108+ );
109+ }
110+
111+ const weatherData = await weatherResponse.json();
112+
113+ // Format concise response focusing on temperature and precipitation
114+ const parts: string[] = [];
115+ parts.push(`${locationName}:`);
116+
117+ // Current conditions
118+ if (weatherData.current) {
119+ const current = weatherData.current;
120+ const temp = current.temperature_2m;
121+ const precip = current.precipitation;
122+ if (temp !== undefined) {
123+ parts.push(`Now: ${temp}°C${precip !== undefined && precip > 0 ? `, ${precip}mm rain` : ""}`);
151124 }
125+ }
152126
153- // Daily forecast (next 3 days)
154- if (weatherData.daily && weatherData.daily.time) {
155- parts.push(`\n3-Day Forecast:`);
156- for (let i = 0; i < Math.min(3, weatherData.daily.time.length); i++) {
157- const date = new Date(weatherData.daily.time[i]);
158- const dayName = date.toLocaleDateString("en-US", { weekday: "long" });
159- const maxTemp = weatherData.daily.temperature_2m_max?.[i];
160- const minTemp = weatherData.daily.temperature_2m_min?.[i];
161- const weatherCode = weatherData.daily.weather_code?.[i];
162- const precipitation = weatherData.daily.precipitation_sum?.[i];
163-
164- parts.push(`\n ${dayName} (${date.toLocaleDateString()}):`);
165- if (maxTemp !== undefined && minTemp !== undefined) {
166- parts.push(` High: ${maxTemp}°C, Low: ${minTemp}°C`);
167- }
168- if (weatherCode !== undefined) {
169- parts.push(` Conditions: ${getWeatherDescription(weatherCode)}`);
170- }
171- if (precipitation !== undefined && precipitation > 0) {
172- parts.push(` Precipitation: ${precipitation} mm`);
173- }
127+ // Daily forecast (only if forecastDays > 0)
128+ if (days > 0 && weatherData.daily && weatherData.daily.time) {
129+ for (let i = 0; i < Math.min(days, weatherData.daily.time.length); i++) {
130+ const date = new Date(weatherData.daily.time[i]);
131+ const dayName = date.toLocaleDateString("en-US", { weekday: "short" });
132+ const maxTemp = weatherData.daily.temperature_2m_max?.[i];
133+ const minTemp = weatherData.daily.temperature_2m_min?.[i];
134+ const precipitation = weatherData.daily.precipitation_sum?.[i];
135+
136+ const tempStr =
137+ maxTemp !== undefined && minTemp !== undefined
138+ ? `${minTemp}°/${maxTemp}°C`
139+ : maxTemp !== undefined
140+ ? `${maxTemp}°C`
141+ : "";
142+ const precipStr =
143+ precipitation !== undefined && precipitation > 0 ? `, ${precipitation}mm` : "";
144+
145+ if (tempStr) {
146+ parts.push(`${dayName}: ${tempStr}${precipStr}`);
174147 }
175148 }
176-
177- const result = parts.join("\n");
178- // Cache successful results
179- await setCache(cacheKey, result, CACHE_TTL_MS);
180- return result;
181- } catch (error) {
182- // Don't cache errors
183- return `Error querying weather: ${error instanceof Error ? error.message : "Unknown error"}`;
184149 }
150+
151+ const result = parts.join("\n");
152+ // Cache successful results
153+ await setCache(cacheKey, result, CACHE_TTL_MS);
154+ return result;
185155 }
186156
187157 /**
@@ -191,18 +161,28 @@ export const weatherTool = {
191161 type: "function" as const,
192162 function: {
193163 name: "query_weather",
194- description:
195- "Query Open-Meteo's weather API to get current weather conditions and 3-day forecast for a location. Use this when users ask about weather, temperature, forecast, or current conditions for any location worldwide.",
164+ description:
165+ "Query Open-Meteo's weather API to get current weather conditions and optionally forecast for a location. Returns temperature and precipitation data. By default returns only current weather. Use forecastDays parameter to include forecast. Use this when users ask about weather, temperature, forecast, or current conditions for any location worldwide.",
196166 parameters: {
197167 type: "object",
198168 properties: {
199- location: {
169+ query: {
200170 type: "string",
201171 description:
202- "The location name (e.g., 'New York', 'London', 'Tokyo', 'Paris'). Can be a city name, city with country, or more specific location.",
172+ "Location name (e.g., 'New York', 'London', 'Tokyo', 'Paris'). Can be a city name, city with country, or more specific location.",
173+ },
174+ timezone: {
175+ type: "string",
176+ description:
177+ "Timezone (e.g., 'America/New_York', 'Europe/London', 'Asia/Tokyo'). Use 'auto' to automatically detect. Defaults to 'auto'.",
178+ },
179+ forecastDays: {
180+ type: "number",
181+ description:
182+ "Number of forecast days (0-16). Use 0 for current weather only (default), or 1-16 for forecast days.",
203183 },
204184 },
205- required: ["location"],
185+ required: ["query"],
206186 },
207187 },
208188 };
src/lib/ollama/websearch.ts+41−42
@@ -41,60 +41,59 @@ export async function queryWebSearch(query: string): Promise<string> {
4141
4242 if (!apiKey || !cx) {
4343 debug(`[WebSearch] Missing API credentials`);
44- return `Error: Google Custom Search API credentials not configured. Please set GOOGLE_CUSTOM_SEARCH_API_KEY and GOOGLE_CUSTOM_SEARCH_ENGINE_ID environment variables.`;
44+ throw new Error(
45+ "Google Custom Search API credentials not configured. Please set GOOGLE_CUSTOM_SEARCH_API_KEY and GOOGLE_CUSTOM_SEARCH_ENGINE_ID environment variables."
46+ );
4547 }
4648
4749 // Check rate limit before making the request
4850 const rateLimitCheck = await webSearchRateLimiter.check();
4951 if (!rateLimitCheck.allowed) {
5052 const hoursRemaining = rateLimitCheck.hoursUntilReset || 0;
51- return `Error: Web search rate limit exceeded. Maximum of 100 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`;
53+ throw new Error(
54+ `Web search rate limit exceeded. Maximum of 100 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`
55+ );
5256 }
5357
54- try {
55- // Increment rate limit counter before making the request
56- // This ensures all API attempts are counted, not just successful ones
57- await webSearchRateLimiter.increment();
58-
59- const customsearch = google.customsearch("v1");
60- const res = await customsearch.cse.list({
61- cx: cx,
62- q: query,
63- auth: apiKey,
64- });
65-
66- if (!res.data.items || res.data.items.length === 0) {
67- debug(`[WebSearch] No results found for query: "${query}"`);
68- const result = `No search results found for query: "${query}"`;
69- // Cache even "no results" responses to avoid repeated API calls
70- await setCache(cacheKey, result, CACHE_TTL_MS);
71- return result;
72- }
58+ // Increment rate limit counter before making the request
59+ // This ensures all API attempts are counted, not just successful ones
60+ await webSearchRateLimiter.increment();
61+
62+ const customsearch = google.customsearch("v1");
63+ const res = await customsearch.cse.list({
64+ cx: cx,
65+ q: query,
66+ auth: apiKey,
67+ });
68+
69+ if (!res.data.items || res.data.items.length === 0) {
70+ debug(`[WebSearch] No results found for query: "${query}"`);
71+ const result = `No search results found for query: "${query}"`;
72+ // Cache even "no results" responses to avoid repeated API calls
73+ await setCache(cacheKey, result, CACHE_TTL_MS);
74+ return result;
75+ }
7376
74- debug(`[WebSearch] Found ${res.data.items.length} results`);
77+ debug(`[WebSearch] Found ${res.data.items.length} results`);
7578
76- const parts: string[] = [];
77- parts.push(`Web search results for "${query}":\n`);
79+ const parts: string[] = [];
80+ parts.push(`Web search results for "${query}":\n`);
7881
79- res.data.items.forEach((item, index) => {
80- parts.push(`${index + 1}. ${item.title || "Untitled"}`);
81- if (item.link) {
82- parts.push(` URL: ${item.link}`);
83- }
84- if (item.snippet) {
85- parts.push(` ${item.snippet}`);
86- }
87- parts.push(""); // Empty line between results
88- });
82+ res.data.items.forEach((item, index) => {
83+ parts.push(`${index + 1}. ${item.title || "Untitled"}`);
84+ if (item.link) {
85+ parts.push(` URL: ${item.link}`);
86+ }
87+ if (item.snippet) {
Cut short: this commit's diff is over 1000 lines.
tsconfig.tsbuildinfo+1−1
Cut short: this commit's diff is over 1000 lines.