xonecas.io
53129
Pa

PAT / files

PAT / src / lib / threads.ts

3.9 KB
1import { db } from "@/src/lib/db";
2import { threads } from "@/src/lib/db/schema";
3import { debug } from "@/src/lib/debug";
4import { createMessage } from "@/src/lib/messages";
5import ollama from "ollama";
6
7export async function generateTitle(model: string, message: string): Promise<string> {
8  const response = await ollama.generate({
9    model: model,
10    prompt: `Create a concise summary using only alphanumeric characters and spaces of the following message: "${message}."`,
11  });
12
13  return response.response ?? message.substring(0, 100);
14}
15
16export function generateSystemPrompt(options: {
17  time?: string;
18  timezone?: string;
19  userPrompt?: string | null;
20}): string {
21  const { time, timezone, userPrompt } = options;
22
23  // Build system prompt with location and time if available
24  let systemPrompt = `**Purpose:** Assist the user with their questions and tasks. Don't lie, don't make up information, don't make assumptions.
25**Format:** Reply with markdown whenever possible. When asked for code or text return it in a markdown code block. Include links to the sources you used to answer the question. Include map links when asked about locations.
26**Style and tone:** Use a friendly, professional, and helpful tone. Be concise and to the point. Avoid repeating yourself. Avoid using emojis.
27**Context:** You are PAT, a helpful personal assistant. Bellow you can see the contextual information for the conversation, like time and location of the user. Use this information to help the user.`;
28
29  // Filter out empty strings - only use non-empty values
30  const validTime = time?.trim() || undefined;
31  const validTimezone = timezone?.trim() || undefined;
32
33  if (validTime || validTimezone) {
34    systemPrompt += "\n\n";
35    if (validTime && validTimezone) {
36      // Format time in the user's timezone
37      try {
38        const timeDate = new Date(validTime);
39        const formattedTime = new Intl.DateTimeFormat("en-US", {
40          timeZone: validTimezone,
41          year: "numeric",
42          month: "long",
43          day: "numeric",
44          hour: "numeric",
45          minute: "2-digit",
46          second: "2-digit",
47          timeZoneName: "short",
48        }).format(timeDate);
49        systemPrompt += `**User's current time:** ${formattedTime}\n`;
50      } catch {
51        // Fallback to ISO string if timezone formatting fails
52        systemPrompt += `**User's current time:** ${validTime}\n`;
53      }
54    } else if (validTime) {
55      systemPrompt += `**User's current time:** ${validTime}\n`;
56    }
57    if (validTimezone) {
58      // Extract city name, take everything after the / and replace underscores.
59      const timezoneCity = validTimezone.split("/").slice(1).join("/").replace(/_/g, " ").trim();
60      systemPrompt += `**User's location:** ${timezoneCity}`;
61    }
62  }
63
64  // Add user prompt if provided
65  if (userPrompt && userPrompt.trim()) {
66    systemPrompt += "\n\n";
67    systemPrompt += `**User added information:**:\n${userPrompt.trim()}`;
68  }
69
70  return systemPrompt;
71}
72
73export async function createThread(
74  userMessage: string,
75  model: string,
76  maxPromptLength: "none" | 1024 | 4096,
77  userPrompt: string,
78  time: string,
79  timezone: string
80) {
81  let title = userMessage.substring(0, 100);
82  try {
83    title = await generateTitle(model, userMessage);
84  } catch (error) {
85    debug(`[Threads] Error generating title:`, error);
86  }
87
88  const newThread = await db
89    .insert(threads)
90    .values({
91      title: title,
92      model: model,
93      maxPromptLength:
94        maxPromptLength === "none" || maxPromptLength === null ? null : maxPromptLength,
95      userPrompt: userPrompt || null,
96      createdAt: new Date(),
97      updatedAt: new Date(),
98    })
99    .returning();
100
101  const threadId = newThread[0].id;
102
103  // Generate system prompt
104  const systemPrompt = generateSystemPrompt({
105    time,
106    timezone,
107    userPrompt: userPrompt || null,
108  });
109
110  // Insert system message with guidelines
111  await createMessage(systemPrompt, "system", threadId);
112
113  return newThread[0];
114}