### Example: Getting Model Configurations
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Shows how to use the getModel hook to access and log the configured thinking and networking models.
```typescript
const { createModelProvider, getModel } = useAiProvider();
const { thinkingModel, networkingModel } = getModel();
console.log(`Using ${thinkingModel} for thinking, ${networkingModel} for search`);
```
--------------------------------
### Progress Event Examples
Source: https://github.com/u14app/deep-research/blob/main/docs/deep-research-api-doc.md
Illustrates how progress events are formatted, showing the start and end of a search task with optional data.
```text
event: progress
data: {"step":"search-task","status":"start","name":"AI trends for this year"}
```
```text
event: progress
data: {"step":"search-task","status":"end","name":"AI trends for this year","data":{"results_count": 15}}
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/u14app/deep-research/blob/main/README.md
Install project dependencies using pnpm, npm, or yarn. Ensure you have one of these package managers installed.
```bash
pnpm install # or npm install or yarn install
```
--------------------------------
### Example: Creating a Model Provider
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Demonstrates how to use the createModelProvider hook within a React component to get an AI model instance.
```typescript
function MyComponent() {
const { createModelProvider } = useAiProvider();
const handleGenerateText = async () => {
const model = await createModelProvider('gpt-4o');
// Use model for text generation
};
return ;
}
```
--------------------------------
### Production Setup for Deep Research
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/README.md
Configures environment variables for a production deployment using server mode with authentication. Supports multi-key configurations for AI and search providers and includes build and start commands.
```bash
# Server mode with authentication
export ACCESS_PASSWORD="secure-password"
export MCP_AI_PROVIDER="google"
export MCP_THINKING_MODEL="gemini-2.0-flash-thinking-exp"
export MCP_TASK_MODEL="gemini-2.0-flash-exp"
export MCP_SEARCH_PROVIDER="tavily"
# Multi-key support
export GOOGLE_GENERATIVE_AI_API_KEY="key1,key2,key3"
export TAVILY_API_KEY="key1,key2"
# Deploy
npm run build && npm start
```
--------------------------------
### Local Testing Setup
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/README.md
Configure API keys for Gemini and Tavily and run the development server. Access the application at http://localhost:3000.
```bash
# Test with free Gemini API
export GOOGLE_GENERATIVE_AI_API_KEY="your-key"
export TAVILY_API_KEY="your-key"
npm run dev
# Open http://localhost:3000
```
--------------------------------
### SearXNG Docker Installation
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/search-providers.md
Installs and runs a SearXNG instance using Docker. The instance is exposed on port 8080.
```bash
docker run --name searxng -p 8080:8080 searxng/searxng
```
--------------------------------
### Infor Event Example
Source: https://github.com/u14app/deep-research/blob/main/docs/deep-research-api-doc.md
An example of an 'infor' event, including the project name and version.
```text
event: infor
data: {"name":"deep-research","version":"0.1.0"}
```
--------------------------------
### start()
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/api-reference-deepresearch.md
Executes the complete deep research workflow from topic to final report, including citation and reference generation options.
```APIDOC
## Method: start()
### Description
Executes the complete deep research workflow from topic to final report. This method orchestrates the entire research process, from initial query to the final synthesized report, with options to include citations, references, and images.
### Method
`async start(query: string, enableCitationImage: boolean = true, enableReferences: boolean = true, enableFileFormatResource: boolean = false): Promise`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **query** (`string`) - Required - Research topic or question.
* **enableCitationImage** (`boolean`) - Optional - Defaults to `true`. Include images in the final report.
* **enableReferences** (`boolean`) - Optional - Defaults to `true`. Include citation links and references.
* **enableFileFormatResource** (`boolean`) - Optional - Defaults to `false`. Enable file-formatted resources during generation.
### Response
#### Success Response
* **FinalReportResult** - Object containing title, finalReport markdown, learnings array, sources array, and images array.
#### Response Example
```typescript
{
title: "Latest trends in AI for 2024",
finalReport: "# Latest trends in AI for 2024\n...",
learnings: ["AI is rapidly evolving..."],
sources: ["https://example.com/source1"],
images: ["https://example.com/image1.png"]
}
```
### Throws
* `Error` if any step fails during research execution.
### Example
```typescript
try {
const result = await deepResearch.start(
'Latest trends in AI for 2024',
true,
true,
false
);
console.log('Report Title:', result.title);
console.log('Final Report:', result.finalReport);
console.log('Sources:', result.sources);
} catch (error) {
console.error('Research failed:', error);
}
```
```
--------------------------------
### MCP Progress Event Example
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/mcp-server-api.md
Shows an example of a progress event streamed by the MCP server during a research operation.
```text
Event: progress
Data: {"step": "report-plan", "status": "end"}
```
--------------------------------
### Example Live Deep Research URL
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/endpoints.md
An example URL to access a live deep research session for machine learning trends.
```http
http://localhost:3000/api/sse/live?query=machine+learning+trends&provider=google&thinkingModel=gemini-2.0-flash-thinking-exp&taskModel=gemini-2.0-flash-exp&searchProvider=tavily
```
--------------------------------
### Run Development Server
Source: https://github.com/u14app/deep-research/blob/main/README.md
Start the development server to run Deep Research locally. Access the application via http://localhost:3000.
```bash
pnpm dev # or npm run dev or yarn dev
```
--------------------------------
### Create Search Provider Example
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/search-providers.md
Demonstrates how to use the `createSearchProvider` function to perform a search using the Tavily provider and log the number of sources and images found.
```typescript
import { createSearchProvider } from '@/utils/deep-research/search';
const results = await createSearchProvider({
provider: 'tavily',
query: 'quantum computing breakthroughs 2024',
apiKey: process.env.TAVILY_API_KEY,
maxResult: 5,
});
console.log(`Found ${results.sources.length} sources`);
console.log(`${results.images.length} images`);
```
--------------------------------
### Minimum Local Setup for Deep Research
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/README.md
Sets up essential environment variables for a single AI and search provider for local development. Requires API keys for the chosen providers and runs the development server.
```bash
# Choose one AI provider
export GOOGLE_GENERATIVE_AI_API_KEY="your-key"
# Choose one search provider
export TAVILY_API_KEY="your-key"
# Run
npm run dev
```
--------------------------------
### Docker Compose Deployment
Source: https://github.com/u14app/deep-research/blob/main/README.md
Define and deploy the service using a docker-compose.yml file. This example includes environment variables and port mapping.
```yaml
version: '3.9'
services:
deep-research:
image: xiangfa/deep-research
container_name: deep-research
environment:
- ACCESS_PASSWORD=your-password
- GOOGLE_GENERATIVE_AI_API_KEY=AIzaSy...
ports:
- 3333:3000
```
--------------------------------
### Example Usage of useMobile
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Shows how to use the useMobile hook to conditionally render components based on whether the viewport is mobile.
```typescript
function ResponsiveComponent() {
const { isMobile } = useMobile();
return isMobile ? : ;
}
```
--------------------------------
### ThinkTagStreamProcessor Example Usage
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/utility-functions.md
Demonstrates how to use the ThinkTagStreamProcessor to process streaming text chunks and log content and reasoning separately.
```typescript
import { ThinkTagStreamProcessor } from '@/utils/text';
const processor = new ThinkTagStreamProcessor();
// Simulate streaming text
const chunks = [
"Some analysis ",
"Let me ",
"reason through ",
"this problem ",
"Final conclusion"
];
chunks.forEach(chunk => {
processor.processChunk(
chunk,
(content) => console.log('Content:', content),
(reasoning) => console.log('Reasoning:', reasoning)
);
});
processor.end();
```
--------------------------------
### SSE 'infor' Event Data
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/endpoints.md
Example data for the 'infor' event, sent at the start of an SSE connection. It contains server metadata such as the service name and version.
```json
{
"event": "infor",
"data": {
"name": "deep-research",
"version": "0.11.1"
}
}
```
--------------------------------
### Reasoning Event Example
Source: https://github.com/u14app/deep-research/blob/main/docs/deep-research-api-doc.md
An example of a 'reasoning' event, showing the output of a thinking process.
```text
event: message
data: {"type":"text","text":"Output thinking process"}
```
--------------------------------
### Example Usage of fileParser
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/file-parsing.md
Demonstrates how to use the fileParser function to extract content from a file and store it in a knowledge base. Includes error handling for parsing failures.
```typescript
import { fileParser } from '@/utils/parser';
async function uploadDocument(file: File) {
try {
const content = await fileParser(file);
console.log(`Extracted ${content.length} characters from ${file.name}`);
// Store in knowledge base
const knowledge = {
id: generateId(),
title: file.name,
content: content,
type: 'file',
fileMeta: {
name: file.name,
size: file.size,
type: file.type,
lastModified: file.lastModified,
},
createdAt: Date.now(),
updatedAt: Date.now(),
};
knowledgeStore.addKnowledge(knowledge);
} catch (error) {
console.error('Failed to parse file:', error);
// Handle error - show user message, etc.
}
}
```
--------------------------------
### Example Usage of useModelList getProviderModels
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Demonstrates how to use the getProviderModels function from the useModelList hook to fetch models for different providers.
```typescript
const { getProviderModels } = useModelList();
const openaiModels = getProviderModels('openai');
const googleModels = getProviderModels('google');
```
--------------------------------
### Error Event Example
Source: https://github.com/u14app/deep-research/blob/main/docs/deep-research-api-doc.md
Demonstrates the format of an error event, including a message explaining the cause of the error.
```text
event: error
data: {"message":"Invalid query parameters."}
```
--------------------------------
### Run Docker Container with Environment Variables
Source: https://github.com/u14app/deep-research/blob/main/README.md
Deploy the Docker image with custom environment variables for access password and API keys. The ACCESS_PASSWORD and GOOGLE_GENERATIVE_AI_API_KEY are examples.
```bash
docker run -d --name deep-research \
-p 3333:3000 \
-e ACCESS_PASSWORD=your-password \
-e GOOGLE_GENERATIVE_AI_API_KEY=AIzaSy... \
xiangfa/deep-research
```
--------------------------------
### Message Event Example
Source: https://github.com/u14app/deep-research/blob/main/docs/deep-research-api-doc.md
An example of a 'message' event containing markdown-formatted text.
```text
event: message
data: {"type":"text","text":"This is a **markdown** string."}
```
--------------------------------
### useDeepResearch Hook Usage Example
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Demonstrates how to use the useDeepResearch hook to initiate a research workflow with a given query. It shows how to access the status and the startResearch function.
```typescript
function ResearchComponent() {
const { status, startResearch } = useDeepResearch();
const taskStore = useTaskStore();
const handleStartResearch = async () => {
await startResearch('Latest AI breakthroughs 2024');
};
return (
Status: {status}
{taskStore.tasks.map((task, i) => (
{task.query}: {task.learning}
))}
);
}
```
--------------------------------
### Example Usage of Deep Research Tool with Claude SDK
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/mcp-server-api.md
Demonstrates how to use the 'deep_research' MCP tool with the Claude SDK. Ensure the Anthropic client is initialized and the tool is correctly specified.
```python
# Using Claude SDK with MCP
from anthropic import Anthropic
client = Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=4096,
tools=[
{
"type": "use_mcp_tool",
"mcp_server": "deep-research",
"tool_name": "deep_research",
"tool_input": {
"query": "Recent advances in quantum computing",
"language": "en",
"maxResult": 5,
"enableReferences": True
}
}
]
)
# Access results
for block in response.content:
if hasattr(block, 'text'):
print(block.text)
```
--------------------------------
### Create AI Provider Instances
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/api-reference-provider.md
Instantiate AI provider models using the `createAIProvider` function. Examples cover Google, OpenAI, Anthropic, Google Vertex, and Azure providers, demonstrating different authentication and configuration options.
```typescript
import { createAIProvider } from '@/utils/deep-research/provider';
// Google provider
const googleModel = await createAIProvider({
provider: 'google',
model: 'gemini-2.0-flash',
apiKey: process.env.GOOGLE_API_KEY,
baseURL: 'https://generativelanguage.googleapis.com/v1beta',
});
// OpenAI provider
const openaiModel = await createAIProvider({
provider: 'openai',
model: 'gpt-4o',
apiKey: process.env.OPENAI_API_KEY,
baseURL: 'https://api.openai.com/v1',
});
// Anthropic provider
const anthropicModel = await createAIProvider({
provider: 'anthropic',
model: 'claude-opus-4-8',
apiKey: process.env.ANTHROPIC_API_KEY,
baseURL: 'https://api.anthropic.com/v1',
headers: {
'anthropic-dangerous-direct-browser-access': 'true',
},
});
// Google Vertex with service account
const vertexModel = await createAIProvider({
provider: 'google-vertex',
model: 'gemini-2.0-flash',
auth: {
project: 'my-project',
location: 'us-central1',
clientEmail: 'service-account@project.iam.gserviceaccount.com',
privateKey: '-----BEGIN PRIVATE KEY-----...',
},
});
// Azure OpenAI
const azureModel = await createAIProvider({
provider: 'azure',
model: 'gpt-4-turbo',
auth: {
resourceName: 'my-resource',
apiKey: process.env.AZURE_API_KEY,
apiVersion: '2024-05-01-preview',
},
});
// With search grounding
const modelWithSearch = await createAIProvider({
provider: 'google',
model: 'gemini-2.0-flash',
apiKey: process.env.GOOGLE_API_KEY,
settings: { useSearchGrounding: true },
});
```
--------------------------------
### useWebSearch Hook Usage Example
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Illustrates how to use the useWebSearch hook to perform a web search and log the results. It demonstrates calling the search function and iterating over the returned results.
```typescript
function SearchComponent() {
const { search } = useWebSearch();
const handleSearch = async () => {
const results = await search('quantum computing breakthroughs');
results.forEach(result => {
console.log(`${result.title}: ${result.url}`);
console.log(result.content);
});
};
return ;
}
```
--------------------------------
### Example: Checking for API Key
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Illustrates how to use the hasApiKey hook to conditionally render UI elements based on API key configuration.
```typescript
const { hasApiKey } = useAiProvider();
if (!hasApiKey()) {
return
Please configure API key in settings
;
}
```
--------------------------------
### GET /api/sse/live
Source: https://github.com/u14app/deep-research/blob/main/README.md
Allows direct monitoring of the deep research process via a URL, similar to watching a video stream.
```APIDOC
## GET /api/sse/live
### Description
Provides a live, streamable view of the deep research process. Access the report directly through a URL, similar to watching a video.
### Method
GET
### Endpoint
/api/sse/live
### Parameters
#### Query Parameters
- **query** (string) - Required - The research topic.
- **provider** (string) - Required - The AI provider to use (e.g., google, openai, anthropic).
- **thinkingModel** (string) - Required - The ID of the thinking model.
- **taskModel** (string) - Required - The ID of the task model.
- **searchProvider** (string) - Required - The search engine to use (e.g., model, tavily, firecrawl).
- **language** (string) - Optional - The desired response and search language.
- **maxResult** (number) - Optional - The maximum number of search results to retrieve. Defaults to 5.
- **enableCitationImage** (boolean) - Optional - Whether to include content-related images in the report. Defaults to true.
- **enableReferences** (boolean) - Optional - Whether to include citation links in search results and reports. Defaults to true.
- **password** (string) - Optional - Required if the `ACCESS_PASSWORD` environment variable is set.
### Request Example
```text
http://localhost:3000/api/sse/live?query=AI+trends+for+this+year&provider=pollinations&thinkingModel=openai&taskModel=openai-fast&searchProvider=searxng
```
### Response
#### Success Response (200)
- Data is streamed in real-time, allowing live monitoring of the research process.
```
--------------------------------
### MCP Error Response Example
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/mcp-server-api.md
Illustrates the structure of an error response from the MCP server, including error code, message, and additional data.
```json
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32602,
"message": "Invalid params",
"data": {
"details": "Missing required parameter: query"
}
}
}
```
--------------------------------
### Use Deep Research MCP Tool with Python SDK
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/mcp-server-api.md
This Python example demonstrates using the 'use_mcp_tool' for deep research. It specifies the MCP server, tool name, and input parameters for the research query, including language and result limits.
```python
import anthropic
import json
client = anthropic.Anthropic(api_key="your-api-key")
def deep_research(topic: str):
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=4096,
tools=[
{
"type": "use_mcp_tool",
"mcp_server": "deep-research",
"tool_name": "deep_research",
"tool_input": {
"query": topic,
"language": "en",
"maxResult": 5,
"enableReferences": True
}
}
],
messages=[
{
"role": "user",
"content": f"Provide comprehensive research on: {topic}"
}
]
)
return response.content
# Usage
result = deep_research("Quantum computing applications")
print(json.dumps(result, indent=2))
```
--------------------------------
### Initiate SSE Research Task
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/endpoints.md
Example of initiating a deep research task via POST request to the /api/sse endpoint using fetch-event-source. Handles 'message' and 'progress' events.
```javascript
import { fetchEventSource } from '@microsoft/fetch-event-source';
const eventSource = await fetchEventSource('/api/sse', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: 'Recent breakthroughs in quantum computing',
provider: 'google',
thinkingModel: 'gemini-2.0-flash-thinking-exp',
taskModel: 'gemini-2.0-flash-exp',
searchProvider: 'tavily',
maxResult: 5,
language: 'en',
enableCitationImage: true,
enableReferences: true,
}),
onopen() {
console.log('Connection opened');
},
onmessage(event) {
if (event.event === 'message') {
console.log('Report content:', event.data.text);
} else if (event.event === 'progress') {
console.log(`[${event.data.step}] ${event.data.status}`);
}
},
onerror(err) {
console.error('Stream error:', err);
},
});
```
--------------------------------
### SSE 'progress' Event Data
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/endpoints.md
Example data for the 'progress' event, indicating the status of research steps. Includes the step name, status (start/end), and optional query text or step-specific data.
```json
{
"event": "progress",
"data": {
"step": "report-plan|serp-query|task-list|search-task|final-report",
"status": "start|end",
"name": "optional query text",
"data": "step-specific data object"
}
}
```
--------------------------------
### Set Up Environment Variables
Source: https://github.com/u14app/deep-research/blob/main/README.md
Copy the template environment file to either .env.local for development or .env for production. This file contains necessary configuration variables.
```bash
# For Development
cp env.tpl .env.local
# For Production
cp env.tpl .env
```
--------------------------------
### Create .env file from template
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/configuration.md
Use this command to create a production environment file from a template.
```bash
cp env.tpl .env
```
--------------------------------
### Accessing and Subscribing to Settings
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/configuration.md
Demonstrates how to import and use the `useSettingStore` hook to retrieve all settings, specific settings, or subscribe to changes in the settings store.
```typescript
import { useSettingStore } from '@/store/setting';
// Get all settings
const allSettings = useSettingStore.getState();
// Get specific setting
const { provider, apiKey, language } = useSettingStore.getState();
// Watch setting changes
useSettingStore.subscribe((state) => {
console.log('Settings updated:', state);
});
```
--------------------------------
### Configuration Options
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/MANIFEST.txt
Documentation for the 100+ configuration options, including environment variables for API keys, client settings, and deployment.
```APIDOC
## Configuration Reference
### Description
Comprehensive guide to the configuration options available for the Deep Research system.
### Configuration Details
- Over 100 environment variables.
- API key configuration for 12+ providers.
- Search provider setup details.
- Client settings store structure.
- Deployment platform guides.
### Usage
Consult `configuration.md` for detailed information on all configuration options and environment variables.
```
--------------------------------
### Get Deep Research Thinking Model
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/api-reference-deepresearch.md
Retrieves an initialized thinking model instance. Use this to get a language model ready for streaming text generation.
```typescript
async getThinkingModel(): Promise
```
```typescript
const model = await deepResearch.getThinkingModel();
```
--------------------------------
### Get Deep Research Task Model
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/api-reference-deepresearch.md
Retrieves an initialized task model instance. Use this to get a language model ready for task execution, potentially with search grounding.
```typescript
async getTaskModel(): Promise
```
```typescript
const model = await deepResearch.getTaskModel();
```
--------------------------------
### Create .env.local file for development
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/configuration.md
Use this command to create a local development environment file from a template.
```bash
cp env.tpl .env.local
```
--------------------------------
### removeJsonMarkdown Example Usage
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/utility-functions.md
Demonstrates using removeJsonMarkdown to clean a JSON string that is wrapped in markdown code block syntax.
```typescript
import { removeJsonMarkdown } from '@/utils/text';
const dirty = `\
\
{\"key\": \"value\"}
\
\
`;
const clean = removeJsonMarkdown(dirty);
// Result: '{"key": "value"}'
```
--------------------------------
### Get Supported MIME Types
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/file-parsing.md
Returns a list of MIME types that the parser supports. This can be used to understand the default supported formats.
```typescript
function getSupportedMimeTypes(): string[] {
return [
// Text formats
'text/plain',
'text/html',
'text/markdown',
'text/xml',
// Structured data
'application/json',
'application/xml',
'application/x-yaml',
// Office documents
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.oasis.opendocument.text',
// PDF
'application/pdf',
];
}
```
--------------------------------
### Build Static Export
Source: https://github.com/u14app/deep-research/blob/main/README.md
Builds a static version of the project. The output will be placed in the 'out' directory, ready for deployment to static hosting services.
```bash
pnpm build:export
```
--------------------------------
### StreamableHTTP Transport Configuration
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/mcp-server-api.md
Configure the MCP server to use the streamable-http transport. Ensure the URL and transport type match your setup.
```json
{
"mcpServers": {
"deep-research": {
"url": "http://127.0.0.1:3000/api/mcp",
"transportType": "streamable-http",
"timeout": 600
}
}
}
```
--------------------------------
### useSettingStore()
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Provides access to and methods for modifying user settings and application configuration, such as API keys, language, and theme.
```APIDOC
## useSettingStore()
### Description
Access and modify user settings and configuration, including AI provider details, search engine settings, and UI preferences.
### State Properties
- `provider` — AI provider name
- `mode` — Execution mode (local/proxy)
- `apiKey` — Current provider API key
- `searchProvider` — Search engine
- `searchMaxResult` — Max search results
- `language` — UI language (en/zh/es)
- `theme` — Theme (light/dark/auto)
- `reportStyle` — Report writing style
- `reportLength` — Report length preference
### Usage
```typescript
const { provider, mode, apiKey, language } = useSettingStore.getState();
useSettingStore.setState({ language: 'zh', theme: 'dark' });
```
```
--------------------------------
### Use useKnowledge Hook
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Demonstrates how to use the useKnowledge hook to add files to the local knowledge base. Ensure the file input is correctly handled.
```typescript
function UploadComponent() {
const { addKnowledge } = useKnowledge();
const handleFileChange = async (e: React.ChangeEvent) => {
const file = e.target.files?.[0];
if (file) {
await addKnowledge(file);
}
};
return ;
}
```
--------------------------------
### React Hooks API
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/MANIFEST.txt
Documentation for the 10+ React hooks provided by the Deep Research library, including usage examples and return types.
```APIDOC
## React Hooks
### Description
Documentation for the React hooks available in the Deep Research library.
### Available Hooks
- `useAiProvider`
- `useDeepResearch`
- `useWebSearch`
- `useKnowledge`
- Store hooks: `useTaskStore`, `useSettingStore`
- Over 10 hooks in total.
### Usage
Consult `hooks-api.md` for detailed documentation, return types, and usage examples for each React hook.
```
--------------------------------
### File Parsing and Knowledge Base Integration
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/quick-reference.md
Demonstrates how to use the `fileParser` utility to extract content from various file types and add it to the knowledge base.
```typescript
import { fileParser } from '@/utils/parser';
// Supports: .txt, .pdf, .docx, .xlsx, .pptx, .md, .json, etc.
const content = await fileParser(file);
// Add to knowledge base
const knowledge = {
id: crypto.randomUUID(),
title: file.name,
content: content,
type: 'file',
fileMeta: { name: file.name, size: file.size, type: file.type, lastModified: file.lastModified },
createdAt: Date.now(),
updatedAt: Date.now(),
};
knowledgeStore.addKnowledge(knowledge);
```
--------------------------------
### useModelList()
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Hook for retrieving and managing the list of available models. It provides the list of models, a function to get models by provider, and a loading state.
```APIDOC
## useModelList()
### Description
Hook for retrieving and managing available model list.
### Returns
- **models** (ModelConfig[]) - The list of available models.
- **getProviderModels** (function) - A function that takes a provider string and returns an array of ModelConfig for that provider.
- **isLoading** (boolean) - Indicates if the model list is currently being loaded.
### Methods
#### getProviderModels(provider: string)
Get all models for a specific provider.
**Example:**
```typescript
const { getProviderModels } = useModelList();
const openaiModels = getProviderModels('openai');
const googleModels = getProviderModels('google');
```
### Types
#### ModelConfig
- **id** (string)
- **name** (string)
- **provider** (string)
- **type** ('thinking' | 'networking' | 'general')
```
--------------------------------
### Example Usage of useAccurateTimer
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Demonstrates how to use the useAccurateTimer hook for precise interval timing with automatic cleanup. The callback function is executed at specified intervals.
```typescript
useAccurateTimer(() => {
// Callback runs at precise intervals
console.log('Tick');
}, 1000); // Every 1000ms
```
--------------------------------
### Connect to SSE Endpoint and Handle Events
Source: https://github.com/u14app/deep-research/blob/main/docs/deep-research-api-doc.md
This snippet demonstrates how to establish a connection to the SSE endpoint using fetchEventSource. It includes handling 'message', 'progress', and 'error' events, and shows how to send a POST request with a JSON body containing research parameters.
```typescript
import { fetchEventSource } from "@microsoft/fetch-event-source";
const ctrl = new AbortController();
let report = "";
fetchEventSource("/api/sse", {
method: "POST",
headers: {
"Content-Type": "application/json",
// If you set an access password
// Authorization: "Bearer YOUR_ACCESS_PASSWORD",
},
body: JSON.stringify({
query: "AI trends for this year",
provider: "google",
thinkingModel: "gemini-2.0-flash-thinking-exp",
taskModel: "gemini-2.0-flash-exp",
searchProvider: "model",
language: "en-US",
maxResult: 5,
enableCitationImage: true,
enableReferences: true,
promptOverrides: {
systemInstruction:
"You are an expert researcher. Keep answers concise and evidence-driven.",
},
}),
signal: ctrl.signal,
onmessage(msg) {
const msgData = JSON.parse(msg.data);
if (msg.event === "message") {
if (msgData.type === "text") {
report += msgData.text;
}
} else if (msg.event === "progress") {
console.log(
`[${data.step}]: ${msgData.name ? `${msgData.name} ` : ""}${
msgData.status
}`
);
if (msgData.data) console.log(msgData.data);
} else if (msg.event === "error") {
throw new Error(msgData.message);
}
},
onclose() {
console.log(report);
},
});
```
--------------------------------
### SSE 'error' Event Data
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/endpoints.md
Example data for the 'error' event, emitted when a research task fails. The 'message' field provides a description of the error.
```json
{
"event": "error",
"data": {
"message": "error description"
}
}
```
--------------------------------
### Clone Deep Research Repository
Source: https://github.com/u14app/deep-research/blob/main/README.md
Clone the project repository to your local machine. This is the first step in setting up the development environment.
```bash
git clone https://github.com/u14app/deep-research.git
cd deep-research
```
--------------------------------
### Core API Reference (DeepResearch Class)
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/MANIFEST.txt
Documentation for the core DeepResearch class, including its public methods, signatures, usage examples, and return types.
```APIDOC
## DeepResearch Class API
### Description
Reference documentation for the core `DeepResearch` class, outlining its public methods and their usage.
### Methods
- 7 public methods with detailed signatures.
- Usage examples and return types are provided for each method.
### Usage
Consult `api-reference-deepresearch.md` for in-depth information on the `DeepResearch` class methods and their implementation.
```
--------------------------------
### Build and Run Custom Docker Image
Source: https://github.com/u14app/deep-research/blob/main/README.md
Build your own Docker image from the source code and then run it as a detached container. This is useful for custom builds.
```bash
docker build -t deep-research .
docker run -d --name deep-research -p 3333:3000 deep-research
```
--------------------------------
### Example Usage of useSubmitShortcut
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Illustrates how to use the useSubmitShortcut hook to trigger a callback function when Ctrl+Enter or Cmd+Enter keyboard shortcuts are pressed, typically for form submission.
```typescript
const inputRef = useRef(null);
useSubmitShortcut(() => {
// Called when Ctrl+Enter or Cmd+Enter is pressed
console.log('Submit via shortcut');
}, inputRef);
```
--------------------------------
### Combine Search Providers
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/search-providers.md
Demonstrates how to use different search providers concurrently to gather results from multiple sources.
```typescript
const results1 = await createSearchProvider({
provider: 'tavily',
query: 'topic',
});
const results2 = await createSearchProvider({
provider: 'exa',
query: 'topic',
});
```
--------------------------------
### OpenAI-compatible API
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/api-reference-provider.md
Configuration details for using an OpenAI-compatible API. Requires a base URL and API key.
```APIDOC
## openaicompatible
### Description
Configuration details for using an OpenAI-compatible API.
### Authentication
Requires `baseURL`, `apiKey`.
### Environment Variable
`OPENAI_COMPATIBLE_API_KEY`
```
--------------------------------
### SSE Data Format Example
Source: https://github.com/u14app/deep-research/blob/main/docs/deep-research-api-doc.md
Illustrates the structure of Server-Sent Events (SSE) used by the API. Events are categorized by 'event' type and contain JSON data.
```text
event: EventName
data: JSON_String
```
--------------------------------
### OpenAI (GPT models)
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/api-reference-provider.md
Configuration details for using OpenAI (GPT models). Requires an API key.
```APIDOC
## openai
### Description
Configuration details for using OpenAI (GPT models).
### Base URL
`https://api.openai.com/v1`
### Authentication
Requires `apiKey`.
### Environment Variable
`OPENAI_API_KEY`
### Special Notes
Returns `responses()` model for GPT-4o/4.1/5 variants.
```
--------------------------------
### Client-Side Deep Research Component
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/README.md
Utilize the `useDeepResearch` hook for initiating research from your React frontend components. This example assumes a `useTaskStore` is available for state management.
```typescript
function ResearchComponent() {
const { startResearch, status } = useDeepResearch();
const taskStore = useTaskStore();
const handleResearch = async () => {
await startResearch('Your research topic');
};
return (
{taskStore.finalReport}
);
}
```
--------------------------------
### SSE 'message' Event Data
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/endpoints.md
Example data for the 'message' event, streaming markdown content chunks during research generation. The 'text' field contains the content.
```json
{
"event": "message",
"data": {
"type": "text",
"text": "markdown content chunk"
}
}
```
--------------------------------
### Provider API Reference
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/MANIFEST.txt
Documentation for the `createAIProvider()` factory function and supported AI providers, including configuration details.
```APIDOC
## AI Provider Integration
### Description
Information regarding the `createAIProvider()` factory function and the configuration for 13 supported AI providers.
### Configuration
- Details on configuring each of the 13 supported AI providers.
- Environment variables relevant to provider configuration.
### Usage
Refer to `api-reference-provider.md` for comprehensive details on creating and configuring AI providers.
```
--------------------------------
### Build Docker Compose Image
Source: https://github.com/u14app/deep-research/blob/main/README.md
Builds the Docker image defined in the docker-compose.yml file. This command should be run in the same directory as the docker-compose.yml.
```bash
docker compose -f docker-compose.yml build
```
--------------------------------
### Configure custom model list
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/configuration.md
Set the NEXT_PUBLIC_MODEL_LIST environment variable to specify custom models for proxy mode.
```bash
NEXT_PUBLIC_MODEL_LIST=gpt-4o,gpt-4-turbo,claude-opus-4-8
```
--------------------------------
### Live SSE Endpoint URL
Source: https://github.com/u14app/deep-research/blob/main/README.md
Example URL for accessing the live deep research report via Server-Sent Events. Parameters are similar to the POST request body.
```text
http://localhost:3000/api/sse/live?query=AI+trends+for+this+year&provider=pollinations&thinkingModel=openai&taskModel=openai-fast&searchProvider=searxng
```
--------------------------------
### useAiProvider()
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Hook for managing AI provider model creation and configuration. It provides methods to create model instances, retrieve current model configurations, and check for API key validity.
```APIDOC
## useAiProvider()
### Description
Provides methods for managing AI provider model creation and configuration. This hook allows developers to interact with different AI models, retrieve their settings, and verify authentication credentials.
### Methods
#### createModelProvider(model: string, settings?: any): Promise
Creates a model instance based on current settings store configuration. This method can be used to instantiate a language model for use in AI-powered features.
**Parameters:**
- **model** (string) - Required - Model identifier
- **settings** (any) - Optional - Optional provider-specific settings
**Behavior:**
- In **local mode**: Uses client-side API keys from settings store
- In **proxy mode**: Routes through `/api/ai/{provider}/*` with signature authentication
- Handles provider-specific configuration (e.g., Google Vertex auth, Azure deployment)
- Adds headers for browser-based CORS handling (Anthropic)
### Request Example
```typescript
const { createModelProvider } = useAiProvider();
const handleGenerateText = async () => {
const model = await createModelProvider('gpt-4o');
// Use model for text generation
};
```
#### getModel(): {
thinkingModel: string;
networkingModel: string;
}
Returns the currently configured thinking and networking models. This method is useful for understanding which models are active for different types of AI tasks.
**Returns:** Object with `thinkingModel` (for complex reasoning) and `networkingModel` (for search-enabled tasks).
### Request Example
```typescript
const { getModel } = useAiProvider();
const { thinkingModel, networkingModel } = getModel();
console.log(`Using ${thinkingModel} for thinking, ${networkingModel} for search`);
```
#### hasApiKey(): boolean
Checks if the current provider has valid API credentials configured. This is a crucial step for ensuring that AI services can be accessed successfully.
**Returns:** `true` if provider has required API key/credentials.
### Request Example
```typescript
const { hasApiKey } = useAiProvider();
if (!hasApiKey()) {
return
Please configure API key in settings
;
}
```
```
--------------------------------
### SSE 'reasoning' Event Data
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/endpoints.md
Example data for the 'reasoning' event, providing extended thinking or reasoning content from models that support it. The 'text' field contains this content.
```json
{
"event": "reasoning",
"data": {
"type": "text",
"text": "reasoning/thinking content"
}
}
```
--------------------------------
### Allow only specified models
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/configuration.md
Use '-all' to disable all default models and then '+' to enable only the desired models in NEXT_PUBLIC_MODEL_LIST.
```bash
NEXT_PUBLIC_MODEL_LIST=-all,+gpt-4o,+claude-opus-4-8
```
--------------------------------
### Handle Search Failures with Fallback
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/search-providers.md
Illustrates how to implement a fallback mechanism to an alternative search provider when the primary provider fails.
```typescript
try {
const results = await createSearchProvider({
provider: 'tavily',
query,
});
} catch (err) {
const fallback = await createSearchProvider({
provider: 'model',
query,
});
}
```
--------------------------------
### Extract Artifacts from Markdown
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/utility-functions.md
Parses markdown content to extract artifact blocks, including code blocks with specified languages. Useful for processing markdown files that contain embedded code examples.
```typescript
function extractArtifactFromMarkdown(
markdown: string
): Array<{ type: string; language: string; content: string }>
```
```typescript
const artifacts = extractArtifactFromMarkdown(`
Some text
\
\
python
print("hello")
\
\
More text
\
\
json
{"key": "value"}
\
\
`);
// Returns artifacts with type, language, and content
```
--------------------------------
### Download File
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/utility-functions.md
Initiates a browser download for the provided file content. Specify the filename and MIME type for correct handling.
```typescript
function downloadFile(
content: string | Blob,
filename: string,
type?: string
): void
```
```typescript
import { downloadFile } from '@/utils/file.ts';
const report = `# Research Report\n...`;
downloadFile(report, 'report.md', 'text/markdown');
```
--------------------------------
### POST /api/sse
Source: https://github.com/u14app/deep-research/blob/main/README.md
Initiates a research task via Server-Sent Events. Use `@microsoft/fetch-event-source` to listen for the 'message' event for real-time data streams.
```APIDOC
## POST /api/sse
### Description
Initiates a complex research task by sending configuration details to the server. The results are streamed back in real-time.
### Method
POST
### Endpoint
/api/sse
### Parameters
#### Request Body
- **query** (string) - Required - The research topic.
- **provider** (string) - Required - The AI provider to use (e.g., google, openai, anthropic).
- **thinkingModel** (string) - Required - The ID of the thinking model.
- **taskModel** (string) - Required - The ID of the task model.
- **searchProvider** (string) - Required - The search engine to use (e.g., model, tavily, firecrawl).
- **language** (string) - Optional - The desired response and search language.
- **maxResult** (number) - Optional - The maximum number of search results to retrieve. Defaults to 5.
- **enableCitationImage** (boolean) - Optional - Whether to include content-related images in the report. Defaults to true.
- **enableReferences** (boolean) - Optional - Whether to include citation links in search results and reports. Defaults to true.
#### Headers
- **Content-Type**: "application/json"
- **Authorization**: "Bearer YOUR_ACCESS_PASSWORD" (Optional) - If an access password is set.
### Request Example
```json
{
"query": "AI trends for this year",
"provider": "openai",
"thinkingModel": "gpt-4o",
"taskModel": "gpt-4-turbo",
"searchProvider": "tavily",
"language": "en",
"maxResult": 10,
"enableCitationImage": false,
"enableReferences": false
}
```
### Response
#### Success Response (200)
- Data is streamed as text. Listen to the `message` event for the final report.
```
--------------------------------
### GET /api/sse/live
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/endpoints.md
Allows users to watch a live deep research session by providing research parameters via URL. It returns an HTML page that streams real-time updates of the research process.
```APIDOC
## GET /api/sse/live
### Description
Watch a live deep research session via URL parameters. Returns rendered HTML page streaming updates.
### Method
GET
### Endpoint
/api/sse/live
### Parameters
#### Query Parameters
- **query** (string) - Required - Research topic
- **provider** (string) - Required - AI provider name
- **thinkingModel** (string) - Required - Thinking model ID
- **taskModel** (string) - Required - Task model ID
- **searchProvider** (string) - Required - Search provider name
- **maxResult** (number) - Optional - Search result limit
- **language** (string) - Optional - Response language
- **enableCitationImage** (boolean) - Optional - Include images
- **enableReferences** (boolean) - Optional - Include citations
- **password** (string) - Optional - Access password (required if set)
### Request Example
```
GET /api/sse/live?query=AI+trends+for+this+year&provider=google&thinkingModel=gemini-2.0-flash-thinking-exp&taskModel=gemini-2.0-flash-exp&searchProvider=tavily&maxResult=5&password=ACCESS_PASSWORD
```
### Response
#### Success Response (200)
HTML page with streaming research updates displayed in real-time.
#### Response Example
(Response is an HTML page with streaming updates, not a JSON object)
```
--------------------------------
### Accessing and Modifying User Settings
Source: https://github.com/u14app/deep-research/blob/main/_autodocs/hooks-api.md
Shows how to access and update user settings and configuration using `useSettingStore`. This includes reading current settings like provider and API key, and updating them, such as changing the language or theme.
```typescript
const { provider, mode, apiKey, language } = useSettingStore.getState();
// Update settings
useSettingStore.setState({ language: 'zh', theme: 'dark' });
```