### Server Actions - Custom Instructions Source: https://context7.com/zaidmukaddam/scira/llms.txt Manages user-defined custom instructions, allowing for retrieval, saving, and deletion of personalized instructions that guide the AI's responses. ```APIDOC ## Server Actions - Custom Instructions ### Description Provides functionality to manage custom instructions for users, including fetching, saving, and deleting them. ### Method Various (functions) ### Endpoints - `getCustomInstructions()` - `saveCustomInstructions(content)` - `deleteCustomInstructionsAction()` ### Parameters #### `getCustomInstructions` - None. #### `saveCustomInstructions` - **content** (string) - Required - The content of the custom instructions. #### `deleteCustomInstructionsAction` - None. ### Response #### `getCustomInstructions` Success Response - **instructions** (object) - Custom instructions object with `userId` and `content`. #### `saveCustomInstructions` Success Response - **result** (object) - Confirmation object with `success` (boolean) and `data`. #### `deleteCustomInstructionsAction` Success Response - **result** (object) - Confirmation object with `success` (boolean). ``` -------------------------------- ### Custom Instructions Management Server Actions (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Manages user-defined custom instructions that guide the AI's responses. This includes fetching existing instructions, saving new or updated instructions, and deleting them entirely. Custom instructions allow users to personalize the AI's tone, style, or provide specific context for all interactions. ```typescript import { getCustomInstructions, saveCustomInstructions, deleteCustomInstructionsAction } from '@/app/actions'; // Get user's custom instructions const instructions = await getCustomInstructions(); // { userId: "user-uuid", content: "Always respond in a formal tone...", ... } // Save or update custom instructions const result = await saveCustomInstructions( "Always respond in a formal tone and provide detailed technical explanations." ); // { success: true, data: { ... } } // Delete custom instructions await deleteCustomInstructionsAction(); // { success: true } ``` -------------------------------- ### Server Actions - User Management and Authentication Source: https://context7.com/zaidmukaddam/scira/llms.txt Provides functionalities for retrieving user information, performing fast authentication checks, getting message counts, and verifying Pro user status. ```APIDOC ## Server Actions - User Management and Authentication ### Description Handles user data retrieval, authentication checks, message counts, and Pro user status verification. ### Method Various (functions) ### Endpoints - `getCurrentUser()` - `getLightweightUser()` - `getUserMessageCount()` - `getProUserStatusOnly()` ### Parameters None for these endpoints. ### Response #### `getCurrentUser` Success Response - **user** (object) - Full user data including `id`, `name`, `email`, `isProUser`, `proSource`, `polarSubscription`, and `dodoPayments`. #### `getLightweightUser` Success Response - **lightweightUser** (object) - Lightweight user data including `userId` and `isProUser`. #### `getUserMessageCount` Success Response - **count** (number) - The user's current message count. - **error** (string) - Error message if retrieval fails. #### `getProUserStatusOnly` Success Response - **isProUser** (boolean) - True if the user is a Pro user, false otherwise. ``` -------------------------------- ### Google Drive Connector Actions (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Manages Google Drive connections within the application. Includes actions for creating, listing, deleting, and syncing user connectors. Requires authentication to set up connections. ```typescript import { createConnectorAction, listUserConnectorsAction, deleteConnectorAction, manualSyncConnectorAction, getConnectorSyncStatusAction } from '@/app/actions'; // Create a new Google Drive connection const { success, authLink } = await createConnectorAction('google-drive'); // authLink: "https://supermemory.ai/oauth/google-drive?userId=..." // Redirect user to authLink to complete OAuth flow // List user's connected services const { success, connections } = await listUserConnectorsAction(); // connections: [{ // id: "conn-uuid", // provider: "google-drive", // status: "connected", // lastSyncAt: "2025-12-09T10:00:00Z" // }] // Manually trigger sync await manualSyncConnectorAction('google-drive'); // Check sync status const { status } = await getConnectorSyncStatusAction('google-drive'); // status: { syncing: true, progress: 45, total: 100 } // Delete connection await deleteConnectorAction('conn-uuid'); ``` -------------------------------- ### User Management and Authentication Server Actions (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Enables server-side management of user data and authentication status. Functions allow fetching comprehensive user profiles including Pro subscription details, performing lightweight authentication checks, retrieving daily message counts, and directly querying Pro user status. Useful for access control and personalization. ```typescript import { getCurrentUser, getLightweightUser, getUserMessageCount, getProUserStatusOnly } from '@/app/actions'; // Get full user data with Pro status and subscription info const user = await getCurrentUser(); // { // id: "user-uuid", // name: "John Doe", // email: "john@example.com", // isProUser: true, // proSource: "polar", // or "dodo" // polarSubscription: { ... }, // dodoPayments: { expiresAt: "2025-12-31", ... } // } // Fast authentication check (lightweight) const lightweightUser = await getLightweightUser(); // { userId: "user-uuid", isProUser: true } // Get user's daily message count const { count, error } = await getUserMessageCount(); // count: 45 (out of 100 for free users) // Check Pro status only const isProUser = await getProUserStatusOnly(); // true or false ``` -------------------------------- ### Scheduled Searches (Lookouts) Management Server Actions (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Facilitates the creation, retrieval, and management of scheduled searches, referred to as 'lookouts'. Users can define lookouts with specific prompts, frequencies, times, and timezones. The actions support pausing, resuming, updating, deleting, and immediately testing these scheduled tasks. Provides detailed information on lookout status and schedules. ```typescript import { createScheduledLookout, getUserLookouts, updateLookoutStatusAction, updateLookoutAction, deleteLookoutAction, testLookoutAction } from '@/app/actions'; // Create a daily scheduled search const result = await createScheduledLookout({ title: "AI News Digest", prompt: "Latest developments in artificial intelligence", frequency: "daily", // "once", "daily", "weekly", "monthly", "yearly" time: "09:00", // HH:MM format timezone: "America/New_York", // For weekly: time: "09:00:1" (1 = Monday, 0 = Sunday) }); // Get all user's lookouts const { success, lookouts } = await getUserLookouts(); // lookouts: [{ // id: "lookout-uuid", // title: "AI News Digest", // prompt: "Latest developments...", // frequency: "daily", // status: "active", // nextRunAt: "2025-12-10T09:00:00Z", // lastRunAt: null, // cronSchedule: "CRON_TZ=America/New_York 0 9 * * *" // }] // Pause/resume a lookout await updateLookoutStatusAction({ id: "lookout-uuid", status: "paused" // "active", "paused", "archived" }); // Update lookout configuration await updateLookoutAction({ id: "lookout-uuid", title: "Updated Title", prompt: "Updated prompt", frequency: "weekly", time: "10:00", timezone: "America/Los_Angeles", dayOfWeek: "1" // Monday for weekly }); // Delete a lookout await deleteLookoutAction({ id: "lookout-uuid" }); // Test run a lookout immediately await testLookoutAction({ id: "lookout-uuid" }); ``` -------------------------------- ### Server Actions - Scheduled Searches (Lookouts) Source: https://context7.com/zaidmukaddam/scira/llms.txt Enables the creation, retrieval, updating, deletion, and testing of scheduled searches (Lookouts) for automated information gathering. ```APIDOC ## Server Actions - Scheduled Searches (Lookouts) ### Description Manages scheduled searches (Lookouts), allowing for creation, retrieval, updates, deletion, and immediate testing. ### Method Various (functions) ### Endpoints - `createScheduledLookout(lookoutDetails)` - `getUserLookouts()` - `updateLookoutStatusAction(lookoutIdAndStatus)` - `updateLookoutAction(lookoutUpdateDetails)` - `deleteLookoutAction(lookoutId)` - `testLookoutAction(lookoutId)` ### Parameters #### `createScheduledLookout` - **lookoutDetails** (object) - Required - Details for the scheduled lookout. - **title** (string) - Required - The title of the lookout. - **prompt** (string) - Required - The search prompt. - **frequency** (string) - Required - Frequency of the search (e.g., "daily", "weekly"). - **time** (string) - Required - Time for the search (HH:MM format). - **timezone** (string) - Required - Timezone for the search. - **dayOfWeek** (string) - Optional - Day of the week for weekly frequency. #### `getUserLookouts` - None. #### `updateLookoutStatusAction` - **lookoutIdAndStatus** (object) - Required - Contains lookout ID and new status. - **id** (string) - Required - The ID of the lookout. - **status** (string) - Required - New status (e.g., "active", "paused", "archived"). #### `updateLookoutAction` - **lookoutUpdateDetails** (object) - Required - Details to update. - **id** (string) - Required - The ID of the lookout. - **title** (string) - Optional - New title. - **prompt** (string) - Optional - New prompt. - **frequency** (string) - Optional - New frequency. - **time** (string) - Optional - New time. - **timezone** (string) - Optional - New timezone. - **dayOfWeek** (string) - Optional - New day of the week. #### `deleteLookoutAction` - **lookoutId** (object) - Required - Contains the lookout ID. - **id** (string) - Required - The ID of the lookout to delete. #### `testLookoutAction` - **lookoutId** (object) - Required - Contains the lookout ID. - **id** (string) - Required - The ID of the lookout to test. ### Response #### `createScheduledLookout` Success Response - **result** (object) - Confirmation of creation. #### `getUserLookouts` Success Response - **success** (boolean) - Indicates if the request was successful. - **lookouts** (array) - An array of lookout objects with details like `id`, `title`, `prompt`, `frequency`, `status`, `nextRunAt`, `lastRunAt`, `cronSchedule`. #### `updateLookoutStatusAction` Success Response - (void) #### `updateLookoutAction` Success Response - (void) #### `deleteLookoutAction` Success Response - (void) #### `testLookoutAction` Success Response - (void). ``` -------------------------------- ### POST /api/raycast/route for Raycast Extension Searches (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Initiates a search query via the Raycast extension API. It sends a POST request with a JSON payload containing the search query, model, and search provider. The response includes the search result and associated sources. Requires SCIRA_API_KEY for authorization. ```typescript const response = await fetch('/api/raycast', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${SCIRA_API_KEY}` }, body: JSON.stringify({ query: "What is quantum computing?", model: "scira-default", searchProvider: "parallel" }) }); const { result, sources } = await response.json(); // result: "Quantum computing is..." // sources: [{ title: "...", url: "...", content: "..." }] ``` -------------------------------- ### Web Search Tool Execution (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Performs multi-provider web searches with options for parallel execution and streaming results. Supports retrieving search results and images, with configurable parameters like max results and quality. ```typescript import { webSearchTool } from '@/lib/tools/web-search'; // Execute multi-query web search const tool = webSearchTool(dataStream, 'parallel'); // or 'exa', 'tavily', 'firecrawl' const result = await tool.execute({ queries: [ "latest AI developments 2025", "AI breakthrough research", "artificial intelligence news" ], maxResults: [15, 15, 20], // Per query topics: ['general', 'general', 'news'], quality: ['default', 'default', 'best'] }); // Result structure { searches: [ { query: "latest AI developments 2025", results: [ { url: "https://example.com/ai-news", title: "Major AI Breakthrough Announced", content: "Researchers have developed...", published_date: "2025-12-01", author: "Jane Doe" } // ... more results ], images: [ { url: "https://example.com/image.jpg", description: "AI visualization" } // ... more images ] } // ... more search queries ] } // Streaming updates via dataStream // type: 'data-query_completion' // data: { query, index, total, status: 'started' | 'completed' | 'error', resultsCount, imagesCount } ``` -------------------------------- ### Database Schema and Queries (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Manages core data models and query functions for chat and message persistence. It includes functions for saving, retrieving, and updating chat data and messages, interacting with a PostgreSQL database via Drizzle ORM. Dependencies include database connection utilities. ```typescript import { getChatById, saveChat, saveMessages, getChatsByUserId, deleteChatById, updateChatVisibilityById, updateChatTitleById } from '@/lib/db/queries'; // Create a new chat await saveChat({ id: "chat-uuid", userId: "user-uuid", title: "New Chat", visibility: "private" }); // Save messages to chat await saveMessages({ messages: [ { chatId: "chat-uuid", id: "msg-uuid", role: "user", parts: [{ type: "text", text: "Hello" }], attachments: [], createdAt: new Date(), model: "scira-default", inputTokens: 10, outputTokens: 50, totalTokens: 60, completionTime: 1.2 } ] }); // Get chat with messages const chat = await getChatById({ id: "chat-uuid" }); // { // id: "chat-uuid", // userId: "user-uuid", // title: "New Chat", // visibility: "private", // createdAt: Date, // updatedAt: Date, // messages: [...] // } // Get user's chats const { chats, hasMore } = await getChatsByUserId({ id: "user-uuid", limit: 20, startingAfter: null, endingBefore: null }); // Database schema (PostgreSQL with Drizzle ORM) // Tables: user, session, account, verification, chat, message, stream, // custom_instructions, lookout, usage_tracking, payment ``` -------------------------------- ### POST /api/lookout/route - Execute Scheduled Search Source: https://context7.com/zaidmukaddam/scira/llms.txt This internal endpoint is designed to be called by a QStash cron job to execute scheduled searches. It performs a search based on a provided lookout ID and prompt, and can create a new chat with the results, potentially sending an email notification. ```APIDOC ## POST /api/lookout/route ### Description Execute scheduled search (called by QStash cron). ### Method POST ### Endpoint /api/lookout/route ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication, validated via QStash signature. Example: `Bearer YOUR_CRON_SECRET` #### Request Body - **lookoutId** (string) - Required - The unique identifier for the scheduled search task. - **prompt** (string) - Required - The search query or prompt to execute. - **userId** (string) - Required - The ID of the user for whom the search is being performed. ### Request Example ```json { "lookoutId": "lookout-uuid", "prompt": "Latest AI news", "userId": "user-uuid" } ``` ### Response #### Success Response (200) Indicates the scheduled search was executed. The endpoint typically creates a new chat with the search results and may trigger an email notification. ``` -------------------------------- ### Extreme Search Tool Execution (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt An advanced autonomous research agent that performs multi-step research, planning, and execution. It integrates with other tools like web search and code runners, providing synthesized research, tool results, and source references. ```typescript import { extremeSearchTool } from '@/lib/tools/extreme-search'; // Execute deep research with autonomous agent const tool = extremeSearchTool(dataStream); const result = await tool.execute({ prompt: "Comprehensive analysis of quantum computing applications in cryptography" }); // Result structure { research: { text: "Detailed research synthesis by AI agent…", toolResults: [ { toolName: 'webSearch', result: [...] }, { toolName: 'xSearch', result: {...} }, { toolName: 'codeRunner', result: { result: "...", charts: [...] } } ], sources: [ { title: "Quantum Cryptography Research Paper", url: "https://arxiv.org/...", content: "Abstract and key findings…", publishedDate: "2025-11-15", favicon: "https://..." } // ... 20+ sources from multiple searches ], charts: [ { type: 'line', title: 'Quantum Computing Progress', elements: { x: [...], y: [...], labels: [...] } } ] } } // Streaming updates via dataStream // Plan phase: type: 'data-extreme_search', data: { kind: 'plan', status, plan } // Query phase: type: 'data-extreme_search', data: { kind: 'query', queryId, query, status } // Source phase: type: 'data-extreme_search', data: { kind: 'source', queryId, source } // Code phase: type: 'data-extreme_search', data: { kind: 'code', codeId, code, status, result, charts } // X Search: type: 'data-extreme_search', data: { kind: 'x_search', xSearchId, query, status, result } ``` -------------------------------- ### Execute Python Code and Generate Charts Source: https://context7.com/zaidmukaddam/scira/llms.txt The Code Interpreter Tool allows execution of Python code within a sandboxed Daytona environment. It supports libraries like matplotlib, pandas, and numpy for data analysis and visualization. The tool can return execution results, summary statistics, and automatically generated charts. ```typescript import { codeInterpreterTool } from '@/lib/tools/code-interpreter'; // Execute Python code with visualization const result = await codeInterpreterTool.execute({ title: "Stock Price Analysis", code: ` import yfinance as yf import matplotlib.pyplot as plt # Fetch Tesla stock data tsla = yf.Ticker("TSLA") hist = tsla.history(period="1mo") # Create visualization plt.figure(figsize=(10, 6)) plt.plot(hist.index, hist['Close'], label='TSLA Close Price') plt.xlabel('Date') plt.ylabel('Price (USD)') plt.title('Tesla Stock Price - Last Month') plt.legend() plt.grid(True) plt.show() # Print summary statistics print(f"Average Close: {hist['Close'].mean():.2f}") print(f"Max Close: {hist['Close'].max():.2f}") print(f"Min Close: {hist['Close'].min():.2f}") `, icon: "stock" // "stock", "date", "calculation", "default" }); // Result structure { message: "Average Close: 352.45\nMax Close: 389.23\nMin Close: 321.15", chart: { type: 'line', title: 'Tesla Stock Price - Last Month', elements: { x: ['2025-11-10', '2025-11-11', ...], y: [345.67, 352.34, ...], labels: ['TSLA Close Price'] } } } // Note: Charts are automatically detected and returned // Supported libraries: matplotlib, pandas, numpy, scipy, keras, seaborn, transformers, scikit-learn ``` -------------------------------- ### AI Model Management (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Handles AI model configuration and access control. It provides utilities to check authentication requirements, subscription tiers, model capabilities (vision, reasoning), and user eligibility for specific models. Dependencies include AI provider configurations. ```typescript import { scira, requiresAuthentication, requiresProSubscription, hasVisionSupport, hasReasoningSupport, getModelConfig, canUseModel } from '@/ai/providers'; // Get language model instance const model = scira.languageModel('scira-default'); // Check model requirements const needsAuth = requiresAuthentication('scira-grok-3'); // true - requires user authentication const needsPro = requiresProSubscription('scira-gpt5'); // true - requires Pro subscription const supportsVision = hasVisionSupport('scira-default'); // true - can process images const supportsReasoning = hasReasoningSupport('scira-grok-4-fast-think'); // true - has chain-of-thought reasoning // Check if user can access model const { canUse, reason } = canUseModel('scira-gpt5', user, isProUser); // { canUse: false, reason: 'pro_subscription_required' } // Available models include: // Free: scira-default (Grok 4 Fast), scira-qwen-32b, scira-nano // Free (Auth): scira-grok-3-mini, scira-gpt-4.1-nano, scira-google-lite // Pro: scira-grok-4, scira-gpt5, scira-google-pro, scira-anthropic (Claude), // scira-deepseek-r1, scira-qwen-coder, scira-cmd-a, and 40+ more ``` -------------------------------- ### Manage User Chats with Server Actions (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Provides functions to interact with user chat data on the server. This includes fetching chat history with pagination, deleting specific chats, updating their visibility and titles, and suggesting follow-up questions based on conversation context. These actions are crucial for building chat interfaces. ```typescript import { getUserChats, deleteChat, updateChatVisibility, updateChatTitle, suggestQuestions } from '@/app/actions'; // Get user's chat history with pagination const { chats, hasMore } = await getUserChats( userId, 20, // limit startingAfter, // cursor endingBefore ); // Delete a chat await deleteChat(chatId); // Update chat visibility await updateChatVisibility(chatId, 'public'); // Update chat title await updateChatTitle(chatId, 'New Chat Title'); // Generate follow-up questions const { questions } = await suggestQuestions([ { role: 'user', content: 'What is AI?' }, { role: 'assistant', content: 'AI stands for...' } ]); // questions: ["How does machine learning work?", "What are neural networks?", ...] ``` -------------------------------- ### Prompt Enhancement Action (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Enhances user-provided prompts using AI capabilities, likely for generating more detailed or specific queries. This feature may require a premium subscription. ```typescript import { enhancePrompt } from '@/app/actions'; // Enhance a user prompt (Pro feature) const result = await enhancePrompt("tell me about ai"); // { // success: true, // enhanced: "Provide a comprehensive overview of artificial intelligence, including its definition, key subfields (machine learning, deep learning, natural language processing), current state-of-the-art applications, and recent breakthroughs as of December 2025." // } ``` -------------------------------- ### POST /api/raycast/route Source: https://context7.com/zaidmukaddam/scira/llms.txt Raycast extension API endpoint for performing quick searches within the Scira platform. It allows users to query information using specified models and search providers. ```APIDOC ## POST /api/raycast/route ### Description Raycast extension API for quick searches. ### Method POST ### Endpoint /api/raycast/route ### Parameters #### Request Body - **query** (string) - Required - The search query. - **model** (string) - Optional - The model to use for the search (e.g., "scira-default"). - **searchProvider** (string) - Optional - The search provider to use (e.g., "parallel"). ### Request Example ```json { "query": "What is quantum computing?", "model": "scira-default", "searchProvider": "parallel" } ``` ### Response #### Success Response (200) - **result** (string) - The search result. - **sources** (array) - An array of source objects, each containing `title`, `url`, and `content`. ``` -------------------------------- ### Search YouTube Videos Source: https://context7.com/zaidmukaddam/scira/llms.txt The YouTube Search Tool facilitates searching for YouTube videos based on a given query. It returns a list of videos, each with comprehensive metadata such as URL, title, description, author, publication date, view count, and video duration. ```typescript import { youtubeSearchTool } from '@/lib/tools/youtube-search'; // Search YouTube videos const result = await youtubeSearchTool.execute({ query: "react server components tutorial" }); // Result structure { results: [ { url: "https://youtube.com/watch?v=abc123", title: "Complete Guide to React Server Components", content: "Learn how to use React Server Components...", publishedDate: "2025-11-20", author: "Tech Channel", views: "125000", duration: "15:42" } // ... more videos ] } ``` -------------------------------- ### Execute Scheduled Search (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt This internal endpoint is designed to be called by a QStash cron scheduler to execute a scheduled search. It requires a specific authorization header and accepts a lookout ID, prompt, and user ID. The function creates a new chat with search results and sends an email notification. ```typescript // Internal endpoint called by QStash scheduler const response = await fetch('/api/lookout', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${CRON_SECRET}` // Validated via QStash signature }, body: JSON.stringify({ lookoutId: "lookout-uuid", prompt: "Latest AI news", userId: "user-uuid" }) }); // Creates new chat with search results and sends email notification ``` -------------------------------- ### YouTube Search Tool Source: https://context7.com/zaidmukaddam/scira/llms.txt Searches for YouTube videos, returning results with detailed metadata including title, URL, description, publication date, author, views, and duration. ```APIDOC ## YouTube Search Tool ### Description Searches for YouTube videos and retrieves detailed metadata for each result. ### Method `execute` (via `youtubeSearchTool`) ### Parameters #### Request Body - **query** (string) - Required - The search term for YouTube videos. ### Request Example ```json { "query": "react server components tutorial" } ``` ### Response #### Success Response (200) - **results** (array of objects) - List of found YouTube videos. - **url** (string) - URL of the video. - **title** (string) - Title of the video. - **content** (string) - Description or snippet of the video. - **publishedDate** (string) - Publication date. - **author** (string) - Channel name. - **views** (string) - Number of views. - **duration** (string) - Video duration (e.g., '15:42'). #### Response Example ```json { "results": [ { "url": "https://youtube.com/watch?v=abc123", "title": "Complete Guide to React Server Components", "content": "Learn how to use React Server Components...", "publishedDate": "2025-11-20", "author": "Tech Channel", "views": "125000", "duration": "15:42" } ] } ``` ``` -------------------------------- ### POST /api/upload/route - File Upload for Analysis Source: https://context7.com/zaidmukaddam/scira/llms.txt Enables uploading images or PDF documents for vision and document analysis. The endpoint returns a URL and content type for the uploaded file, which can then be used in chat messages. ```APIDOC ## POST /api/upload/route ### Description Upload images or PDFs for vision/document analysis. ### Method POST ### Endpoint /api/upload/route ### Parameters #### Request Body - **file** (File) - Required - The image or PDF file to upload. This should be sent as multipart/form-data. ### Request Example ```javascript const formData = new FormData(); formData.append('file', fileBlob, 'document.pdf'); fetch('/api/upload/route', { method: 'POST', body: formData }); ``` ### Response #### Success Response (200) - **url** (string) - A URL pointing to the uploaded file (e.g., a blob URL). - **contentType** (string) - The MIME type of the uploaded file (e.g., "application/pdf"). #### Response Example ```json { "url": "blob:https://example.com/abc-123", "contentType": "application/pdf" } ``` ### Usage in Chat ```javascript const message = { role: "user", parts: [{ type: "text", text: "Analyze this document" }], experimental_attachments: [{ url, contentType, name: "document.pdf" }] }; ``` ``` -------------------------------- ### Code Interpreter Tool Source: https://context7.com/zaidmukaddam/scira/llms.txt Executes Python code in a sandboxed environment, capable of generating charts and performing data analysis. Supported libraries include matplotlib, pandas, numpy, scipy, keras, seaborn, transformers, and scikit-learn. ```APIDOC ## Code Interpreter Tool ### Description Executes Python code and generates visualizations. ### Method `execute` (via `codeInterpreterTool`) ### Parameters #### Request Body - **title** (string) - Required - The title for the execution. - **code** (string) - Required - The Python code to execute. - **icon** (string) - Optional - An identifier for the icon to associate with the execution (e.g., 'stock', 'date', 'calculation', 'default'). ### Request Example ```json { "title": "Stock Price Analysis", "code": "import yfinance as yf\nimport matplotlib.pyplot as plt\n\ntsla = yf.Ticker(\"TSLA\")\nhist = tsla.history(period=\"1mo\")\n\nplt.figure(figsize=(10, 6))\nplt.plot(hist.index, hist['Close'], label='TSLA Close Price')\nplt.xlabel('Date')\nplt.ylabel('Price (USD)')\nplt.title('Tesla Stock Price - Last Month')\nplt.legend()\nplt.grid(True)\nplt.show()\n\nprint(f\"Average Close: {hist['Close'].mean():.2f}\")\nprint(f\"Max Close: {hist['Close'].max():.2f}\")\nprint(f\"Min Close: {hist['Close'].min():.2f}\")", "icon": "stock" } ``` ### Response #### Success Response (200) - **message** (string) - The textual output from the code execution (e.g., summary statistics). - **chart** (object) - Contains chart data if a chart was generated. - **type** (string) - The type of chart (e.g., 'line'). - **title** (string) - The title of the chart. - **elements** (object) - The data points and labels for the chart. - **x** (array) - Array of x-axis values. - **y** (array) - Array of y-axis values. - **labels** (array) - Labels for the data series. #### Response Example ```json { "message": "Average Close: 352.45\nMax Close: 389.23\nMin Close: 321.15", "chart": { "type": "line", "title": "Tesla Stock Price - Last Month", "elements": { "x": ["2025-11-10", "2025-11-11", ...], "y": [345.67, 352.34, ...], "labels": ["TSLA Close Price"] } } } ``` ``` -------------------------------- ### Upload Files for Analysis (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt This endpoint handles the upload of files, such as images or PDFs, for subsequent vision or document analysis. It uses FormData to send the file and returns a JSON response containing the URL and content type of the uploaded file, which can then be used in chat messages. ```typescript const formData = new FormData(); formData.append('file', fileBlob, 'document.pdf'); const response = await fetch('/api/upload', { method: 'POST', body: formData }); const { url, contentType } = await response.json(); // url: "blob:https://example.com/abc-123" // contentType: "application/pdf" // Use uploaded file in chat message const message = { role: "user", parts: [{ type: "text", text: "Analyze this document" }], experimental_attachments: [{ url, contentType, name: "document.pdf" }] }; ``` -------------------------------- ### Server Actions - Search and Chat Management Source: https://context7.com/zaidmukaddam/scira/llms.txt Manages user chat history, allowing for retrieval, deletion, and updates to chat visibility and titles. Also supports suggesting follow-up questions based on conversation context. ```APIDOC ## Server Actions - Search and Chat Management ### Description Manages user chat history, including retrieval, deletion, and updates. Also provides functionality to suggest follow-up questions. ### Method Various (functions) ### Endpoints - `getUserChats(userId, limit, startingAfter, endingBefore)` - `deleteChat(chatId)` - `updateChatVisibility(chatId, visibility)` - `updateChatTitle(chatId, title)` - `suggestQuestions(conversationHistory)` ### Parameters #### `getUserChats` - **userId** (string) - Required - The ID of the user. - **limit** (number) - Optional - The maximum number of chats to return. - **startingAfter** (string) - Optional - Cursor for pagination, returns chats after this cursor. - **endingBefore** (string) - Optional - Cursor for pagination, returns chats before this cursor. #### `deleteChat` - **chatId** (string) - Required - The ID of the chat to delete. #### `updateChatVisibility` - **chatId** (string) - Required - The ID of the chat to update. - **visibility** (string) - Required - The new visibility status (e.g., "public"). #### `updateChatTitle` - **chatId** (string) - Required - The ID of the chat to update. - **title** (string) - Required - The new title for the chat. #### `suggestQuestions` - **conversationHistory** (array) - Required - An array of message objects, each with `role` and `content`. ### Response #### `getUserChats` Success Response - **chats** (array) - An array of chat objects. - **hasMore** (boolean) - Indicates if there are more chats available. #### `deleteChat` Success Response - (void) #### `updateChatVisibility` Success Response - (void) #### `updateChatTitle` Success Response - (void) #### `suggestQuestions` Success Response - **questions** (array) - An array of suggested questions. ``` -------------------------------- ### Speech Generation Action (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Converts input text into speech audio using the ElevenLabs API. The output is a base64 encoded MP3 string that can be directly used in an HTML audio element. ```typescript import { generateSpeech } from '@/app/actions'; // Convert text to speech using ElevenLabs const { audio } = await generateSpeech( "This is the text to be converted to speech." ); // audio: "data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAA..." // Use in audio element const audioElement = new Audio(audio); audioElement.play(); ``` -------------------------------- ### POST /api/search/route - Main Search Endpoint Source: https://context7.com/zaidmukaddam/scira/llms.txt This is the primary endpoint for initiating AI chat requests. It supports tool calling and provides streaming responses using Server-Sent Events. You can specify search modes, AI models, and search providers. ```APIDOC ## POST /api/search/route ### Description Main search endpoint that handles AI chat requests with tool calling and streaming responses. ### Method POST ### Endpoint /api/search/route ### Parameters #### Request Body - **messages** (array) - Required - An array of message objects representing the conversation history. Each message can contain text, attachments, and have a role (user/assistant). - **model** (string) - Required - The ID of the AI model to use (e.g., "scira-default", "scira-grok-4-fast"). - **group** (string) - Required - The search group or mode (e.g., "web", "academic", "youtube", "x", "reddit", "extreme", "chat", "memory", "connectors"). - **timezone** (string) - Required - The user's timezone (e.g., "America/New_York"). - **id** (string) - Required - A unique identifier for the chat session. - **selectedVisibilityType** (string) - Required - Visibility setting for the chat (e.g., "private", "public"). - **isCustomInstructionsEnabled** (boolean) - Required - Flag to enable custom instructions. - **searchProvider** (string) - Optional - The search provider to use (e.g., "parallel", "exa", "tavily", "firecrawl"). - **selectedConnectors** (array) - Optional - An array of connector IDs to use for the search (e.g., ["google-drive"]). ### Request Example ```json { "messages": [ { "id": "msg-uuid", "role": "user", "parts": [{ "type": "text", "text": "What are the latest AI developments?" }], "experimental_attachments": [] } ], "model": "scira-default", "group": "web", "timezone": "America/New_York", "id": "chat-uuid", "selectedVisibilityType": "private", "isCustomInstructionsEnabled": true, "searchProvider": "parallel", "selectedConnectors": ["google-drive"] } ``` ### Response #### Success Response (Streaming via Server-Sent Events) Responses are streamed as Server-Sent Events (SSE). Each event is prefixed with `0:` and contains a JSON payload. - **type** (string) - The type of message (e.g., "text-delta", "tool-call", "tool-result", "data-query_completion"). - **textDelta** (string) - For "text-delta" type, contains a chunk of the AI's response text. - **toolName** (string) - For "tool-call" type, the name of the tool being called. - **result** (object) - For "tool-result" type, the result of the tool execution. - **data** (any) - For "data-query_completion" type, provides status or data related to the query. #### Response Example (Metadata after stream ends) ```json { "model": "scira-default", "completionTime": 2.45, "totalTokens": 1523, "inputTokens": 243, "outputTokens": 1280 } ``` ``` -------------------------------- ### Perform AI Search and Stream Responses (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt The main search endpoint handles AI chat requests with tool calling and streaming responses using Server-Sent Events. It accepts messages, model, group, and search provider as input. The response is streamed in chunks with different message types like text-delta, tool-call, and tool-result. ```typescript const requestBody = { messages: [ { id: "msg-uuid", role: "user", parts: [{ type: "text", text: "What are the latest AI developments?" }], experimental_attachments: [] } ], model: "scira-default", // Model ID (e.g., scira-grok-4-fast) group: "web", // Search group: web, academic, youtube, x, reddit, extreme, chat, memory, connectors timezone: "America/New_York", id: "chat-uuid", selectedVisibilityType: "private", // or "public" isCustomInstructionsEnabled: true, searchProvider: "parallel", // or "exa", "tavily", "firecrawl" selectedConnectors: ["google-drive"] // Optional connector IDs }; fetch("/api/search", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(requestBody) }).then(response => { const reader = response.body.getReader(); const decoder = new TextDecoder(); reader.read().then(function processText({ done, value }) { if (done) return; const chunk = decoder.decode(value); const lines = chunk.split('\n'); lines.forEach(line => { if (line.startsWith('0:')) { const data = JSON.parse(line.slice(2)); // Handle different message types if (data.type === 'text-delta') { console.log('Text chunk:', data.textDelta); } else if (data.type === 'tool-call') { console.log('Tool called:', data.toolName); } else if (data.type === 'tool-result') { console.log('Tool result:', data.result); } else if (data.type === 'data-query_completion') { console.log('Query status:', data.data); } } }); return reader.read().then(processText); }); }); // Response includes metadata { model: "scira-default", completionTime: 2.45, // seconds totalTokens: 1523, inputTokens: 243, outputTokens: 1280 } ``` -------------------------------- ### Search X (Twitter) Posts with Filters Source: https://context7.com/zaidmukaddam/scira/llms.txt The X Search Tool enables searching for posts on X (formerly Twitter) with advanced filtering options including date ranges and specific user handles. It returns posts with details such as URL, title, content, author, handle, publication date, likes, and retweets. ```typescript import { xSearchTool } from '@/lib/tools/x-search'; // Search X posts const result = await xSearchTool.execute({ queries: [ "GPT-5 announcement", "AI startups funding", "machine learning trends" ], maxResults: [15, 15, 20], startDate: ['2025-11-01', '2025-11-01', '2025-10-01'], endDate: ['2025-12-09', '2025-12-09', '2025-12-09'], xHandles: [['openai', 'sama'], [], []] // Optional: specific handles per query }); // Result structure { searches: [ { query: "GPT-5 announcement", results: [ { url: "https://x.com/openai/status/123456789", title: "Post from @openai: We're excited to ann...", content: "We're excited to announce GPT-5...", author: "OpenAI", handle: "openai", publishedDate: "2025-12-01T10:30:00Z", likes: 45678, retweets: 12345 } // ... more posts ] } ] } ``` -------------------------------- ### Transcribe Audio Files (TypeScript) Source: https://context7.com/zaidmukaddam/scira/llms.txt Utilizes OpenAI Whisper to transcribe audio files into text. The endpoint accepts an audio file via FormData and returns a JSON response containing the transcribed text. This is useful for converting voice recordings or other audio content into readable text. ```typescript const formData = new FormData(); formData.append('file', audioBlob, 'recording.m4a'); const response = await fetch('/api/transcribe', { method: 'POST', body: formData }); const { text } = await response.json(); // text: "This is the transcribed audio content..." ```