diff --git a/app.dockerfile b/app.dockerfile index 605957e..c3c0fd0 100644 --- a/app.dockerfile +++ b/app.dockerfile @@ -7,7 +7,6 @@ RUN yarn install --frozen-lockfile --network-timeout 600000 COPY tsconfig.json next.config.mjs next-env.d.ts postcss.config.js drizzle.config.ts tailwind.config.ts ./ COPY src ./src -COPY messages ./messages COPY public ./public RUN mkdir -p /home/perplexica/data diff --git a/docs/API/SEARCH.md b/docs/API/SEARCH.md index b67b62b..37c13ba 100644 --- a/docs/API/SEARCH.md +++ b/docs/API/SEARCH.md @@ -34,6 +34,7 @@ The API accepts a JSON object in the request body, where you define the focus mo ["assistant", "I am doing well, how can I help you today?"] ], "systemInstructions": "Focus on providing technical details about Perplexica's architecture.", + "locale": "en-US", "stream": false } ``` @@ -66,6 +67,8 @@ The API accepts a JSON object in the request body, where you define the focus mo - **`systemInstructions`** (string, optional): Custom instructions provided by the user to guide the AI's response. These instructions are treated as user preferences and have lower priority than the system's core instructions. For example, you can specify a particular writing style, format, or focus area. +- **`locale`** (string, optional): Specifies a custom locale for the search operation. If not provided, the default locale (en-US) will be used. This can be useful for tailoring search results to a specific language or region. Format: IETF BCP 47 codes ({ISO 639-1}-{ISO 3166-1 alpha-2}), see https://www.rfc-editor.org/rfc/bcp/bcp47.txt. + - **`history`** (array, optional): An array of message pairs representing the conversation history. Each pair consists of a role (either 'human' or 'assistant') and the message content. This allows the system to use the context of the conversation to refine results. Example: ```json diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts index 2d53b75..81e724f 100644 --- a/src/app/api/chat/route.ts +++ b/src/app/api/chat/route.ts @@ -50,6 +50,7 @@ type Body = { chatModel: ChatModel; embeddingModel: EmbeddingModel; systemInstructions: string; + locale: string; }; const handleEmitterEvents = async ( @@ -280,6 +281,7 @@ export const POST = async (req: Request) => { body.optimizationMode, body.files, body.systemInstructions, + body.locale, ); const responseStream = new TransformStream(); diff --git a/src/app/api/search/route.ts b/src/app/api/search/route.ts index 5f752ec..e2e297f 100644 --- a/src/app/api/search/route.ts +++ b/src/app/api/search/route.ts @@ -13,6 +13,7 @@ import { getCustomOpenaiModelName, } from '@/lib/config'; import { searchHandlers } from '@/lib/search'; +import { DEFAULT_LOCALE } from '@/i18n/locales'; interface chatModel { provider: string; @@ -35,6 +36,7 @@ interface ChatRequestBody { history: Array<[string, string]>; stream?: boolean; systemInstructions?: string; + locale?: string; } export const POST = async (req: Request) => { @@ -126,6 +128,7 @@ export const POST = async (req: Request) => { body.optimizationMode, [], body.systemInstructions || '', + body.locale || DEFAULT_LOCALE, ); if (!body.stream) { diff --git a/src/app/api/suggestions/route.ts b/src/app/api/suggestions/route.ts index 99179d2..78167e4 100644 --- a/src/app/api/suggestions/route.ts +++ b/src/app/api/suggestions/route.ts @@ -8,6 +8,7 @@ import { getAvailableChatModelProviders } from '@/lib/providers'; import { BaseChatModel } from '@langchain/core/language_models/chat_models'; import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages'; import { ChatOpenAI } from '@langchain/openai'; +import { DEFAULT_LOCALE } from '@/i18n/locales'; interface ChatModel { provider: string; @@ -17,6 +18,7 @@ interface ChatModel { interface SuggestionsGenerationBody { chatHistory: any[]; chatModel?: ChatModel; + locale?: string; } export const POST = async (req: Request) => { @@ -66,6 +68,7 @@ export const POST = async (req: Request) => { const suggestions = await generateSuggestions( { chat_history: chatHistory, + locale: body.locale || DEFAULT_LOCALE, }, llm, ); diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 69a88d2..519a009 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -1,15 +1,14 @@ 'use client'; import { Settings as SettingsIcon, ArrowLeft, Loader2 } from 'lucide-react'; -import { useCallback, useEffect, useState } from 'react'; +import { useEffect, useState } from 'react'; import { cn } from '@/lib/utils'; import { Switch } from '@headlessui/react'; import ThemeSwitcher from '@/components/theme/Switcher'; +import LocaleSwitcher from '@/components/LocaleSwitcher'; import { ImagesIcon, VideoIcon } from 'lucide-react'; import Link from 'next/link'; import { PROVIDER_METADATA } from '@/lib/providers'; -import LocaleSwitcher from '@/components/LocaleSwitcher'; -import { getPromptLanguageName } from '@/i18n/locales'; import { useLocale, useTranslations } from 'next-intl'; interface SettingsType { @@ -216,8 +215,7 @@ const Page = () => { localStorage.getItem('autoVideoSearch') === 'true', ); - const stored = localStorage.getItem('systemInstructions') || ''; - setSystemInstructions(stripPrefixedPrompt(stored)); + setSystemInstructions(localStorage.getItem('systemInstructions')!); setMeasureUnit( localStorage.getItem('measureUnit')! as 'Imperial' | 'Metric', @@ -229,37 +227,6 @@ const Page = () => { fetchConfig(); }, []); - // Remove prefix for UI display if it exists in stored value - const stripPrefixedPrompt = (text: string) => { - const trimmed = (text || '').trim(); - const starts = 'Always respond to all non-code content and explanations in'; - if (trimmed.startsWith(starts)) { - const parts = trimmed.split('\n\n'); - // Drop the first block (prefix paragraph and rules) - const rest = parts.slice(1).join('\n\n'); - return rest || ''; - } - return trimmed; - }; - - const buildPrefixedPrompt = useCallback((base: string, loc: string) => { - const langName = getPromptLanguageName(loc); - const prefix = `Always respond to all non-code content and explanations in ${langName}.\nRules:\n1. All descriptions, explanations, and example clarifications must be in ${langName}.\n2. Any content inside code blocks and code comments must be entirely in English.\n3. For language-specific or technical terms, use the original term in that specific language (do not translate it).`; - const trimmed = (base || '').trim(); - // If already starts with the prefix (by simple inclusion of first sentence), avoid duplicating - if ( - trimmed.startsWith( - `Always respond to all non-code content and explanations in`, - ) - ) { - // If locale changed, replace the existing first paragraph block - const parts = trimmed.split('\n\n'); - const rest = parts.slice(1).join('\n\n'); - return `${prefix}${rest ? '\n\n' + rest : ''}`; - } - return prefix + (trimmed ? `\n\n${trimmed}` : ''); - }, []); - const saveConfig = async (key: string, value: any) => { setSavingStates((prev) => ({ ...prev, [key]: true })); @@ -495,16 +462,7 @@ const Page = () => {

{t('preferences.language')}

- { - // Rebuild and persist with new locale prefix; keep UI clean - const prefixed = buildPrefixedPrompt( - systemInstructions, - nextLocale, - ); - saveConfig('systemInstructions', prefixed); - }} - /> + @@ -602,12 +560,7 @@ const Page = () => { onChange={(e) => { setSystemInstructions(e.target.value); }} - onSave={(value) => { - const prefixed = buildPrefixedPrompt(value, locale); - // Keep UI as user input without prefix - setSystemInstructions(value); - saveConfig('systemInstructions', prefixed); - }} + onSave={(value) => saveConfig('systemInstructions', value)} placeholder={t('systemInstructions.placeholder')} /> @@ -857,7 +810,6 @@ const Page = () => {

{ @@ -966,7 +918,6 @@ const Page = () => {

{ diff --git a/src/components/ChatWindow.tsx b/src/components/ChatWindow.tsx index a56e050..6fe48cd 100644 --- a/src/components/ChatWindow.tsx +++ b/src/components/ChatWindow.tsx @@ -7,7 +7,7 @@ import Chat from './Chat'; import EmptyChat from './EmptyChat'; import crypto from 'crypto'; import { toast } from 'sonner'; -import { useTranslations } from 'next-intl'; +import { useLocale, useTranslations } from 'next-intl'; import { useSearchParams } from 'next/navigation'; import { getSuggestions } from '@/lib/actions'; import { Settings } from 'lucide-react'; @@ -264,6 +264,7 @@ const loadMessages = async ( const ChatWindow = ({ id }: { id?: string }) => { const t = useTranslations(); + const locale = useLocale(); const searchParams = useSearchParams(); const initialMessage = searchParams.get('q'); @@ -473,7 +474,7 @@ const ChatWindow = ({ id }: { id?: string }) => { lastMsg.sources.length > 0 && !lastMsg.suggestions ) { - const suggestions = await getSuggestions(messagesRef.current); + const suggestions = await getSuggestions(messagesRef.current, locale); setMessages((prev) => prev.map((msg) => { if (msg.messageId === lastMsg.messageId) { @@ -516,6 +517,7 @@ const ChatWindow = ({ id }: { id?: string }) => { provider: embeddingModelProvider.provider, }, systemInstructions: localStorage.getItem('systemInstructions'), + locale: locale, }), }); diff --git a/messages/de.json b/src/i18n/de.json similarity index 100% rename from messages/de.json rename to src/i18n/de.json diff --git a/messages/en-GB.json b/src/i18n/en-GB.json similarity index 100% rename from messages/en-GB.json rename to src/i18n/en-GB.json diff --git a/messages/en-US.json b/src/i18n/en-US.json similarity index 100% rename from messages/en-US.json rename to src/i18n/en-US.json diff --git a/messages/fr-CA.json b/src/i18n/fr-CA.json similarity index 100% rename from messages/fr-CA.json rename to src/i18n/fr-CA.json diff --git a/messages/fr-FR.json b/src/i18n/fr-FR.json similarity index 100% rename from messages/fr-FR.json rename to src/i18n/fr-FR.json diff --git a/messages/ja.json b/src/i18n/ja.json similarity index 100% rename from messages/ja.json rename to src/i18n/ja.json diff --git a/messages/ko.json b/src/i18n/ko.json similarity index 100% rename from messages/ko.json rename to src/i18n/ko.json diff --git a/src/i18n/locales.ts b/src/i18n/locales.ts index 014dd34..3af8351 100644 --- a/src/i18n/locales.ts +++ b/src/i18n/locales.ts @@ -1,3 +1,4 @@ +// IETF BCP 47 codes, see https://www.rfc-editor.org/rfc/bcp/bcp47.txt. {ISO 639-1}-{ISO 3166-1 alpha-2} export const LOCALES = [ 'en-US', 'en-GB', @@ -10,6 +11,7 @@ export const LOCALES = [ 'fr-CA', 'de', ] as const; + export type AppLocale = (typeof LOCALES)[number]; // Default locale for fallbacks @@ -19,7 +21,7 @@ export const DEFAULT_LOCALE: AppLocale = 'en-US'; export const LOCALE_LABELS: Record = { 'en-US': 'English (US)', 'en-GB': 'English (UK)', - 'zh-TW': '繁體中文', + 'zh-TW': '繁體中文(台灣)', 'zh-HK': '繁體中文(香港)', 'zh-CN': '简体中文', ja: '日本語', diff --git a/src/i18n/request.ts b/src/i18n/request.ts index 79fc15b..a9b7148 100644 --- a/src/i18n/request.ts +++ b/src/i18n/request.ts @@ -110,6 +110,6 @@ export default getRequestConfig(async () => { return { locale, - messages: (await import(`../../messages/${locale}.json`)).default, + messages: (await import(`./${locale}.json`)).default, }; }); diff --git a/messages/zh-CN.json b/src/i18n/zh-CN.json similarity index 100% rename from messages/zh-CN.json rename to src/i18n/zh-CN.json diff --git a/messages/zh-HK.json b/src/i18n/zh-HK.json similarity index 100% rename from messages/zh-HK.json rename to src/i18n/zh-HK.json diff --git a/messages/zh-TW.json b/src/i18n/zh-TW.json similarity index 100% rename from messages/zh-TW.json rename to src/i18n/zh-TW.json diff --git a/src/lib/actions.ts b/src/lib/actions.ts index 0f4c0f0..28b29ef 100644 --- a/src/lib/actions.ts +++ b/src/lib/actions.ts @@ -1,6 +1,9 @@ import { Message } from '@/components/ChatWindow'; -export const getSuggestions = async (chatHisory: Message[]) => { +export const getSuggestions = async ( + chatHistory: Message[], + locale?: string, +) => { const chatModel = localStorage.getItem('chatModel'); const chatModelProvider = localStorage.getItem('chatModelProvider'); @@ -13,7 +16,7 @@ export const getSuggestions = async (chatHisory: Message[]) => { 'Content-Type': 'application/json', }, body: JSON.stringify({ - chatHistory: chatHisory, + chatHistory: chatHistory, chatModel: { provider: chatModelProvider, model: chatModel, @@ -22,6 +25,7 @@ export const getSuggestions = async (chatHisory: Message[]) => { customOpenAIBaseURL, }), }, + locale, }), }); diff --git a/src/lib/chains/suggestionGeneratorAgent.ts b/src/lib/chains/suggestionGeneratorAgent.ts index 9129059..8a78c5d 100644 --- a/src/lib/chains/suggestionGeneratorAgent.ts +++ b/src/lib/chains/suggestionGeneratorAgent.ts @@ -5,14 +5,30 @@ import formatChatHistoryAsString from '../utils/formatHistory'; import { BaseMessage } from '@langchain/core/messages'; import { BaseChatModel } from '@langchain/core/language_models/chat_models'; import { ChatOpenAI } from '@langchain/openai'; +import { getPromptLanguageName } from '@/i18n/locales'; const suggestionGeneratorPrompt = ` -You are an AI suggestion generator for an AI powered search engine. You will be given a conversation below. You need to generate 4-5 suggestions based on the conversation. The suggestion should be relevant to the conversation that can be used by the user to ask the chat model for more information. -You need to make sure the suggestions are relevant to the conversation and are helpful to the user. Keep a note that the user might use these suggestions to ask a chat model for more information. -Make sure the suggestions are medium in length and are informative and relevant to the conversation. +You are an AI suggestion generator for an AI powered search engine. -Provide these suggestions separated by newlines between the XML tags and . For example: +Your need to meet these requirements: +- You will be given a conversation below. You need to generate 4-5 suggestions based on the conversation. +- The suggestion should be relevant to the conversation that can be used by the user to ask the chat model for more information. +- You need to make sure the suggestions are relevant to the conversation and are helpful to the user. Keep a note that the user might use these suggestions to ask a chat model for more information. +### Language Instructions +- **Language Definition**: Interpret "{language}" as a combination of language and optional region. + - Format: "language (region)" or "language(region)" (e.g., "English (US)", "繁體中文(台灣)"). + - The main language indicates the linguistic system (e.g., English, 繁體中文, 日本語). + - The region in parentheses indicates the regional variant or locale style (e.g., US, UK, 台灣, 香港, France). +- **Primary Language**: Use "{language}" for all non-code content, including explanations, descriptions, and examples. +- **Regional Variants**: Adjust word choice, spelling, and style according to the region specified in "{language}" (e.g., 繁體中文(台灣)使用「伺服器」, 简体中文使用「服务器」; English (US) uses "color", English (UK) uses "colour"). +- **Code and Comments**: All code blocks and code comments must be entirely in "English (US)". +- **Technical Terms**: Technical terms, product names, and programming keywords should remain in their original form (do not translate). +- **Fallback Rule**: If a concept cannot be clearly expressed in "{language}", provide the explanation in "{language}" first, followed by the original term (in its source language) in parentheses for clarity. + +### Formatting Instructions +- Make sure the suggestions are medium in length and are informative and relevant to the conversation. +- Provide these suggestions separated by newlines between the XML tags and . For example: Tell me more about SpaceX and their recent projects What is the latest news on SpaceX? @@ -25,6 +41,7 @@ Conversation: type SuggestionGeneratorInput = { chat_history: BaseMessage[]; + locale: string; }; const outputParser = new ListLineOutputParser({ @@ -36,6 +53,8 @@ const createSuggestionGeneratorChain = (llm: BaseChatModel) => { RunnableMap.from({ chat_history: (input: SuggestionGeneratorInput) => formatChatHistoryAsString(input.chat_history), + language: (input: SuggestionGeneratorInput) => + getPromptLanguageName(input.locale), }), PromptTemplate.fromTemplate(suggestionGeneratorPrompt), llm, diff --git a/src/lib/prompts/academicSearch.ts b/src/lib/prompts/academicSearch.ts index d015910..3d609dd 100644 --- a/src/lib/prompts/academicSearch.ts +++ b/src/lib/prompts/academicSearch.ts @@ -20,50 +20,61 @@ Rephrased question: `; export const academicSearchResponsePrompt = ` - You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. +You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. - Your task is to provide answers that are: - - **Informative and relevant**: Thoroughly address the user's query using the given context. - - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. - - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. - - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. - - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. +Your task is to provide answers that are: +- **Informative and relevant**: Thoroughly address the user's query using the given context. +- **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. +- **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. +- **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. +- **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. - ### Formatting Instructions - - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. - - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. - - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. - - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. - - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. - - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. +### Formatting Instructions +- **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. +- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. +- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. +- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. +- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. +- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. - ### Citation Requirements - - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. - - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." - - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. - - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." - - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. - - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. +### Citation Requirements +- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. +- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." +- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. +- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." +- Always prioritize credibility and accuracy by linking all statements back to their respective context sources. +- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. - ### Special Instructions - - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. - - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. - - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. - - You are set on focus mode 'Academic', this means you will be searching for academic papers and articles on the web. - - ### User instructions - These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. - {systemInstructions} +### Special Instructions +- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. +- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. +- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. +- You are set on focus mode 'Academic', this means you will be searching for academic papers and articles on the web. - ### Example Output - - Begin with a brief introduction summarizing the event or query topic. - - Follow with detailed sections under clear headings, covering all aspects of the query if possible. - - Provide explanations or historical context as needed to enhance understanding. - - End with a conclusion or overall perspective if relevant. +### User instructions +These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. +{systemInstructions} - - {context} - +### Language Instructions +- **Language Definition**: Interpret "{language}" as a combination of language and optional region. + - Format: "language (region)" or "language(region)" (e.g., "English (US)", "繁體中文(台灣)"). + - The main language indicates the linguistic system (e.g., English, 繁體中文, 日本語). + - The region in parentheses indicates the regional variant or locale style (e.g., US, UK, 台灣, 香港, France). +- **Primary Language**: Use "{language}" for all non-code content, including explanations, descriptions, and examples. +- **Regional Variants**: Adjust word choice, spelling, and style according to the region specified in "{language}" (e.g., 繁體中文(台灣)使用「伺服器」, 简体中文使用「服务器」; English (US) uses "color", English (UK) uses "colour"). +- **Code and Comments**: All code blocks and code comments must be entirely in "English (US)". +- **Technical Terms**: Technical terms, product names, and programming keywords should remain in their original form (do not translate). +- **Fallback Rule**: If a concept cannot be clearly expressed in "{language}", provide the explanation in "{language}" first, followed by the original term (in its source language) in parentheses for clarity. - Current date & time in ISO format (UTC timezone) is: {date}. +### Example Output +- Begin with a brief introduction summarizing the event or query topic. +- Follow with detailed sections under clear headings, covering all aspects of the query if possible. +- Provide explanations or historical context as needed to enhance understanding. +- End with a conclusion or overall perspective if relevant. + + +{context} + + +Current date & time in ISO format (UTC timezone) is: {date}. `; diff --git a/src/lib/prompts/redditSearch.ts b/src/lib/prompts/redditSearch.ts index 577fa82..6c2d2c5 100644 --- a/src/lib/prompts/redditSearch.ts +++ b/src/lib/prompts/redditSearch.ts @@ -20,50 +20,61 @@ Rephrased question: `; export const redditSearchResponsePrompt = ` - You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. +You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. - Your task is to provide answers that are: - - **Informative and relevant**: Thoroughly address the user's query using the given context. - - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. - - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. - - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. - - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. +Your task is to provide answers that are: +- **Informative and relevant**: Thoroughly address the user's query using the given context. +- **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. +- **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. +- **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. +- **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. - ### Formatting Instructions - - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. - - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. - - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. - - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. - - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. - - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. +### Formatting Instructions +- **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. +- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. +- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. +- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. +- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. +- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. - ### Citation Requirements - - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. - - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." - - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. - - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." - - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. - - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. +### Citation Requirements +- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. +- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." +- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. +- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." +- Always prioritize credibility and accuracy by linking all statements back to their respective context sources. +- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. - ### Special Instructions - - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. - - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. - - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. - - You are set on focus mode 'Reddit', this means you will be searching for information, opinions and discussions on the web using Reddit. - - ### User instructions - These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. - {systemInstructions} +### Special Instructions +- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. +- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. +- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. +- You are set on focus mode 'Reddit', this means you will be searching for information, opinions and discussions on the web using Reddit. - ### Example Output - - Begin with a brief introduction summarizing the event or query topic. - - Follow with detailed sections under clear headings, covering all aspects of the query if possible. - - Provide explanations or historical context as needed to enhance understanding. - - End with a conclusion or overall perspective if relevant. +### User instructions +These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. +{systemInstructions} - - {context} - +### Language Instructions +- **Language Definition**: Interpret "{language}" as a combination of language and optional region. + - Format: "language (region)" or "language(region)" (e.g., "English (US)", "繁體中文(台灣)"). + - The main language indicates the linguistic system (e.g., English, 繁體中文, 日本語). + - The region in parentheses indicates the regional variant or locale style (e.g., US, UK, 台灣, 香港, France). +- **Primary Language**: Use "{language}" for all non-code content, including explanations, descriptions, and examples. +- **Regional Variants**: Adjust word choice, spelling, and style according to the region specified in "{language}" (e.g., 繁體中文(台灣)使用「伺服器」, 简体中文使用「服务器」; English (US) uses "color", English (UK) uses "colour"). +- **Code and Comments**: All code blocks and code comments must be entirely in "English (US)". +- **Technical Terms**: Technical terms, product names, and programming keywords should remain in their original form (do not translate). +- **Fallback Rule**: If a concept cannot be clearly expressed in "{language}", provide the explanation in "{language}" first, followed by the original term (in its source language) in parentheses for clarity. - Current date & time in ISO format (UTC timezone) is: {date}. +### Example Output +- Begin with a brief introduction summarizing the event or query topic. +- Follow with detailed sections under clear headings, covering all aspects of the query if possible. +- Provide explanations or historical context as needed to enhance understanding. +- End with a conclusion or overall perspective if relevant. + + +{context} + + +Current date & time in ISO format (UTC timezone) is: {date}. `; diff --git a/src/lib/prompts/webSearch.ts b/src/lib/prompts/webSearch.ts index 1a431ea..18035f0 100644 --- a/src/lib/prompts/webSearch.ts +++ b/src/lib/prompts/webSearch.ts @@ -62,49 +62,60 @@ Rephrased question: `; export const webSearchResponsePrompt = ` - You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. +You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. - Your task is to provide answers that are: - - **Informative and relevant**: Thoroughly address the user's query using the given context. - - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. - - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. - - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. - - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. +Your task is to provide answers that are: +- **Informative and relevant**: Thoroughly address the user's query using the given context. +- **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. +- **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. +- **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. +- **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. - ### Formatting Instructions - - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. - - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. - - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. - - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. - - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. - - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. +### Formatting Instructions +- **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. +- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. +- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. +- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. +- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. +- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. - ### Citation Requirements - - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. - - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." - - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. - - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." - - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. - - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. +### Citation Requirements +- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. +- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." +- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. +- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." +- Always prioritize credibility and accuracy by linking all statements back to their respective context sources. +- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. - ### Special Instructions - - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. - - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. - - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. +### Special Instructions +- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. +- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. +- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. - ### User instructions - These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. - {systemInstructions} +### User instructions +These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. +{systemInstructions} - ### Example Output - - Begin with a brief introduction summarizing the event or query topic. - - Follow with detailed sections under clear headings, covering all aspects of the query if possible. - - Provide explanations or historical context as needed to enhance understanding. - - End with a conclusion or overall perspective if relevant. +### Language Instructions +- **Language Definition**: Interpret "{language}" as a combination of language and optional region. + - Format: "language (region)" or "language(region)" (e.g., "English (US)", "繁體中文(台灣)"). + - The main language indicates the linguistic system (e.g., English, 繁體中文, 日本語). + - The region in parentheses indicates the regional variant or locale style (e.g., US, UK, 台灣, 香港, France). +- **Primary Language**: Use "{language}" for all non-code content, including explanations, descriptions, and examples. +- **Regional Variants**: Adjust word choice, spelling, and style according to the region specified in "{language}" (e.g., 繁體中文(台灣)使用「伺服器」, 简体中文使用「服务器」; English (US) uses "color", English (UK) uses "colour"). +- **Code and Comments**: All code blocks and code comments must be entirely in "English (US)". +- **Technical Terms**: Technical terms, product names, and programming keywords should remain in their original form (do not translate). +- **Fallback Rule**: If a concept cannot be clearly expressed in "{language}", provide the explanation in "{language}" first, followed by the original term (in its source language) in parentheses for clarity. - - {context} - +### Example Output +- Begin with a brief introduction summarizing the event or query topic. +- Follow with detailed sections under clear headings, covering all aspects of the query if possible. +- Provide explanations or historical context as needed to enhance understanding. +- End with a conclusion or overall perspective if relevant. - Current date & time in ISO format (UTC timezone) is: {date}. + +{context} + + +Current date & time in ISO format (UTC timezone) is: {date}. `; diff --git a/src/lib/prompts/wolframAlpha.ts b/src/lib/prompts/wolframAlpha.ts index 63145dd..fac2a0c 100644 --- a/src/lib/prompts/wolframAlpha.ts +++ b/src/lib/prompts/wolframAlpha.ts @@ -20,50 +20,61 @@ Rephrased question: `; export const wolframAlphaSearchResponsePrompt = ` - You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. +You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. - Your task is to provide answers that are: - - **Informative and relevant**: Thoroughly address the user's query using the given context. - - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. - - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. - - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. - - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. +Your task is to provide answers that are: +- **Informative and relevant**: Thoroughly address the user's query using the given context. +- **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. +- **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. +- **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. +- **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. - ### Formatting Instructions - - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. - - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. - - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. - - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. - - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. - - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. +### Formatting Instructions +- **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. +- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. +- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. +- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. +- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. +- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. - ### Citation Requirements - - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. - - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." - - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. - - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." - - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. - - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. +### Citation Requirements +- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. +- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." +- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. +- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." +- Always prioritize credibility and accuracy by linking all statements back to their respective context sources. +- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. - ### Special Instructions - - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. - - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. - - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. - - You are set on focus mode 'Wolfram Alpha', this means you will be searching for information on the web using Wolfram Alpha. It is a computational knowledge engine that can answer factual queries and perform computations. - - ### User instructions - These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. - {systemInstructions} +### Special Instructions +- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. +- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. +- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. +- You are set on focus mode 'Wolfram Alpha', this means you will be searching for information on the web using Wolfram Alpha. It is a computational knowledge engine that can answer factual queries and perform computations. - ### Example Output - - Begin with a brief introduction summarizing the event or query topic. - - Follow with detailed sections under clear headings, covering all aspects of the query if possible. - - Provide explanations or historical context as needed to enhance understanding. - - End with a conclusion or overall perspective if relevant. +### User instructions +These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. +{systemInstructions} - - {context} - +### Language Instructions +- **Language Definition**: Interpret "{language}" as a combination of language and optional region. + - Format: "language (region)" or "language(region)" (e.g., "English (US)", "繁體中文(台灣)"). + - The main language indicates the linguistic system (e.g., English, 繁體中文, 日本語). + - The region in parentheses indicates the regional variant or locale style (e.g., US, UK, 台灣, 香港, France). +- **Primary Language**: Use "{language}" for all non-code content, including explanations, descriptions, and examples. +- **Regional Variants**: Adjust word choice, spelling, and style according to the region specified in "{language}" (e.g., 繁體中文(台灣)使用「伺服器」, 简体中文使用「服务器」; English (US) uses "color", English (UK) uses "colour"). +- **Code and Comments**: All code blocks and code comments must be entirely in "English (US)". +- **Technical Terms**: Technical terms, product names, and programming keywords should remain in their original form (do not translate). +- **Fallback Rule**: If a concept cannot be clearly expressed in "{language}", provide the explanation in "{language}" first, followed by the original term (in its source language) in parentheses for clarity. - Current date & time in ISO format (UTC timezone) is: {date}. +### Example Output +- Begin with a brief introduction summarizing the event or query topic. +- Follow with detailed sections under clear headings, covering all aspects of the query if possible. +- Provide explanations or historical context as needed to enhance understanding. +- End with a conclusion or overall perspective if relevant. + + +{context} + + +Current date & time in ISO format (UTC timezone) is: {date}. `; diff --git a/src/lib/prompts/writingAssistant.ts b/src/lib/prompts/writingAssistant.ts index 565827a..af097d3 100644 --- a/src/lib/prompts/writingAssistant.ts +++ b/src/lib/prompts/writingAssistant.ts @@ -11,6 +11,17 @@ However you do not need to cite it using the same number. You can use different These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. {systemInstructions} +### Language Instructions +- **Language Definition**: Interpret "{language}" as a combination of language and optional region. + - Format: "language (region)" or "language(region)" (e.g., "English (US)", "繁體中文(台灣)"). + - The main language indicates the linguistic system (e.g., English, 繁體中文, 日本語). + - The region in parentheses indicates the regional variant or locale style (e.g., US, UK, 台灣, 香港, France). +- **Primary Language**: Use "{language}" for all non-code content, including explanations, descriptions, and examples. +- **Regional Variants**: Adjust word choice, spelling, and style according to the region specified in "{language}" (e.g., 繁體中文(台灣)使用「伺服器」, 简体中文使用「服务器」; English (US) uses "color", English (UK) uses "colour"). +- **Code and Comments**: All code blocks and code comments must be entirely in "English (US)". +- **Technical Terms**: Technical terms, product names, and programming keywords should remain in their original form (do not translate). +- **Fallback Rule**: If a concept cannot be clearly expressed in "{language}", provide the explanation in "{language}" first, followed by the original term (in its source language) in parentheses for clarity. + {context} diff --git a/src/lib/prompts/youtubeSearch.ts b/src/lib/prompts/youtubeSearch.ts index 9898016..1fcccca 100644 --- a/src/lib/prompts/youtubeSearch.ts +++ b/src/lib/prompts/youtubeSearch.ts @@ -20,50 +20,61 @@ Rephrased question: `; export const youtubeSearchResponsePrompt = ` - You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. +You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. - Your task is to provide answers that are: - - **Informative and relevant**: Thoroughly address the user's query using the given context. - - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. - - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. - - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. - - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. +Your task is to provide answers that are: +- **Informative and relevant**: Thoroughly address the user's query using the given context. +- **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. +- **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. +- **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. +- **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. - ### Formatting Instructions - - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. - - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. - - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. - - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. - - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. - - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. +### Formatting Instructions +- **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. +- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. +- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. +- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. +- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. +- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. - ### Citation Requirements - - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. - - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." - - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. - - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." - - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. - - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. +### Citation Requirements +- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. +- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." +- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. +- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." +- Always prioritize credibility and accuracy by linking all statements back to their respective context sources. +- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. - ### Special Instructions - - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. - - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. - - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. - - You are set on focus mode 'Youtube', this means you will be searching for videos on the web using Youtube and providing information based on the video's transcrip - - ### User instructions - These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. - {systemInstructions} +### Special Instructions +- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. +- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. +- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. +- You are set on focus mode 'Youtube', this means you will be searching for videos on the web using Youtube and providing information based on the video's transcrip - ### Example Output - - Begin with a brief introduction summarizing the event or query topic. - - Follow with detailed sections under clear headings, covering all aspects of the query if possible. - - Provide explanations or historical context as needed to enhance understanding. - - End with a conclusion or overall perspective if relevant. +### User Instructions +These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines. +{systemInstructions} - - {context} - +### Language Instructions +- **Language Definition**: Interpret "{language}" as a combination of language and optional region. + - Format: "language (region)" or "language(region)" (e.g., "English (US)", "繁體中文(台灣)"). + - The main language indicates the linguistic system (e.g., English, 繁體中文, 日本語). + - The region in parentheses indicates the regional variant or locale style (e.g., US, UK, 台灣, 香港, France). +- **Primary Language**: Use "{language}" for all non-code content, including explanations, descriptions, and examples. +- **Regional Variants**: Adjust word choice, spelling, and style according to the region specified in "{language}" (e.g., 繁體中文(台灣)使用「伺服器」, 简体中文使用「服务器」; English (US) uses "color", English (UK) uses "colour"). +- **Code and Comments**: All code blocks and code comments must be entirely in "English (US)". +- **Technical Terms**: Technical terms, product names, and programming keywords should remain in their original form (do not translate). +- **Fallback Rule**: If a concept cannot be clearly expressed in "{language}", provide the explanation in "{language}" first, followed by the original term (in its source language) in parentheses for clarity. - Current date & time in ISO format (UTC timezone) is: {date}. +### Example Output +- Begin with a brief introduction summarizing the event or query topic. +- Follow with detailed sections under clear headings, covering all aspects of the query if possible. +- Provide explanations or historical context as needed to enhance understanding. +- End with a conclusion or overall perspective if relevant. + + +{context} + + +Current date & time in ISO format (UTC timezone) is: {date}. `; diff --git a/src/lib/search/metaSearchAgent.ts b/src/lib/search/metaSearchAgent.ts index 070e562..5901ea1 100644 --- a/src/lib/search/metaSearchAgent.ts +++ b/src/lib/search/metaSearchAgent.ts @@ -25,6 +25,7 @@ import computeSimilarity from '../utils/computeSimilarity'; import formatChatHistoryAsString from '../utils/formatHistory'; import eventEmitter from 'events'; import { StreamEvent } from '@langchain/core/tracers/log_stream'; +import { getPromptLanguageName } from '@/i18n/locales'; export interface MetaSearchAgentType { searchAndAnswer: ( @@ -35,6 +36,7 @@ export interface MetaSearchAgentType { optimizationMode: 'speed' | 'balanced' | 'quality', fileIds: string[], systemInstructions: string, + locale: string, ) => Promise; } @@ -241,10 +243,12 @@ class MetaSearchAgent implements MetaSearchAgentType { embeddings: Embeddings, optimizationMode: 'speed' | 'balanced' | 'quality', systemInstructions: string, + language: string, ) { return RunnableSequence.from([ RunnableMap.from({ systemInstructions: () => systemInstructions, + language: () => language, query: (input: BasicChainInput) => input.query, chat_history: (input: BasicChainInput) => input.chat_history, date: () => new Date().toISOString(), @@ -475,6 +479,7 @@ class MetaSearchAgent implements MetaSearchAgentType { optimizationMode: 'speed' | 'balanced' | 'quality', fileIds: string[], systemInstructions: string, + locale: string, ) { const emitter = new eventEmitter(); @@ -484,6 +489,7 @@ class MetaSearchAgent implements MetaSearchAgentType { embeddings, optimizationMode, systemInstructions, + getPromptLanguageName(locale), ); const stream = answeringChain.streamEvents(