### Install Dependencies (Bash) Source: https://github.com/openai/openai-responses-starter-app/blob/main/README.md Command to install project dependencies using npm. This is a crucial step after cloning a repository to ensure all required packages are available. ```bash npm install ``` -------------------------------- ### Run Development Server (Bash) Source: https://github.com/openai/openai-responses-starter-app/blob/main/README.md Command to start the development server for the NextJS application. This allows for local testing and development. ```bash npm run dev ``` -------------------------------- ### Example Custom Functions (TypeScript) Source: https://github.com/openai/openai-responses-starter-app/blob/main/README.md Illustrative example of custom functions that can be added to the application for use with the Responses API. These functions, like 'get_weather' and 'get_joke', demonstrate how to extend the assistant's capabilities. ```typescript export const functions = { get_weather: async (location: string) => { // Implementation to fetch weather data return `Weather in ${location}: sunny, 25°C`; }, get_joke: async () => { // Implementation to fetch a joke return "Why don't scientists trust atoms? Because they make up everything!"; }, }; ``` -------------------------------- ### Create Vector Store for File Search (TypeScript) Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Illustrates how to create a new vector store using the POST /api/vector_stores/create_store endpoint. This is essential for enabling the file search tool, allowing the AI to query uploaded documents. Includes request/response examples and client-side usage. ```typescript // POST /api/vector_stores/create_store // Request body: { "name": "My Documents" } // Response: OpenAI VectorStore object // curl example curl -X POST "http://localhost:3000/api/vector_stores/create_store" \ -H "Content-Type: application/json" \ -d '{"name": "Product Documentation"}' // Response: {"id":"vs_abc123","name":"Product Documentation","status":"completed",...} // Client-side usage const createVectorStore = async (name: string) => { const response = await fetch("/api/vector_stores/create_store", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) }); return response.json(); }; const store = await createVectorStore("Knowledge Base"); console.log(`Created store: ${store.id}`); ``` -------------------------------- ### GET /api/google/auth Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Initiates the Google OAuth 2.0 authentication flow using the Proof Key for Code Exchange (PKCE) method. This endpoint redirects the user to Google's consent screen. ```APIDOC ## GET /api/google/auth ### Description Initiates the Google OAuth 2.0 flow with PKCE for secure authentication, enabling Google Calendar and Gmail integration. ### Method GET ### Endpoint /api/google/auth ### Parameters None ### Behavior This endpoint redirects the user's browser to the Google OAuth consent page. It generates a code verifier and challenge for PKCE, storing them along with a state parameter in httpOnly cookies. The redirect includes requested scopes: openid, email, profile, Google Calendar events, and Gmail modify permissions. ### Environment Variables Required (.env.local) - **GOOGLE_CLIENT_ID**: Your Google OAuth client ID. - **GOOGLE_CLIENT_SECRET**: Your Google OAuth client secret. - **GOOGLE_REDIRECT_URI**: The callback URI registered with Google (e.g., "http://localhost:3000/api/google/callback"). ### Usage To start the OAuth flow, redirect the user's browser to this endpoint: ```javascript window.location.href = "/api/google/auth"; ``` ``` -------------------------------- ### GET /api/vector_stores/list_files Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Retrieves a list of all files currently associated with a specified vector store. ```APIDOC ## GET /api/vector_stores/list_files ### Description Retrieves all files associated with a specific vector store. ### Method GET ### Endpoint /api/vector_stores/list_files ### Parameters #### Query Parameters - **vector_store_id** (string) - Required - The ID of the vector store for which to list files. ### Response #### Success Response (200) - **data** (array) - An array of file objects associated with the vector store. - **id** (string) - The ID of the file. - **status** (string) - The status of the file within the vector store. #### Response Example ```json { "data": [ { "id": "file_xyz", "status": "completed" }, { "id": "file_uvw", "status": "processing" } ] } ``` ``` -------------------------------- ### Implement Get Weather Function (TypeScript) Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Details the 'get_weather' custom function, which fetches weather data using external APIs. It includes the API endpoint, example request/response formats, a curl example, and client-side wrapper code for easy integration within the assistant. ```typescript // GET /api/functions/get_weather?location=Paris&unit=celsius // Example response: { "temperature": 22 } // curl example curl "http://localhost:3000/api/functions/get_weather?location=San%20Francisco&unit=fahrenheit" // Response: {"temperature":65} // Client-side function wrapper (config/functions.ts) export const get_weather = async ({ location, unit }: { location: string; unit: string }) => { const res = await fetch(`/api/functions/get_weather?location=${location}&unit=${unit}`); return res.json(); }; // Usage in tool handling const result = await get_weather({ location: "Tokyo", unit: "celsius" }); console.log(`Temperature: ${result.temperature}°C`); ``` -------------------------------- ### GET /api/vector_stores/retrieve_store Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Fetches detailed information about a specific vector store, including its status and the number of files it contains. ```APIDOC ## GET /api/vector_stores/retrieve_store ### Description Fetches details about a specific vector store including its status and file counts. ### Method GET ### Endpoint /api/vector_stores/retrieve_store ### Parameters #### Query Parameters - **vector_store_id** (string) - Required - The ID of the vector store to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the vector store. - **name** (string) - The name of the vector store. - **status** (string) - The status of the vector store (e.g., "completed"). - **file_counts** (object) - An object detailing the counts of files in different states within the vector store. - **in_progress** (integer) - Number of files currently being processed. - **completed** (integer) - Number of files successfully processed. - **failed** (integer) - Number of files that failed processing. - **cancelled** (integer) - Number of files that were cancelled. #### Response Example ```json { "id": "vs_abc123", "name": "My Documents", "status": "completed", "file_counts": { "in_progress": 0, "completed": 5, "failed": 0, "cancelled": 0 } } ``` ``` -------------------------------- ### Implement Get Joke Function (TypeScript) Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Provides the implementation for the 'get_joke' custom function, which retrieves programming jokes from an external API. It includes the API endpoint, example request/response, a curl example, and client-side wrapper code. ```typescript // GET /api/functions/get_joke // Example response: { "joke": "Why do programmers prefer dark mode? - Because light attracts bugs!" } // curl example curl "http://localhost:3000/api/functions/get_joke" // Response: {"joke":"A SQL query walks into a bar, walks up to two tables and asks... 'Can I join you?'"} // Client-side function wrapper export const get_joke = async () => { const res = await fetch("/api/functions/get_joke"); return res.json(); }; // Adding to functions map for tool handling export const functionsMap = { get_weather: get_weather, get_joke: get_joke }; ``` -------------------------------- ### GET /api/functions/get_joke Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Fetches a random programming joke from JokeAPI. This function demonstrates adding custom, simple functions to the assistant. ```APIDOC ## GET /api/functions/get_joke ### Description A simple function that fetches programming jokes from JokeAPI, demonstrating how to add custom functions to the assistant. ### Method GET ### Endpoint /api/functions/get_joke ### Parameters None ### Request Example ```bash curl "http://localhost:3000/api/functions/get_joke" ``` ### Response #### Success Response (200) - **joke** (string) - A programming joke. #### Response Example ```json { "joke": "A SQL query walks into a bar, walks up to two tables and asks... 'Can I join you?'" } ``` ``` -------------------------------- ### GET /api/functions/get_weather Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Retrieves current weather data for a specified location using external APIs. Supports temperature units in Celsius or Fahrenheit. ```APIDOC ## GET /api/functions/get_weather ### Description A custom function that retrieves current weather data for any location using the Nominatim geocoding API and Open-Meteo weather API. ### Method GET ### Endpoint /api/functions/get_weather ### Parameters #### Query Parameters - **location** (string) - Required - The city or location for which to fetch the weather. - **unit** (string) - Required - The unit for temperature ('celsius' or 'fahrenheit'). ### Request Example ```bash curl "http://localhost:3000/api/functions/get_weather?location=San%20Francisco&unit=fahrenheit" ``` ### Response #### Success Response (200) - **temperature** (number) - The current temperature in the specified unit. #### Response Example ```json { "temperature": 65 } ``` ``` -------------------------------- ### Clone Repository (Bash) Source: https://github.com/openai/openai-responses-starter-app/blob/main/README.md Standard command to clone a Git repository from a remote URL. This is the first step in setting up the project locally. ```bash git clone https://github.com/openai/openai-responses-starter-app.git ``` -------------------------------- ### Handle Tool Calls and Custom Functions Source: https://context7.com/openai/openai-responses-starter-app/llms.txt This snippet illustrates how to handle tool calls by routing function calls to their implementations and returning results. It shows executing predefined tools like `get_weather` and `get_joke`, and demonstrates how to add custom functions to the `functionsMap` and `toolsList` configurations. ```typescript // lib/tools/tools-handling.ts import { handleTool } from "@/lib/tools/tools-handling"; import { functionsMap } from "@/config/functions"; // Execute a tool by name with parameters const weatherResult = await handleTool("get_weather", { location: "London", unit: "celsius" }); // Returns: { temperature: 18 } const jokeResult = await handleTool("get_joke", {}); // Returns: { joke: "Why do Java developers wear glasses? Because they can't C#!" } // Adding custom functions (config/functions.ts) export const my_custom_function = async ({ param1, param2 }: { param1: string; param2: number }) => { // Your implementation return { result: `Processed ${param1} with ${param2}` }; }; export const functionsMap = { get_weather, get_joke, my_custom_function // Add your function here }; // Also add to tools list (config/tools-list.ts) export const toolsList = [ // ... existing tools { name: "my_custom_function", description: "Description of what this function does", parameters: { param1: { type: "string", description: "First parameter" }, param2: { type: "number", description: "Second parameter" } } } ]; ``` -------------------------------- ### Manage Tool Configuration with Zustand Source: https://context7.com/openai/openai-responses-starter-app/llms.txt This snippet shows how to manage tool configurations using Zustand, with automatic persistence to localStorage. It allows enabling/disabling various AI capabilities like web search, file search, and code interpreter, and configuring associated settings. ```typescript // stores/useToolsStore.ts import useToolsStore from "@/stores/useToolsStore"; // Access and modify tool settings const { webSearchEnabled, setWebSearchEnabled, fileSearchEnabled, setFileSearchEnabled, functionsEnabled, setFunctionsEnabled, codeInterpreterEnabled, setCodeInterpreterEnabled, vectorStore, setVectorStore, webSearchConfig, setWebSearchConfig, mcpEnabled, setMcpEnabled, mcpConfig, setMcpConfig, googleIntegrationEnabled, setGoogleIntegrationEnabled } = useToolsStore(); // Enable web search with location setWebSearchEnabled(true); setWebSearchConfig({ user_location: { type: "approximate", country: "US", city: "New York", region: "NY" } }); // Configure MCP server setMcpEnabled(true); setMcpConfig({ server_label: "my-tools", server_url: "https://my-mcp-server.com/sse", allowed_tools: "search,fetch", skip_approval: false }); // State is automatically persisted to localStorage under "tools-store" ``` -------------------------------- ### Google Connector Tools Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Generates MCP-style connector tools for Google Calendar and Gmail integration. ```APIDOC ## getGoogleConnectorTools Function ### Description This function, located in `lib/tools/connectors.ts`, generates MCP (Multi-Connector Platform) compatible tool configurations for Google Calendar and Google Mail. It requires an access token for authentication and returns an empty array if no token is provided. ### Method (Function Call) ### Endpoint (N/A - Client-side or Server-side function) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body - **accessToken** (string) - Required - The OAuth access token for the authenticated Google user. ### Request Example ```typescript import { getGoogleConnectorTools } from "@/lib/tools/connectors"; // Assume getFreshAccessToken() retrieves the user's current access token const { accessToken } = await getFreshAccessToken(); if (accessToken) { const googleTools = getGoogleConnectorTools(accessToken); // Add googleTools to the main tools array for the Responses API } ``` ### Response #### Success Response (200) - **tools** (array) - An array of MCP tool configurations for Google Calendar and Gmail. #### Response Example ```json [ { "type": "mcp", "server_label": "GoogleCalendar", "server_description": "Search the user's calendar and read calendar events", "connector_id": "connector_googlecalendar", "authorization": "YOUR_ACCESS_TOKEN", "require_approval": "never" }, { "type": "mcp", "server_label": "GoogleMail", "server_description": "Search the user's email inbox and read emails", "connector_id": "connector_gmail", "authorization": "YOUR_ACCESS_TOKEN", "require_approval": "never" } ] ``` ``` -------------------------------- ### Google OAuth Callback Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Handles the OAuth callback from Google, exchanges the authorization code for tokens, and stores them securely. Redirects to the homepage upon success or failure. ```APIDOC ## GET /api/google/callback ### Description Handles the OAuth callback from Google, validates the state parameter, exchanges the authorization code for tokens using PKCE, and stores tokens securely in httpOnly cookies. Redirects to the homepage with a `connected=1` query parameter on success or an error parameter on failure. ### Method GET ### Endpoint /api/google/callback ### Query Parameters - **code** (string) - Required - The authorization code received from Google. - **state** (string) - Required - The state parameter used for CSRF protection. ### Response #### Redirect - On Success: Redirects to `/?connected=1`. - On Failure: Redirects to `/?error=...` with an appropriate error message. ### Request Example (This endpoint is typically called by Google, not directly by the user) ### Response Example (This endpoint performs a redirect, no direct JSON response) ``` -------------------------------- ### Configure Environment Variables for Google OAuth Source: https://github.com/openai/openai-responses-starter-app/blob/main/README.md This snippet shows how to configure environment variables required for Google OAuth authentication. It includes placeholders for your Google client ID, client secret, and redirect URI. Ensure these are set in your `.env.local` file for the application to connect to Google services. ```bash GOOGLE_CLIENT_ID="your-google-client-id" GOOGLE_CLIENT_SECRET="your-google-client-secret" GOOGLE_REDIRECT_URI="http://localhost:3000/api/google/callback" ``` -------------------------------- ### POST /api/vector_stores/create_store Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Creates a new vector store in OpenAI, which can then be used with the file search tool to enable searching through uploaded documents. ```APIDOC ## POST /api/vector_stores/create_store ### Description Creates a new vector store in OpenAI for use with the file search tool, allowing the assistant to search through uploaded documents. ### Method POST ### Endpoint /api/vector_stores/create_store ### Parameters #### Request Body - **name** (string) - Required - The desired name for the new vector store. ### Request Example ```json { "name": "Product Documentation" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created vector store. - **name** (string) - The name of the vector store. - **status** (string) - The current status of the vector store (e.g., 'completed'). - ... (Other OpenAI VectorStore object properties) #### Response Example ```json { "id": "vs_abc123", "name": "Product Documentation", "status": "completed" } ``` ``` -------------------------------- ### Initiate Google OAuth 2.0 Authentication Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Initiates the Google OAuth 2.0 authentication flow using PKCE. This process redirects the user to Google's consent page to grant access to their Google Calendar and Gmail. It requires environment variables for client ID, secret, and redirect URI. ```typescript // GET /api/google/auth // Redirects to Google OAuth consent page // To initiate OAuth flow, redirect user to this endpoint window.location.href = "/api/google/auth"; // The endpoint: // 1. Generates PKCE code verifier and challenge // 2. Stores state and verifier in httpOnly cookies // 3. Redirects to Google with scopes: // - openid, email, profile // - https://www.googleapis.com/auth/calendar.events // - https://www.googleapis.com/auth/gmail.modify // 4. User is redirected back to /api/google/callback after consent // Environment variables required (.env.local): // GOOGLE_CLIENT_ID="your-google-client-id" // GOOGLE_CLIENT_SECRET="your-google-client-secret" // GOOGLE_REDIRECT_URI="http://localhost:3000/api/google/callback" ``` -------------------------------- ### Handle Multi-Turn Conversations with Streaming Responses (TypeScript) Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Demonstrates the POST /api/turn_response endpoint for managing multi-turn conversations with the OpenAI Responses API. It shows how to send messages and tool configurations, and how to consume streaming responses client-side using the Fetch API and TextDecoder. ```typescript // POST /api/turn_response // Request body const requestBody = { messages: [ { role: "user", content: [{ type: "input_text", text: "What's the weather in Paris?" }] } ], toolsState: { webSearchEnabled: true, fileSearchEnabled: false, functionsEnabled: true, codeInterpreterEnabled: false, vectorStore: null, webSearchConfig: { user_location: { type: "approximate", country: "US" } }, mcpEnabled: false, mcpConfig: { server_label: "", server_url: "", allowed_tools: "", skip_approval: true }, googleIntegrationEnabled: false } }; // Client-side streaming consumption const response = await fetch("/api/turn_response", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(requestBody) }); const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value); const lines = buffer.split("\n\n"); buffer = lines.pop() || ""; for (const line of lines) { if (line.startsWith("data: ")) { const data = JSON.parse(line.slice(6)); // Handle events: response.output_text.delta, response.output_item.added, // response.function_call_arguments.delta, response.completed, etc. console.log(`Event: ${data.event}`, data.data); } } } ``` -------------------------------- ### getTools Function Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Dynamically builds the tools array for the OpenAI Responses API based on enabled features and configurations. ```APIDOC ## getTools Function ### Description This function, located in `lib/tools/tools.ts`, constructs the `tools` array required by the OpenAI Responses API. It dynamically includes tools like web search, file search, code interpreter, and custom functions based on the provided `ToolsState`. ### Method (Function Call) ### Endpoint (N/A - Client-side or Server-side function) ### Parameters #### Request Body - **toolsState** (ToolsState) - Required - An object defining the enabled features and their configurations. - `webSearchEnabled` (boolean) - `fileSearchEnabled` (boolean) - `functionsEnabled` (boolean) - `codeInterpreterEnabled` (boolean) - `vectorStore` (object) - Configuration for vector store search. - `webSearchConfig` (object) - Configuration for web search. - `mcpEnabled` (boolean) - `mcpConfig` (object) - Configuration for MCP (Multi-Connector Platform). - `googleIntegrationEnabled` (boolean) ### Request Example ```typescript import { getTools } from "@/lib/tools/tools"; import { ToolsState } from "@/stores/useToolsStore"; const toolsState: ToolsState = { webSearchEnabled: true, fileSearchEnabled: true, functionsEnabled: true, codeInterpreterEnabled: true, vectorStore: { id: "vs_abc123", name: "My Docs" }, webSearchConfig: { user_location: { type: "approximate", country: "US", city: "San Francisco", region: "CA" } }, mcpEnabled: true, mcpConfig: { server_label: "my-mcp-server", server_url: "https://mcp.example.com/sse", allowed_tools: "search,analyze", skip_approval: false }, googleIntegrationEnabled: true }; const tools = await getTools(toolsState); ``` ### Response #### Success Response (200) - **tools** (array) - An array of tool configurations compatible with the OpenAI Responses API. #### Response Example ```json [ { "type": "web_search", "user_location": { "type": "approximate", "country": "US", ... } }, { "type": "file_search", "vector_store_ids": ["vs_abc123"] }, { "type": "code_interpreter", "container": { "type": "auto" } }, { "type": "function", "name": "get_weather", "description": "...", "parameters": {...}, "strict": true }, { "type": "mcp", "server_label": "my-mcp-server", "server_url": "...", "allowed_tools": ["search", "analyze"] }, { "type": "mcp", "server_label": "GoogleCalendar", "connector_id": "connector_googlecalendar", ... }, { "type": "mcp", "server_label": "GoogleMail", "connector_id": "connector_gmail", ... } ] ``` ``` -------------------------------- ### POST /api/vector_stores/add_file Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Associates an uploaded file with a specific vector store. This makes the file's content searchable within that vector store. ```APIDOC ## POST /api/vector_stores/add_file ### Description Associates an uploaded file with a vector store, enabling the file search tool to query its contents. ### Method POST ### Endpoint /api/vector_stores/add_file ### Parameters #### Request Body - **vectorStoreId** (string) - Required - The ID of the vector store to which the file will be added. - **fileId** (string) - Required - The ID of the file that was previously uploaded to OpenAI. ### Request Example ```json { "vectorStoreId": "vs_abc123", "fileId": "file_xyz789" } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the VectorStoreFile object. - **vector_store_id** (string) - The ID of the associated vector store. - **file_id** (string) - The ID of the associated file. - **status** (string) - The status of the file within the vector store (e.g., "completed"). #### Response Example ```json { "id": "vsf_def456", "vector_store_id": "vs_abc123", "file_id": "file_xyz789", "status": "completed" } ``` ``` -------------------------------- ### Dynamically Generate OpenAI Tools with getTools Source: https://context7.com/openai/openai-responses-starter-app/llms.txt The `getTools` function, located in `lib/tools/tools.ts`, dynamically constructs the `tools` array required by the OpenAI Responses API. It takes a `ToolsState` object as input, which defines which features (like web search, file search, code interpreter, MCP, and Google integration) are enabled. Based on this state, it generates the appropriate tool configurations, including parameters for each tool. ```typescript // lib/tools/tools.ts - getTools function import { getTools } from "@/lib/tools/tools"; import { ToolsState } from "@/stores/useToolsStore"; // Example tools state configuration const toolsState: ToolsState = { webSearchEnabled: true, fileSearchEnabled: true, functionsEnabled: true, codeInterpreterEnabled: true, vectorStore: { id: "vs_abc123", name: "My Docs" }, webSearchConfig: { user_location: { type: "approximate", country: "US", city: "San Francisco", region: "CA" } }, mcpEnabled: true, mcpConfig: { server_label: "my-mcp-server", server_url: "https://mcp.example.com/sse", allowed_tools: "search,analyze", skip_approval: false }, googleIntegrationEnabled: true }; // Generated tools array for Responses API const tools = await getTools(toolsState); // Returns array like: // [ // { type: "web_search", user_location: { type: "approximate", country: "US", ... } }, // { type: "file_search", vector_store_ids: ["vs_abc123"] }, // { type: "code_interpreter", container: { type: "auto" } }, // { type: "function", name: "get_weather", description: "...", parameters: {...}, strict: true }, // { type: "function", name: "get_joke", description: "...", parameters: {...}, strict: true }, // { type: "mcp", server_label: "my-mcp-server", server_url: "...", allowed_tools: ["search", "analyze"] }, // { type: "mcp", server_label: "GoogleCalendar", connector_id: "connector_googlecalendar", ... }, // { type: "mcp", server_label: "GoogleMail", connector_id: "connector_gmail", ... } // ] ``` -------------------------------- ### Manage Chat Conversation State with Zustand Source: https://context7.com/openai/openai-responses-starter-app/llms.txt This snippet demonstrates how to use Zustand to manage chat messages and conversation state. It includes functions for adding messages, managing assistant loading states, and resetting the conversation. Accessing the store allows direct manipulation of chat UI items and API context. ```typescript // stores/useConversationStore.ts import useConversationStore from "@/stores/useConversationStore"; // Access store in components const { chatMessages, // Items displayed in chat UI conversationItems, // Items sent to Responses API isAssistantLoading, // Loading indicator state addChatMessage, // Add message to chat display addConversationItem, // Add item for API context setAssistantLoading, // Update loading state resetConversation // Clear and reset to initial state } = useConversationStore(); // Add a user message addChatMessage({ type: "message", role: "user", content: [{ type: "input_text", text: "Hello!" }] }); addConversationItem({ role: "user", content: [{ type: "input_text", text: "Hello!" }] }); // Reset conversation resetConversation(); // Resets to initial state with welcome message ``` -------------------------------- ### List Files in Vector Store Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Retrieves a list of all files currently associated with a specific vector store. It requires the vector store ID as a query parameter. The response is a JSON object containing an array of file objects, each with an ID and status. ```typescript // GET /api/vector_stores/list_files?vector_store_id=vs_abc123 // Response: { "data": [{ "id": "file_xyz", "status": "completed" }, ...] } // curl example curl "http://localhost:3000/api/vector_stores/list_files?vector_store_id=vs_abc123" // Client-side usage const listFiles = async (vectorStoreId: string) => { const response = await fetch( `/api/vector_stores/list_files?vector_store_id=${vectorStoreId}` ); return response.json(); }; const files = await listFiles("vs_abc123"); console.log(`Store contains ${files.data.length} files`); files.data.forEach(f => console.log(`- ${f.id}: ${f.status}`)); ``` -------------------------------- ### POST /api/turn_response Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Handles multi-turn conversations with the OpenAI Responses API, supporting streaming responses and various tools. It manages the conversation flow and tool integrations. ```APIDOC ## POST /api/turn_response ### Description Handles multi-turn conversations with the OpenAI Responses API, supporting streaming responses with various tools enabled based on the client's configuration. ### Method POST ### Endpoint /api/turn_response ### Parameters #### Request Body - **messages** (array) - Required - An array of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender (e.g., 'user', 'assistant'). - **content** (array) - Required - The content of the message. - **type** (string) - Required - The type of content (e.g., 'input_text'). - **text** (string) - Required - The actual text content. - **toolsState** (object) - Optional - Configuration object for enabling various tools. - **webSearchEnabled** (boolean) - Optional - Enables web search functionality. - **fileSearchEnabled** (boolean) - Optional - Enables file search functionality. - **functionsEnabled** (boolean) - Optional - Enables custom function calling. - **codeInterpreterEnabled** (boolean) - Optional - Enables the code interpreter tool. - **vectorStore** (object | null) - Optional - Configuration for the vector store. - **webSearchConfig** (object) - Optional - Configuration for web search. - **user_location** (object) - Optional - User's approximate location. - **type** (string) - Required - Type of location data (e.g., 'approximate'). - **country** (string) - Required - User's country. - **mcpEnabled** (boolean) - Optional - Enables MCP (Multi-Channel Platform) integration. - **mcpConfig** (object) - Optional - Configuration for MCP integration. - **server_label** (string) - Optional - Label for the MCP server. - **server_url** (string) - Optional - URL of the MCP server. - **allowed_tools** (string) - Optional - Comma-separated list of allowed tools. - **skip_approval** (boolean) - Optional - Skips MCP tool approval. - **googleIntegrationEnabled** (boolean) - Optional - Enables Google integration (Calendar/Gmail). ### Request Example ```json { "messages": [ { "role": "user", "content": [{ "type": "input_text", "text": "What's the weather in Paris?" }] } ], "toolsState": { "webSearchEnabled": true, "fileSearchEnabled": false, "functionsEnabled": true, "codeInterpreterEnabled": false, "vectorStore": null, "webSearchConfig": { "user_location": { "type": "approximate", "country": "US" } }, "mcpEnabled": false, "mcpConfig": { "server_label": "", "server_url": "", "allowed_tools": "", "skip_approval": true }, "googleIntegrationEnabled": false } } ``` ### Response #### Success Response (200) - **event** (string) - The type of event received (e.g., 'response.output_text.delta', 'response.completed'). - **data** (object) - The data associated with the event. #### Response Example ```json { "event": "response.output_text.delta", "data": { "delta": "The weather in Paris is " } } ``` ``` -------------------------------- ### Upload File to OpenAI Storage Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Uploads a file to OpenAI's storage, preparing it for addition to a vector store. It requires the file name and base64-encoded content. The response includes the OpenAI File object. ```typescript // POST /api/vector_stores/upload_file // Request body: { "fileObject": { "name": "document.pdf", "content": "" } } // Response: OpenAI File object // Client-side implementation const uploadFile = async (file: File) => { const content = await new Promise((resolve) => { const reader = new FileReader(); reader.onload = () => { const base64 = (reader.result as string).split(",")[1]; resolve(base64); }; reader.readAsDataURL(file); }); const response = await fetch("/api/vector_stores/upload_file", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileObject: { name: file.name, content } }) }); return response.json(); }; // Usage const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; const uploadedFile = await uploadFile(file); console.log(`Uploaded file ID: ${uploadedFile.id}`); ``` -------------------------------- ### Generate Google Calendar and Gmail Connector Tools Source: https://context7.com/openai/openai-responses-starter-app/llms.txt The `getGoogleConnectorTools` function in `lib/tools/connectors.ts` generates MCP-style connector tools for Google Calendar and Gmail. This function requires an access token and returns an array of tool configurations if the token is valid. These tools are designed to interact with Google services for searching calendars and emails, and can be integrated into the OpenAI Responses API toolset when Google integration is enabled and the user is authenticated. ```typescript // lib/tools/connectors.ts export function getGoogleConnectorTools(accessToken: string): any[] { if (!accessToken) return []; return [ { type: "mcp", server_label: "GoogleCalendar", server_description: "Search the user's calendar and read calendar events", connector_id: "connector_googlecalendar", authorization: accessToken, require_approval: "never" // Change to "always" for approval prompts }, { type: "mcp", server_label: "GoogleMail", server_description: "Search the user's email inbox and read emails", connector_id: "connector_gmail", authorization: accessToken, require_approval: "never" } ]; } // Usage when building tools for Responses API if (googleIntegrationEnabled) { const { accessToken } = await getFreshAccessToken(); tools.push(...getGoogleConnectorTools(accessToken)); } ``` -------------------------------- ### POST /api/vector_stores/upload_file Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Uploads a file to OpenAI's file storage. The file content should be base64-encoded. This is a prerequisite for adding files to a vector store. ```APIDOC ## POST /api/vector_stores/upload_file ### Description Uploads a file to OpenAI's file storage for later addition to a vector store, supporting base64-encoded file content. ### Method POST ### Endpoint /api/vector_stores/upload_file ### Parameters #### Request Body - **fileObject** (object) - Required - An object containing the file's name and its base64-encoded content. - **name** (string) - Required - The name of the file (e.g., "document.pdf"). - **content** (string) - Required - The base64-encoded content of the file. ### Request Example ```json { "fileObject": { "name": "document.pdf", "content": "" } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the uploaded OpenAI file. - **filename** (string) - The name of the uploaded file. - **purpose** (string) - The purpose of the file (e.g., "vector_store"). - **status** (string) - The current status of the file (e.g., "processed"). #### Response Example ```json { "id": "file_abc123", "filename": "document.pdf", "purpose": "vector_store", "status": "processed" } ``` ``` -------------------------------- ### Google Connection Status Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Checks the user's Google OAuth connection status and whether OAuth is configured in the application. ```APIDOC ## GET /api/google/status ### Description Retrieves the current Google OAuth connection status and configuration. This endpoint is useful for determining whether to display a "Connect Google" button or enable Google integration features. ### Method GET ### Endpoint /api/google/status ### Parameters (No parameters) ### Request Example ```bash curl "http://localhost:3000/api/google/status" ``` ### Response #### Success Response (200) - **connected** (boolean) - Indicates if the user has an active Google OAuth connection. - **oauthConfigured** (boolean) - Indicates if Google OAuth is configured in the application. #### Response Example ```json { "connected": false, "oauthConfigured": true } ``` ``` -------------------------------- ### Add File to Vector Store Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Associates an uploaded file with a specified vector store. This enables the file search tool to query the file's content. It requires the vector store ID and the file ID obtained from the upload process. The response is a VectorStoreFile object. ```typescript // POST /api/vector_stores/add_file // Request body: { "vectorStoreId": "vs_abc123", "fileId": "file_xyz789" } // Response: VectorStoreFile object // curl example curl -X POST "http://localhost:3000/api/vector_stores/add_file" \ -H "Content-Type: application/json" \ -d '{"vectorStoreId": "vs_abc123", "fileId": "file_xyz789"}' // Complete workflow: upload then add to store const addFileToStore = async (vectorStoreId: string, file: File) => { // Step 1: Upload file const uploadedFile = await uploadFile(file); // Step 2: Add to vector store const response = await fetch("/api/vector_stores/add_file", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ vectorStoreId, fileId: uploadedFile.id }) }); return response.json(); }; const result = await addFileToStore("vs_abc123", pdfFile); console.log(`File added with status: ${result.status}`); ``` -------------------------------- ### Handle Google OAuth Callback and Token Exchange Source: https://context7.com/openai/openai-responses-starter-app/llms.txt This endpoint, typically located at /api/google/callback, handles the redirection from Google after user authorization. It validates the state parameter, exchanges the authorization code for access, refresh, and ID tokens using PKCE, and securely stores these tokens in memory and httpOnly cookies. The process concludes with a redirect to the homepage, indicating success or failure. ```typescript // GET /api/google/callback?code=...&state=... // Redirects to /?connected=1 on success or /?error=... on failure // This endpoint is called automatically by Google after user consent // It performs: // 1. Validates state parameter against stored cookie // 2. Exchanges authorization code for tokens using PKCE verifier // 3. Stores tokens in memory and httpOnly cookies: // - gc_access_token // - gc_refresh_token // - gc_id_token // - gc_expires_at // 4. Redirects to homepage with connected=1 query param // Token structure stored: interface OAuthTokens { access_token: string; refresh_token?: string; id_token?: string; token_type: string; scope?: string; expires_at?: number; } ``` -------------------------------- ### Retrieve Vector Store Details Source: https://context7.com/openai/openai-responses-starter-app/llms.txt Fetches detailed information about a specific vector store, including its status and file counts. The vector store ID is required as a query parameter. The response is an OpenAI VectorStore object. ```typescript // GET /api/vector_stores/retrieve_store?vector_store_id=vs_abc123 // Response: OpenAI VectorStore object // curl example curl "http://localhost:3000/api/vector_stores/retrieve_store?vector_store_id=vs_abc123" // Client-side usage const getVectorStore = async (vectorStoreId: string) => { const response = await fetch( `/api/vector_stores/retrieve_store?vector_store_id=${vectorStoreId}` ); return response.json(); }; const store = await getVectorStore("vs_abc123"); console.log(`Store: ${store.name}, Status: ${store.status}`); console.log(`File counts:`, store.file_counts); ``` -------------------------------- ### Set OpenAI API Key Environment Variable (Bash) Source: https://github.com/openai/openai-responses-starter-app/blob/main/README.md This snippet shows how to set the OPENAI_API_KEY environment variable in a .env file at the project root. This is a common method for configuring API keys in development environments, especially for Node.js projects. ```bash OPENAI_API_KEY= ``` -------------------------------- ### Process Assistant Messages and Streaming Events Source: https://context7.com/openai/openai-responses-starter-app/llms.txt This snippet details the `processMessages` function, which orchestrates the conversation flow by sending messages to the API and handling streaming events. It manages tool calls, text deltas, and completion events, providing a mechanism for custom event handling. ```typescript // lib/assistant.ts - processMessages function import { processMessages, handleTurn } from "@/lib/assistant"; // Trigger a new assistant turn (call after user sends a message) await processMessages(); // The function: // 1. Gets current state from stores // 2. Calls handleTurn with conversation items // 3. Processes streaming events: // - response.output_text.delta: Append text to assistant message // - response.output_item.added: Handle new tool calls (function, web_search, file_search, mcp, code_interpreter) // - response.function_call_arguments.delta: Stream function arguments // - response.output_item.done: Execute function calls and recurse // - response.completed: Handle MCP tool lists and approval requests // Custom event handling with handleTurn await handleTurn( conversationItems, toolsState, async ({ event, data }) => { switch (event) { case "response.output_text.delta": console.log("Text delta:", data.delta); break; case "response.output_item.added": console.log("New item:", data.item.type); break; case "response.completed": console.log("Response complete"); break; } } ); ``` -------------------------------- ### Check Google Connection Status and OAuth Configuration Source: https://context7.com/openai/openai-responses-starter-app/llms.txt The /api/google/status endpoint provides information about the user's Google OAuth connection status and whether OAuth is configured in the application. It returns a JSON object indicating if a connection is active and if the OAuth configuration is present. This is useful for client-side logic to determine whether to display a 'Connect Google' button or enable Google-related features. ```typescript // GET /api/google/status // Response: { "connected": true, "oauthConfigured": true } // curl example curl "http://localhost:3000/api/google/status" // Response: {"connected":false,"oauthConfigured":true} // Client-side usage const checkGoogleStatus = async () => { const response = await fetch("/api/google/status"); return response.json(); }; const status = await checkGoogleStatus(); if (status.oauthConfigured && !status.connected) { // Show "Connect Google" button showConnectButton(); } else if (status.connected) { // Enable Google integration features enableGoogleTools(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.