Local models were burning the 8-round budget on simple event adds. Raise the limit, resolve calendars by name/default, and inject the household clock so relative dates work.
This commit is contained in:
@@ -1,13 +1,13 @@
|
||||
import { createLlmClient, type ChatMessage, type LlmClient } from "@/lib/llm";
|
||||
import { buildVisionContentParts, textFromMessageContent } from "@/lib/llm/content";
|
||||
import { AGENT_SYSTEM_PROMPT, AGENT_TOOLS } from "../tools";
|
||||
import { AGENT_SYSTEM_PROMPT, AGENT_TOOLS, appendAgentRuntimeContext } from "../tools";
|
||||
import type { ClientChatMessage } from "../messages";
|
||||
import { describeToolActivity } from "../tool-labels";
|
||||
import { createApiToolExecutor, type ToolExecutor } from "../tool-executor";
|
||||
import { resolveAssistantImageDataUrls } from "./resolve-images";
|
||||
import { thinkingLabel, type AgentProgressEvent } from "./progress";
|
||||
|
||||
const MAX_TOOL_ROUNDS = 8;
|
||||
const MAX_TOOL_ROUNDS = 24;
|
||||
|
||||
export type AgentToolCallSummary = {
|
||||
name: string;
|
||||
@@ -53,7 +53,7 @@ export async function runAgentChat(options: {
|
||||
const llm = options.llm ?? createLlmClient({ model: options.model });
|
||||
const executeTool = options.executeTool ?? createApiToolExecutor(options.request);
|
||||
const onProgress = options.onProgress;
|
||||
const systemPrompt = options.systemPrompt ?? AGENT_SYSTEM_PROMPT;
|
||||
const systemPrompt = appendAgentRuntimeContext(options.systemPrompt ?? AGENT_SYSTEM_PROMPT);
|
||||
|
||||
const userMessages = await Promise.all(
|
||||
options.messages.map((message) => toLlmUserMessage(message)),
|
||||
|
||||
@@ -111,8 +111,11 @@ async function dispatchTool(
|
||||
return callApi(request, origin, "GET", `/api/v1/events?${qs.toString()}`);
|
||||
}
|
||||
case "create_event": {
|
||||
const resolved = await resolveCalendarId(args, request, origin);
|
||||
if ("error" in resolved) return resolved.error;
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
calendarId: requireString(args, "calendarId"),
|
||||
calendarId: resolved.calendarId,
|
||||
title: requireString(args, "title"),
|
||||
startAt: requireString(args, "startAt"),
|
||||
endAt: requireString(args, "endAt"),
|
||||
@@ -375,6 +378,49 @@ async function dispatchTool(
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveCalendarId(
|
||||
args: Record<string, unknown>,
|
||||
request: Request,
|
||||
origin: string,
|
||||
): Promise<{ calendarId: string } | { error: ApiCallResult }> {
|
||||
const calendarId = typeof args.calendarId === "string" ? args.calendarId.trim() : "";
|
||||
if (calendarId) return { calendarId };
|
||||
|
||||
const calendarsResult = await callApi(request, origin, "GET", "/api/v1/calendars");
|
||||
if (calendarsResult.status !== 200 || !Array.isArray(calendarsResult.body)) {
|
||||
return { error: calendarsResult };
|
||||
}
|
||||
|
||||
const calendars = calendarsResult.body as Array<{ id?: string; name?: string }>;
|
||||
const calendarName =
|
||||
typeof args.calendarName === "string" ? args.calendarName.trim().toLowerCase() : "";
|
||||
|
||||
if (calendarName) {
|
||||
const match = calendars.find(
|
||||
(calendar) =>
|
||||
typeof calendar.name === "string" && calendar.name.toLowerCase() === calendarName,
|
||||
);
|
||||
if (!match?.id) {
|
||||
return {
|
||||
error: {
|
||||
status: 404,
|
||||
body: {
|
||||
error: `No calendar named "${args.calendarName}"`,
|
||||
calendars: calendars.map((calendar) => ({ id: calendar.id, name: calendar.name })),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
return { calendarId: match.id };
|
||||
}
|
||||
|
||||
const first = calendars[0];
|
||||
if (!first?.id) {
|
||||
return { error: { status: 404, body: { error: "No calendars found" } } };
|
||||
}
|
||||
return { calendarId: first.id };
|
||||
}
|
||||
|
||||
function requireString(args: Record<string, unknown>, key: string): string {
|
||||
const value = args[key];
|
||||
if (typeof value !== "string" || value.trim().length === 0) {
|
||||
|
||||
@@ -159,11 +159,16 @@ export const AGENT_TOOLS: AgentToolDefinition[] = [
|
||||
type: "function",
|
||||
function: {
|
||||
name: "create_event",
|
||||
description: "Create a calendar event.",
|
||||
description:
|
||||
"Create a calendar event. Provide calendarId, or calendarName to match by name, or omit both to use the first visible calendar.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
calendarId: { type: "string" },
|
||||
calendarId: { type: "string", description: "UUID of the calendar" },
|
||||
calendarName: {
|
||||
type: "string",
|
||||
description: "Calendar display name when calendarId is unknown",
|
||||
},
|
||||
title: { type: "string" },
|
||||
startAt: { type: "string", description: "ISO 8601 start" },
|
||||
endAt: { type: "string", description: "ISO 8601 end" },
|
||||
@@ -175,7 +180,7 @@ export const AGENT_TOOLS: AgentToolDefinition[] = [
|
||||
description: "Optional reminder N minutes before start",
|
||||
},
|
||||
},
|
||||
required: ["calendarId", "title", "startAt", "endAt"],
|
||||
required: ["title", "startAt", "endAt"],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -762,13 +767,14 @@ export const AGENT_SYSTEM_PROMPT = `You are the famapp household assistant. Help
|
||||
|
||||
Use the provided tools to read and update data. Prefer calling tools instead of guessing. Be concise and friendly.
|
||||
|
||||
When no dedicated tool fits, or you are unsure how to do something:
|
||||
Prefer a dedicated tool when one exists (create_event, add_list_item, create_note, etc.). When no dedicated tool fits, or you need an endpoint that is not wrapped yet:
|
||||
1. Call get_api_docs with a relevant search term to find the right /api/v1/* endpoint.
|
||||
2. Call call_api with the documented method, path, query, and body.
|
||||
If a tool call fails, read the error body and fix the arguments before trying a different approach.
|
||||
|
||||
When the user sends a photo, read dates, times, locations, and action items from it, then use tools to act.
|
||||
|
||||
Lists: resolve list ids via list_lists. To complete items, list_list_items then update_list_item with done: true.
|
||||
Lists: resolve list ids via list_lists, or pass listType to add_list_item. To complete items, list_list_items then update_list_item with done: true.
|
||||
|
||||
Journal: per-user private entries. Valid mood ids: ${JOURNAL_MOOD_IDS}. stress is 1-10. pillsTaken is boolean.
|
||||
|
||||
@@ -776,4 +782,32 @@ Garden: care types are free text (water, fertilize, prune, etc.). Use list_garde
|
||||
|
||||
Sharing: journal entries are not shareable. Shareable types: calendar, calendar.event, list, note, garden.plant, garden.container.
|
||||
|
||||
Calendar: use ISO 8601 datetimes. Bang dates use YYYY-MM-DD.`;
|
||||
Calendar: use ISO 8601 datetimes with the household timezone below. Pass calendarId, or calendarName, or omit both to use the first visible calendar. Bang dates use YYYY-MM-DD.`;
|
||||
|
||||
export function resolveHouseholdTimezone(): string {
|
||||
return process.env.HOUSEHOLD_TIMEZONE?.trim() || process.env.TZ?.trim() || "America/Chicago";
|
||||
}
|
||||
|
||||
export function appendAgentRuntimeContext(prompt: string, now: Date = new Date()): string {
|
||||
const timeZone = resolveHouseholdTimezone();
|
||||
let localNow: string;
|
||||
try {
|
||||
localNow = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone,
|
||||
weekday: "long",
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
hour12: true,
|
||||
timeZoneName: "short",
|
||||
}).format(now);
|
||||
} catch {
|
||||
localNow = now.toISOString();
|
||||
}
|
||||
|
||||
return `${prompt.trim()}
|
||||
|
||||
Current time: ${localNow} (${timeZone}). ISO now: ${now.toISOString()}. Resolve relative dates from this clock.`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user