Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,17 +68,20 @@ It is also available on npm but not recommended for now, as the code is still un

## Usage

We use Gemini (latest `gemini-2.0-flash`) / OpenAI / [LocalLLM](#use-local-llm) for reasoning, [Jina Reader](https://jina.ai/reader) for searching and reading webpages, you can get a free API key with 1M tokens from jina.ai.
We use Gemini (latest `gemini-2.0-flash`) / OpenAI / [LocalLLM](#use-local-llm) for reasoning, [Jina Reader](https://jina.ai/reader) for searching and reading webpages, you can get a free API key with 1M tokens from jina.ai. Tavily Search is also available as an optional search provider.

```bash
export GEMINI_API_KEY=... # for gemini
# export OPENAI_API_KEY=... # for openai
# export LLM_PROVIDER=openai # for openai
export JINA_API_KEY=jina_... # free jina api key, get from https://jina.ai/reader
# export TAVILY_API_KEY=... # use with search_provider: tavily

npm run dev $QUERY
```

Set `"search_provider": "tavily"` in `config.json` to select Tavily. Its daily, weekly, monthly, and yearly freshness filters are supported; hourly freshness uses Tavily's normal search behavior.

### Official Site

You can try it on [our official site](https://search.jina.ai).
Expand Down
1 change: 1 addition & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"JINA_API_KEY": "",
"BRAVE_API_KEY": "",
"SERPER_API_KEY": "",
"TAVILY_API_KEY": "",
"DEFAULT_MODEL_NAME": ""
},
"defaults": {
Expand Down
9 changes: 9 additions & 0 deletions src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { zodToJsonSchema } from "zod-to-json-schema";
import { ObjectGeneratorSafe } from "./utils/safe-generator";
import { CodeSandbox } from "./tools/code-sandbox";
import { serperSearch } from './tools/serper-search';
import { tavilySearch } from './tools/tavily-search';
import {
addToAllURLs,
rankURLs,
Expand Down Expand Up @@ -317,6 +318,14 @@ async function executeSearchQueries(
case 'serper':
results = (await serperSearch(query)).response.organic || [];
break;
case 'tavily':
results = (await tavilySearch(query, context.tokenTracker)).response.results.map(result => ({
title: result.title,
url: result.url,
description: result.content,
date: result.published_date,
}));
break;
default:
results = [];
}
Expand Down
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const OPENAI_API_KEY = env.OPENAI_API_KEY;
export const JINA_API_KEY = env.JINA_API_KEY;
export const BRAVE_API_KEY = env.BRAVE_API_KEY;
export const SERPER_API_KEY = env.SERPER_API_KEY;
export const TAVILY_API_KEY = env.TAVILY_API_KEY;
export const SEARCH_PROVIDER = configJson.defaults.search_provider;
export const STEP_SLEEP = configJson.defaults.step_sleep;

Expand Down
70 changes: 70 additions & 0 deletions src/tools/__tests__/tavily-search.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import axiosClient from '../../utils/axios-client';
import { TokenTracker } from '../../utils/token-tracker';
import { tavilySearch } from '../tavily-search';

jest.mock('../../config', () => ({
TAVILY_API_KEY: 'tavily-test-key',
}));

jest.mock('../../utils/axios-client', () => ({
post: jest.fn(),
}));

describe('tavilySearch', () => {
const post = axiosClient.post as jest.Mock;

beforeEach(() => {
post.mockReset();
});

it('sends a compatible request and returns Tavily results', async () => {
post.mockResolvedValue({
data: {
query: 'latest research',
results: [{
title: 'Research result',
url: 'https://example.com/research',
content: 'A useful result',
score: 0.9,
published_date: '2024-01-02',
}],
usage: { credits: 1 },
},
});
const tracker = new TokenTracker();

const result = await tavilySearch({ q: 'latest research', tbs: 'qdr:w' }, tracker);

expect(post).toHaveBeenCalledWith(
'https://api.tavily.com/search',
expect.objectContaining({
query: 'latest research',
max_results: 20,
time_range: 'w',
include_answer: false,
include_raw_content: false,
}),
expect.objectContaining({
headers: expect.objectContaining({
Authorization: 'Bearer tavily-test-key',
}),
}),
);
expect(result.response.results[0].url).toBe('https://example.com/research');
expect(tracker.getTotalUsage().totalTokens).toBe(1);
});

it('omits unsupported freshness ranges', async () => {
post.mockResolvedValue({ data: { results: [] } });

await tavilySearch({ q: 'recent research', tbs: 'qdr:h' });

expect(post.mock.calls[0][1]).not.toHaveProperty('time_range');
});

it('rejects malformed responses', async () => {
post.mockResolvedValue({ data: { results: null } });

await expect(tavilySearch({ q: 'research' })).rejects.toThrow('Invalid Tavily search response');
});
});
64 changes: 64 additions & 0 deletions src/tools/tavily-search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { TAVILY_API_KEY } from '../config';
import { SERPQuery, TavilySearchResponse } from '../types';
import axiosClient from '../utils/axios-client';
import { TokenTracker } from '../utils/token-tracker';

const TAVILY_SEARCH_URL = 'https://api.tavily.com/search';

const timeRangeByTbs: Record<string, string> = {
'qdr:d': 'd',
'qdr:w': 'w',
'qdr:m': 'm',
'qdr:y': 'y',
};

export async function tavilySearch(
query: SERPQuery,
tracker?: TokenTracker,
): Promise<{ response: TavilySearchResponse }> {
if (!query.q.trim()) {
throw new Error('Search query cannot be empty');
}

if (!TAVILY_API_KEY) {
throw new Error('TAVILY_API_KEY not found');
}

const payload: Record<string, unknown> = {
query: query.q,
search_depth: 'basic',
max_results: 20,
include_answer: false,
include_raw_content: false,
include_usage: true,
};

const timeRange = query.tbs ? timeRangeByTbs[query.tbs] : undefined;
if (timeRange) {
payload.time_range = timeRange;
}

const { data } = await axiosClient.post<TavilySearchResponse>(TAVILY_SEARCH_URL, payload, {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${TAVILY_API_KEY}`,
'Content-Type': 'application/json',
},
timeout: 30000,
});

if (!data || !Array.isArray(data.results)) {
throw new Error('Invalid Tavily search response');
}

const credits = data.usage?.credits || 0;
if (tracker && credits > 0) {
tracker.trackUsage('search', {
totalTokens: credits,
promptTokens: credits,
completionTokens: 0,
});
}

return { response: data };
}
14 changes: 14 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,20 @@ export interface SerperSearchResponse {
credits: number;
}

export interface TavilySearchResponse {
query: string;
results: Array<{
title: string;
url: string;
content: string;
score: number;
published_date?: string;
}>;
usage?: {
credits?: number;
};
}


export interface ReadResponse {
code: number;
Expand Down