### Starting System in Server Mode Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Server mode starts an HTTP server for API access, compatible with OpenAI. It can be started with or without authentication using a secret token. The server defaults to port 3000 but can be configured via the `PORT` environment variable. ```bash # Without authentication npm run serve # With authentication (requires Bearer token) npm run serve --secret=your_secret_token ``` -------------------------------- ### Verify DeepResearch Installation Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Command to run a simple test query to verify the DeepResearch setup. This is useful for confirming that the server is running and can process basic requests. ```bash npm run dev "1+1=" ``` -------------------------------- ### Environment Variable Proxy Setup - TypeScript Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Example of setting up an HTTPS proxy agent in TypeScript using `undici.ProxyAgent`. This code snippet is part of the DeepResearch application's configuration system and is triggered if the `https_proxy` environment variable is provided. ```typescript if (config.env.https_proxy) { process.env.HTTPS_PROXY = config.env.https_proxy; process.env.HTTP_PROXY = config.env.https_proxy; // Setup agent for undici if needed } ``` -------------------------------- ### Server Mode: OpenAI-Compatible API Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Guides on starting the DeepResearch HTTP server for API access, including options for authentication. ```APIDOC ## Server Mode: OpenAI-Compatible API To enable client integrations and access DeepResearch's capabilities programmatically, you can start it in server mode. This mode exposes an OpenAI-compatible API. ### Starting the Server: * **Without authentication:** ```bash npm run serve ``` * **With authentication (requires a Bearer token):** ```bash npm run serve --secret=your_secret_token ``` ### Server Details: * The server defaults to running on `http://localhost:3000`. You can configure the port using the `PORT` environment variable. ### Available Scripts: | Script | Command | Purpose | | :----- | :---------------------- | :------------------- | | `serve` | `ts-node src/server.ts` | Start API server | | `start` | `ts-node src/server.ts` | Alias for `serve` | ### Server Startup Flow: The server startup process is managed by `src/server.ts`. ``` -------------------------------- ### Example Error Analysis Output in JSON Source: https://deepwiki.com/jina-ai/node-DeepResearch/6-quality-control-and-evaluation Provides an example of the output generated by the `analyzeSteps` function when a failed answer attempt occurs. The output includes a recap of the process, the identified 'blame' or root cause, and specific 'improvement' strategies. ```json { "recap": "The search process consisted of 7 steps with multiple search and visit actions. Initial searches focused on LinkedIn and Crunchbase. When this didn't yield results, additional searches for birthdate information were conducted. Steps 4-5 showed repetition with identical searches. Final visits to entertainment websites suggested loss of focus.", "blame": "Root cause: getting stuck in repetitive search pattern without adapting strategy. Steps 4-5 repeated the same search. Step 6 deviated to less reliable entertainment sources instead of exploring business journals or professional databases.", "improvement": "1. Avoid repeating identical searches. 2. When direct searches fail, try indirect approaches: earliest career mentions, university graduation years, first company founding dates. 3. Focus on high-quality business sources. 4. If exact answer cannot be determined, provide estimated range based on career timeline." } ``` -------------------------------- ### Freshness Analysis Example with Dynamic Date Source: https://deepwiki.com/jina-ai/node-DeepResearch/6 Illustrates the structure of the freshness analysis schema, including dynamic date calculation relative to the current date. ```javascript freshness_analysis: { days_ago: [relative to current date] max_age_days: [acceptable age threshold] } Current date is injected: `relative to ${new Date().toISOString().slice(0, 10)}` ``` -------------------------------- ### API Key Validation - TypeScript Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Example demonstrating API key validation at startup within the DeepResearch application's configuration system. This TypeScript snippet ensures that required API keys for services like OpenAI, Gemini, and others are present before proceeding. ```typescript if (!config.env.OPENAI_API_KEY && !config.env.GEMINI_API_KEY) { throw new Error('Missing API key for OpenAI or Gemini'); } ``` -------------------------------- ### Configuration System - JSON Configuration Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Example of the `config.json` structure for the DeepResearch application. It includes sections for environment variables (`env`), default settings (`defaults`), provider configurations (`providers`), and model parameters (`models`). This file dictates the application's runtime behavior and external service integrations. ```json { "env": { "https_proxy": "", "OPENAI_BASE_URL": "", "GEMINI_API_KEY": "", "OPENAI_API_KEY": "", "JINA_API_KEY": "", "BRAVE_API_KEY": "", "SERPER_API_KEY": "", "DEFAULT_MODEL_NAME": "" }, "defaults": { "search_provider": "jina", "llm_provider": "gemini", "step_sleep": 0.5 }, "providers": { "vertex": { "createClient": "createGoogleVertex", "clientConfig": { "location": "us-central1" } }, "gemini": { "createClient": "createGoogleGenerativeAI" }, "openai": { "createClient": "createOpenAI", "clientConfig": { "compatibility": "strict" } } }, "models": {} } ``` -------------------------------- ### Making Streaming API Request Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started This example shows how to initiate a streaming request to the `/v1/chat/completions` endpoint by setting the `stream` parameter to `true`. The response will be delivered in chunks, with each chunk containing a portion of the generated content. ```bash curl http://localhost:3000/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your_secret_token" \ -d '{ "model": "jina-deepsearch-v1", "messages": [ {"role": "user", "content": "Hello!"} ], "stream": true }' ``` -------------------------------- ### Making API Requests: Streaming Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Example of how to make a streaming API request to the `/v1/chat/completions` endpoint and the format of streaming chunks. ```APIDOC ## Making API Requests: Streaming For real-time responses, you can enable streaming by setting the `stream` parameter to `true`. This allows you to receive response chunks as they are generated. ### Request Example: ```bash curl http://localhost:3000/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your_secret_token" \ -d '{ "model": "jina-deepsearch-v1", "messages": [ {"role": "user", "content": "Hello!"} ], "stream": true }' ``` ### Stream Chunk Format: Each chunk received will follow this structure: ```json { "id": "chatcmpl-123", "object": "chat.completion.chunk", "created": 1694268190, "model": "jina-deepsearch-v1", "choices": [ { "index": 0, "delta": { "content": "..." }, "finish_reason": null } ] } ``` **Special Content Handling:** Thinking steps generated by the model are wrapped in `` tags within the `content` field of the chunks. The final answer will be presented after these thinking steps. ``` -------------------------------- ### OpenAI Base URL Configuration - TypeScript Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Example of configuring a custom base URL for the OpenAI API in TypeScript. This allows the DeepResearch application to use alternative endpoints or proxies for the OpenAI service, managed through environment variables and the configuration system. ```typescript if (config.env.OPENAI_BASE_URL) { openai.baseURL = config.env.OPENAI_BASE_URL; } ``` -------------------------------- ### Vertex AI Provider Configuration Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 This JSON object illustrates the specific configuration for the Vertex AI provider. It includes details on how to create the client and specifies the client configuration, such as the GCP region (location). ```JSON { "providers": { "vertex": { "createClient": "createGoogleVertex", "clientConfig": { "location": "us-central1" } } } } ``` -------------------------------- ### Integrate with OpenAI SDK for DeepResearch Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Demonstrates how to use the OpenAI SDK to interact with the DeepResearch API. Configure the client with the base URL and API key. The example shows a chat completion request. ```typescript import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'http://localhost:3000/v1', apiKey: 'your_secret_token' }); const response = await client.chat.completions.create({ model: 'jina-deepsearch-v1', messages: [ { role: 'user', content: 'What is the latest news from Jina AI?' } ] }); ``` -------------------------------- ### Docker Environment Variables Configuration (Bash) Source: https://deepwiki.com/jina-ai/node-DeepResearch/10 This example demonstrates how to configure essential environment variables for DeepResearch within a Docker run command. It specifies API keys for Gemini, OpenAI, Jina AI, and Brave Search, which are crucial for service integration. ```bash # Docker run example with environment variables docker run -p 3000:3000 \ -e GEMINI_API_KEY=your_gemini_key \ -e OPENAI_API_KEY=your_openai_key \ -e JINA_API_KEY=your_jina_key \ -e BRAVE_API_KEY=your_brave_key \ deepresearch-image ``` -------------------------------- ### Parameter Substitution Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/9-advanced-features Illustrates the parameter substitution format used in i18n templates, showing how dynamic values are inserted into predefined strings. ```text Template: "Let me search for ${keywords}" Input: { keywords: "machine learning" } Output: "Let me search for machine learning" ``` -------------------------------- ### i18n Translation Key System Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/9-advanced-features Shows the translation key system for dynamic message generation, including examples of keys, their purpose, parameters, and usage within the application. ```markdown Key| Purpose| Parameters| Example Usage ---|---|---|--- `eval_first`| Evaluation notification| None| "But wait, let me evaluate the answer first." `search_for`| Search notification| `keywords`| "Let me search for ${keywords}..." `read_for`| Read notification| `urls`| "Let me read ${urls}..." `late_chunk`| Content filtering| `url`| "Content of ${url} is too long..." `finalize_answer`| Answer finalization| None| "Let me finalize the answer." `blocked_content`| Access error| `url`| "I might be blocked by ${url}" `hostnames_no_results`| Search failure| `hostnames`| "Can't find results from ${hostnames}" ``` -------------------------------- ### Run DeepResearch with Docker Compose Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Command to start the DeepResearch service using Docker Compose. This command assumes a valid docker-compose.yml file is present in the current directory. ```bash docker-compose up ``` -------------------------------- ### Making API Requests: Non-Streaming Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Example of how to make a non-streaming API request to the `/v1/chat/completions` endpoint. ```APIDOC ## Making API Requests: Non-Streaming This section demonstrates how to send a standard, non-streaming request to the chat completions endpoint. ### Request Example: ```bash curl http://localhost:3000/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your_secret_token" \ -d '{ "model": "jina-deepsearch-v1", "messages": [ { "role": "user", "content": "What is the latest blog post from Jina AI?" } ] }' ``` ### Response Format (Success): ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1677652288, "model": "jina-deepsearch-v1", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "YOUR FINAL ANSWER" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 9, "completion_tokens": 12, "total_tokens": 21 } } ``` ``` -------------------------------- ### Running System in CLI Mode Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started CLI mode allows direct query execution using the `dev` script. It takes a query string as an argument and executes the full research loop, outputting the final answer to standard output. Various examples demonstrate simple factual queries to complex multi-step research. ```bash # Simple factual query (no tool calling) npm run dev "what is the capital of France?" # 2-step search query npm run dev "what is the latest news from Jina AI?" # 3-step query with search and visit npm run dev "what is the twitter account of jina ai's founder" # Complex multi-step research npm run dev "who will be president of US in 2028?" ``` -------------------------------- ### Running Local Development with Docker Compose (Bash) Source: https://deepwiki.com/jina-ai/node-DeepResearch/10 This bash script illustrates the process of starting the DeepResearch service locally using Docker Compose. It involves setting environment variables (either in a .env file or exported directly) and then executing `docker-compose up --build` to create and run the containers. ```bash # Set environment variables (e.g., in .env file or exported) export GEMINI_API_KEY=your_gemini_key export OPENAI_API_KEY=your_openai_key export JINA_API_KEY=your_jina_key export BRAVE_API_KEY=your_brave_key # Start the service using Docker Compose docker-compose up --build ``` -------------------------------- ### Docker Compose for Development Environment Source: https://deepwiki.com/jina-ai/node-DeepResearch/10-development-guide The docker-compose.yml file sets up a local development environment for the application. It builds the Docker image from the current directory (`.`) and configures essential environment variables for API keys (GEMINI_API_KEY, OPENAI_API_KEY, JINA_API_KEY, BRAVE_API_KEY) which are injected from the host environment. The service exposes port 3000, mapping it to the host's port 3000 for easy access. ```yaml services: app: build: . environment: - GEMINI_API_KEY=${GEMINI_API_KEY} - OPENAI_API_KEY=${OPENAI_API_KEY} - JINA_API_KEY=${JINA_API_KEY} - BRAVE_API_KEY=${BRAVE_API_KEY} ports: - "3000:3000" ``` -------------------------------- ### LLM Provider Configuration - JSON Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Configuration for LLM providers within `config.json` for the DeepResearch application. It specifies how to instantiate clients for different providers like Vertex AI, Gemini, and OpenAI, including necessary factory function names and provider-specific client configurations. ```json { "providers": { "vertex": { "createClient": "createGoogleVertex", "clientConfig": { "location": "us-central1" } }, "gemini": { "createClient": "createGoogleGenerativeAI" }, "openai": { "createClient": "createOpenAI", "clientConfig": { "compatibility": "strict" } } } } ``` -------------------------------- ### Integrate with Vercel AI SDK for DeepResearch Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Shows how to use the Vercel AI SDK to communicate with the DeepResearch API. Similar to the OpenAI SDK, set the baseURL and apiKey. The example focuses on generating text. ```typescript import { createOpenAI } from '@ai-sdk/openai'; import { generateText } from 'ai'; const openai = createOpenAI({ baseURL: 'http://localhost:3000/v1', apiKey: 'your_secret_token' }); const { text } = await generateText({ model: openai('jina-deepsearch-v1'), prompt: 'What is the latest news from Jina AI?' }); ``` -------------------------------- ### General Purpose Docker Build (Node.js) Source: https://deepwiki.com/jina-ai/node-DeepResearch/10 This Dockerfile outlines a general-purpose build for standalone DeepResearch deployments. It utilizes Node.js 20 slim for both build and production stages, incorporates security measures like --ignore-scripts, and installs only production dependencies. ```dockerfile # Example Dockerfile snippet for General Purpose Build FROM node:20-slim AS builder WORKDIR /app COPY package*.json ./ RUN npm install --ignore-scripts COPY . . RUN npm run build FROM node:20-slim WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/package.json ./package.json COPY config.json ./ RUN npm prune --production EXPOSE 3000 CMD [ "node", "dist/server.js" ] ``` -------------------------------- ### Action Tracker Integration Example (TypeScript) Source: https://deepwiki.com/jina-ai/node-DeepResearch/9-advanced-features Demonstrates how the i18n system integrates with the agent's streaming output using the `trackThink` method from the `actionTracker`. ```typescript context.actionTracker.trackThink( 'search_for', // i18n key SchemaGen.languageCode, // detected language { keywords: queries } // parameters ); ``` -------------------------------- ### Configure Environment Variables for DeepResearch Source: https://deepwiki.com/jina-ai/node-DeepResearch/10-development-guide Sets necessary API keys for external services like Gemini, OpenAI, Jina, and Brave through environment variables. The DEFAULT_MODEL_NAME can also be configured. ```shell GEMINI_API_KEY=your_gemini_key OPENAI_API_KEY=your_openai_key JINA_API_KEY=your_jina_key BRAVE_API_KEY=your_brave_key ``` -------------------------------- ### Making Non-Streaming API Request Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started This example demonstrates how to make a non-streaming POST request to the `/v1/chat/completions` endpoint. It includes the necessary headers for content type and authorization, along with a JSON payload containing the model and messages. ```bash curl http://localhost:3000/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your_secret_token" \ -d '{ "model": "jina-deepsearch-v1", "messages": [ { "role": "user", "content": "What is the latest blog post from Jina AI?" } ] }' ``` -------------------------------- ### Question Evaluation Example in TypeScript Source: https://deepwiki.com/jina-ai/node-DeepResearch/6-quality-control-and-evaluation Demonstrates the output of the `evaluateQuestion` function, which analyzes a given question to determine the necessary evaluation types. It shows how a question about bank interest rates is parsed to identify needs for definitive, freshness, and completeness checks. ```typescript /** * Example Question Evaluation */ // Question: "What are the current interest rates from Bank of America, Wells Fargo, and Chase?" // evaluateQuestion() returns: { needsDefinitive: true, // Factual question with verifiable answer needsFreshness: true, // "current" indicates time-sensitivity needsPlurality: false, // Overridden by completeness needsCompleteness: true // Three banks explicitly named } ``` -------------------------------- ### Multi-Stage Docker Build for Node.js Applications Source: https://deepwiki.com/jina-ai/node-DeepResearch/10-development-guide This Dockerfile pattern optimizes build size and security by using separate stages for building and production. The builder stage uses a slim Node.js image for compiling assets, while the production stage uses a minimal Node.js image with only production dependencies. Environment variables for API keys are injected at runtime, and port 3000 is exposed for HTTP API access. The Jina AI variant includes specific configurations for the Jina AI service. ```dockerfile FROM node:22-slim AS builder WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build FROM node:22 WORKDIR /app COPY --from=builder /app/dist ./dist COPY package*.json ./ RUN npm install --only=production ENV NODE_ENV=production EXPOSE 3000 CMD ["node", "dist/server.js"] ``` -------------------------------- ### Docker Production Build Multi-Stage Architecture (Node.js) Source: https://deepwiki.com/jina-ai/node-DeepResearch/10 This snippet illustrates the multi-stage Docker build process for Jina AI production deployments. It uses a 'builder' stage with Node.js 22 slim to compile TypeScript and install dependencies, followed by a 'production' stage based on Node.js 22 for the runtime container, copying built assets and setting environment variables. ```dockerfile # Example Dockerfile snippet for Jina AI Production Build # Stage 1: Builder FROM node:22-slim AS builder WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build # Stage 2: Production FROM node:22 WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/package.json ./package.json ENV NODE_ENV=production EXPOSE 3000 CMD [ "node", "dist/server.js" ] ``` -------------------------------- ### Illustrate Request Flow in TypeScript Source: https://deepwiki.com/jina-ai/node-DeepResearch/index Provides a conceptual outline of the request flow within the DeepResearch application, particularly focusing on the agent's loop and interaction with external services. This example is illustrative and not directly executable code, but demonstrates the sequence of operations for processing a chat completion request. ```typescript // Conceptual flow (not executable code) // Client sends POST to /v1/chat/completions // App.ts validates request, creates TrackerContext, calls getResponse() // Agent initializes state: gaps = [question], allURLs = {}, allKnowledge = [] // Loop iteration 1: // Select currentQuestion from gaps // Generate prompt via getPrompt(), create schema via getAgentSchema() // LLM decides action: search // Execute executeSearchQueries() → updates allURLs // Loop iteration 2: // LLM decides action: visit // Execute processURLs() → updates allKnowledge, allWebContents // Loop iteration 3: // LLM decides action: answer // Execute evaluateAnswer() → checks all evaluation types // If pass: break loop // Finalization: // finalizeAnswer() improves answer quality // buildReferences() matches citations to content // buildImageReferences() if withImages=true // Response returned with markdown answer, references, and metadata ``` -------------------------------- ### Python OpenAI SDK Client Integration Source: https://deepwiki.com/jina-ai/node-DeepResearch/9 Example demonstrating how to use the OpenAI Python SDK to interact with the DeepResearch API, handling different delta types ('think', 'text') received in the streaming response. ```python from openai import OpenAI client = OpenAI( base_url="http://localhost:3000/v1", api_key="your_secret_token" ) stream = client.chat.completions.create( model="jina-deepsearch-v1", messages=[{"role": "user", "content": "What is the latest from Jina AI?"}], stream=True ) for chunk in stream: delta = chunk.choices[0].delta # Handle different delta types if hasattr(delta, 'type'): if delta.type == 'think': # Reasoning step if hasattr(delta, 'query'): print(f"[Query] {delta.query}") elif hasattr(delta, 'url'): print(f"[Visit] {delta.url}") elif hasattr(delta, 'content'): print(delta.content, end='', flush=True) elif delta.type == 'text': # Final answer print(f"\n\n{delta.content}") ``` -------------------------------- ### Environment Variables Configuration - JSON Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Defines environment variables within the `config.json` file for the DeepResearch application. These variables, such as proxy settings and API keys, are initially empty and can be overridden at runtime via actual environment variables or `.env` files. Validation of these variables occurs at application startup. ```json { "env": { "https_proxy": "", "OPENAI_BASE_URL": "", "GEMINI_API_KEY": "", "OPENAI_API_KEY": "", "JINA_API_KEY": "", "BRAVE_API_KEY": "", "SERPER_API_KEY": "", "DEFAULT_MODEL_NAME": "" } } ``` -------------------------------- ### Late Chunking Options and Function Call (TypeScript) Source: https://deepwiki.com/jina-ai/node-DeepResearch/5 Demonstrates how to configure and use the 'cherryPick' function for late chunking. It shows setting snippet length, the number of snippets to extract, and the chunk size for embedding. The example illustrates passing these options to 'cherryPick' for customized content processing. ```typescript const options = { snippetLength: 6000, // Chars per snippet numSnippets: 3, // Number of snippets to extract chunkSize: 300, // Chars per chunk for embedding }; const result = await cherryPick(question, longContext, options, trackers, schemaGen, url); ``` -------------------------------- ### Internationalization Data Example (JSON) Source: https://deepwiki.com/jina-ai/node-DeepResearch/9-advanced-features An example of the i18n JSON structure used for managing language support, including keys for dynamic message generation and parameter substitution. ```json { // ... other language configurations ... } ``` -------------------------------- ### Example Test for Streaming in DeepResearch Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started An example test case written in Jest to verify the streaming functionality of the DeepResearch API. It checks for a 200 status code and the correct 'text/event-stream' content type. ```javascript it('should handle streaming request and track tokens correctly', async () => { const response = await request(app) .post('/v1/chat/completions') .set('Authorization', `Bearer ${TEST_SECRET}`) .send({ model: 'test-model', messages: [{ role: 'user', content: 'test' }], stream: true }); expect(response.status).toBe(200); expect(response.headers['content-type']).toBe('text/event-stream'); // ... verify chunk format }); ``` -------------------------------- ### Configuration Summary Logging Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 This JavaScript object represents a system configuration summary that is logged at startup. It includes details about the LLM provider, search provider, tool configurations, and default settings like step sleep duration. It also shows provider-specific details like the OpenAI baseURL. ```JavaScript const configSummary = { provider: { name: LLM_PROVIDER, model: /* provider default model */, baseUrl: OPENAI_BASE_URL // if OpenAI }, search: { provider: SEARCH_PROVIDER }, tools: /* all tool configurations */, defaults: { stepSleep: STEP_SLEEP } }; ``` -------------------------------- ### Default LLM Provider Override - TypeScript Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Example of overriding the default LLM provider in TypeScript using an environment variable. The DeepResearch application respects the `LLM_PROVIDER` environment variable, which can change the default LLM provider set in the configuration. ```typescript const llmProvider = process.env.LLM_PROVIDER || config.defaults.llm_provider; ``` -------------------------------- ### Unicode Repair Function Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/9-advanced-features Shows the usage of the `repairUnknownChars()` function, which employs LLM-based repair for content with encoding issues. ```typescript // Usage of repairUnknownChars() for LLM-based Unicode repair. ``` -------------------------------- ### Create Configured Model Instance using getModel() Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 The `getModel()` function dynamically creates and returns a configured AI model instance based on the specified tool name. It handles provider-specific configurations, including compatibility settings and custom base URLs for OpenAI, and requires optional dependencies and project IDs for Vertex AI. ```TypeScript import { getModel } from './config'; // In evaluator tool const model = getModel('evaluator'); const result = await generateObject({ model, schema: evaluationSchema, prompt: evaluationPrompt, // temperature and maxTokens are already configured }); ``` -------------------------------- ### Get Max Tokens Function Signature Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Defines the signature for the `getMaxTokens` function, a utility that extracts only the `maxTokens` value from a tool's configuration. ```typescript function getMaxTokens(toolName: ToolName): number ``` -------------------------------- ### Retry Counter Management in TypeScript Source: https://deepwiki.com/jina-ai/node-DeepResearch/6-quality-control-and-evaluation Shows how retry opportunities are managed for different evaluation types. Each evaluation starts with a `maxBadAttempts` count, and the strict evaluation is added specifically for original questions. ```typescript // Retry Counter Management // Each evaluation type starts with `maxBadAttempts` (typically 2) retry opportunities: // Initial setup (line 532-541) evaluationMetrics[currentQuestion] = (await evaluateQuestion(currentQuestion, context, SchemaGen)) .map(e => ({ type: e, numEvalsRequired: maxBadAttempts })); // Add strict evaluation for original question only evaluationMetrics[currentQuestion].push({ type: 'strict', numEvalsRequired: maxBadAttempts }); ``` -------------------------------- ### Log Configuration Summary (TypeScript) Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 At application startup, the configuration system logs a comprehensive summary of the active configuration. This log includes details about providers, search configurations, tools, and default settings, aiding in debugging and environment verification. The code is located in src/config.ts. ```typescript { provider: { name: 'gemini', model: 'gemini-2.5-flash' }, search: { provider: 'jina' }, tools: { agent: { model: 'gemini-2.5-flash', temperature: 0.7, maxTokens: 2000 }, evaluator: { model: 'gemini-2.5-flash', temperature: 0.6, maxTokens: 200 } // ... all tools }, defaults: { stepSleep: 1 } } ``` -------------------------------- ### DeepResearch API Request Example Source: https://deepwiki.com/jina-ai/node-DeepResearch/9-advanced-features Demonstrates a typical API request to the DeepResearch service, specifying the model, user message, and team size for parallel processing. ```json { "model": "jina-deepsearch-v1", "messages": [ { "role": "user", "content": "Compare the economic policies of France, Germany, and Italy in 2024" } ], "team_size": 3 } ``` -------------------------------- ### Extracting Jina AI's Dockerfile Source: https://deepwiki.com/jina-ai/node-DeepResearch/10-development-guide This code snippet is extracted from the Dockerfile used by jina-ai, likely for building their Docker images. It specifies the build process for the container. ```dockerfile FROM jinaai/jina:latest # Copy your application code COPY . /app WORKDIR /app # Install dependencies RUN pip install -r requirements.txt # Expose port and set entrypoint EXPOSE 8000 CMD ["python", "app.py"] ``` -------------------------------- ### CLI Mode: Direct Query Execution Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Instructions on how to run DeepResearch directly from the command line using the `dev` script for single queries. ```APIDOC ## CLI Mode: Direct Query Execution DeepResearch can be run directly from your terminal using the `dev` script, which is defined in `package.json`. This mode is suitable for executing single research queries. ### Command: ```bash npm run dev "your question here" ``` ### Example Queries: * **Simple factual query:** ```bash npm run dev "what is the capital of France?" ``` * **2-step search query:** ```bash npm run dev "what is the latest news from Jina AI?" ``` * **3-step query with search and visit:** ```bash npm run dev "what is the twitter account of jina ai's founder" ``` * **Complex multi-step research:** ```bash npm run dev "who will be president of US in 2028?" ``` ### Execution Flow: The CLI mode directly invokes `src/agent.ts`, which serves as the main entry point. The agent then executes the complete research loop and outputs the final answer directly to the standard output (stdout). ``` -------------------------------- ### Get Tool Configuration Function Signature Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Defines the signature for the `getToolConfig` function, which retrieves the complete configuration for a specified tool by merging provider defaults with tool-specific overrides. ```typescript function getToolConfig(toolName: ToolName): ToolConfig ``` -------------------------------- ### Tool Configuration Parameters Source: https://deepwiki.com/jina-ai/node-DeepResearch/7 Defines the parameters available for configuring individual tools, including the model identifier, generation temperature, and maximum output tokens. These parameters allow for fine-tuning tool behavior. ```markdown Parameter| Type| Purpose| Typical Range ---|---|---|--- `model`| `string`| Model identifier (e.g., `gemini-2.5-flash`, `gpt-4o-mini`)| Provider-specific `temperature`| `number`| Randomness in generation (0=deterministic, 1=creative)| 0.0 - 1.0 `maxTokens`| `number`| Maximum output token limit| 200 - 16000 ``` -------------------------------- ### Run DeepResearch Test Suite Commands Source: https://deepwiki.com/jina-ai/node-DeepResearch/2-getting-started Provides various commands to execute the test suite for the DeepResearch project. Includes options for running all tests, running in watch mode, and running Docker-specific tests. ```bash # Run all tests npm test # Run tests in watch mode npm run test:watch # Run Docker-specific tests npm run test:docker ```