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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ The project is named after the folder, which must belong to a git working tree.

## Local-first by design

Previewing, parsing, searching and the pi agent loop run in the browser. A connected source can also hold your documents on disk or in a repository. AI inference runs at the model provider: on the shared allowance through a Node proxy that holds the credentials but stores no conversation content, and with a reader's own key straight from the browser. Web search queries go through the server to Tavily. See [Your data and models](tutorial/guide/Your%20data%20and%20models.md) for what leaves the browser.
Previewing, parsing, searching and the pi agent loop run in the browser. A connected source can also hold your documents on disk or in a repository. AI inference runs at the model provider: on the shared allowance through a Node proxy that holds the credentials but stores no conversation content, and with a reader's own key straight from the browser. Web search queries go through the server to Tavily, or to DeepSeek where the deployment names it. See [Your data and models](tutorial/guide/Your%20data%20and%20models.md) for what leaves the browser.

![Browser storage, local tools, and the two routes to a model provider](tutorial/examples/How%20Gamma%20Reader%20works.svg)

Expand Down
1 change: 1 addition & 0 deletions compose.production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ services:
GLM_API_KEY: ${GLM_API_KEY:-}
DEEPSEEK_API_KEY: ${DEEPSEEK_API_KEY:-}
TAVILY_API_KEY: ${TAVILY_API_KEY:-}
GAMMA_SEARCH_PROVIDER: ${GAMMA_SEARCH_PROVIDER:-}
GAMMA_SEARCH_PROXY: ${GAMMA_SEARCH_PROXY:-}
GAMMA_PLUGINS_URL: ${GAMMA_PLUGINS_URL:-}
GAMMA_DATA_DIR: /data
Expand Down
3 changes: 2 additions & 1 deletion docs/self-hosting.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ The following are server defaults. npx uses them too, except that `GAMMA_DATA_DI
| --- | --- | --- |
| `GLM_API_KEY` | Unset | Server-side credential for Z.AI Coding CN |
| `DEEPSEEK_API_KEY` | Unset | Server-side credential for DeepSeek |
| `GAMMA_SEARCH_PROVIDER` | `tavily` | The web search service: `tavily`, or `deepseek` to search and read pages with `DEEPSEEK_API_KEY` |
| `TAVILY_API_KEY` | Unset | Server-side credential for Tavily; when set, the chat offers a web search switch |
| `GAMMA_SEARCH_PROXY` | Unset | HTTP proxy for web search requests only, such as `http://172.17.0.1:1080` |
| `GAMMA_SEARCH_PROXY` | Unset | HTTP proxy for Tavily requests only, such as `http://172.17.0.1:1080` |
| `GAMMA_PLUGINS_URL` | Unset | A plugin app the reader offers, such as `https://plugins.example.com`; see [Plugins](plugins.md) |
| `PORT` | `3302` | Node service port |
| `HOST` | `127.0.0.1` | Node service host |
Expand Down
30 changes: 21 additions & 9 deletions web-packages/server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ import { publishing } from './source/publish.js'
import { openRepository, type Source } from './source/repository.js'
import { openWorkingTree } from './source/working-tree.js'
import { readSourceConfig, type SourceConfig } from './source-config.js'
import { tavilyExtract, tavilySearch } from './web-search/provider.js'
import {
deepseekExtract,
deepseekSearch,
tavilyExtract,
tavilySearch,
} from './web-search/provider.js'
import type { WebServices } from './web-search/routes.js'

const port = Number(process.env.PORT ?? 3302)
if (!Number.isInteger(port) || port < 1 || port > 65535) {
Expand All @@ -35,14 +41,20 @@ if (webRoot) {
}

const hostname = process.env.HOST ?? '127.0.0.1'
const tavilyKey = process.env.TAVILY_API_KEY?.trim()
const searchProxy = process.env.GAMMA_SEARCH_PROXY?.trim() || undefined
const web = tavilyKey
? {
search: tavilySearch(tavilyKey, searchProxy),
extract: tavilyExtract(tavilyKey, searchProxy),
}
: undefined
// Tavily unless the deployment names DeepSeek, which then searches with the chat's own key.
const webServices = (): WebServices | undefined => {
const provider = process.env.GAMMA_SEARCH_PROVIDER?.trim() || 'tavily'
if (provider === 'deepseek') {
const key = process.env.DEEPSEEK_API_KEY?.trim()
if (!key) throw new Error('GAMMA_SEARCH_PROVIDER=deepseek needs DEEPSEEK_API_KEY')
return { search: deepseekSearch(key), extract: deepseekExtract(key) }
}
if (provider !== 'tavily') throw new Error('GAMMA_SEARCH_PROVIDER must be tavily or deepseek')
const key = process.env.TAVILY_API_KEY?.trim()
const proxy = process.env.GAMMA_SEARCH_PROXY?.trim() || undefined
return key ? { search: tavilySearch(key, proxy), extract: tavilyExtract(key, proxy) } : undefined
}
const web = webServices()
// A plugin app this deployment trusts: its tool descriptions reach the model as they are.
const pluginsUrl = process.env.GAMMA_PLUGINS_URL?.trim()
if (pluginsUrl && !/^https?:$/.test(URL.parse(pluginsUrl)?.protocol ?? '')) {
Expand Down
58 changes: 57 additions & 1 deletion web-packages/server/src/web-search/provider.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { tavilyExtract, tavilySearch } from './provider.js'
import { deepseekExtract, deepseekSearch, tavilyExtract, tavilySearch } from './provider.js'

afterEach(() => vi.restoreAllMocks())

Expand Down Expand Up @@ -76,3 +76,59 @@ describe('Tavily search', () => {
await expect(extract('https://example.org/b', signal)).rejects.toThrow('could not extract')
})
})

describe('DeepSeek search', () => {
it('asks with a query cut to its limit, and keeps the summary meant for a model', async () => {
const fetchSearch = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
Response.json({
results: [
{
url: 'https://example.org/news',
title: 'News',
snippet: 'Short',
summary: 'Longer summary',
date: '2026-10-17T00:00:00Z',
rerank_score: 2,
},
{ url: 'https://example.org/short', title: 'Short only', snippet: 'Short', summary: '' },
{ title: 'No link', summary: 'Dropped' },
],
}),
)

const hits = await deepseekSearch('sk-key')('读'.repeat(200), 3, new AbortController().signal)

const [url, init] = fetchSearch.mock.calls[0] ?? []
expect(url).toBe('https://api.deepseek.com/v1/tools/search')
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer sk-key')
expect(JSON.parse(String(init?.body))).toEqual({ query: '读'.repeat(128), count: 3 })
expect(hits).toEqual([
{
title: 'News',
url: 'https://example.org/news',
published: '2026-10-17T00:00:00Z',
snippet: 'Longer summary',
},
{ title: 'Short only', url: 'https://example.org/short', snippet: 'Short' },
])
})

it('reads a page as Markdown and fails when DeepSeek could not', async () => {
const fetchPage = vi
.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ title: 'A', content: '# A\n\nText' }))
.mockResolvedValueOnce(new Response('{}', { status: 404 }))
const extract = deepseekExtract('sk-key')
const signal = new AbortController().signal

expect(await extract('https://example.org/a', signal)).toEqual({
url: 'https://example.org/a',
title: 'A',
content: '# A\n\nText',
})
const [url, init] = fetchPage.mock.calls[0] ?? []
expect(url).toBe('https://api.deepseek.com/v1/tools/fetch')
expect(JSON.parse(String(init?.body))).toEqual({ url: 'https://example.org/a' })
await expect(extract('https://example.org/b', signal)).rejects.toThrow('DeepSeek answered 404')
})
})
96 changes: 78 additions & 18 deletions web-packages/server/src/web-search/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,29 @@ const tavilyHit = (result: TavilyResult): SearchHit[] =>
]
: []

// Calls Tavily, through an HTTP proxy when one is given; only Tavily traffic takes it.
const tavilyClient = (apiKey: string, proxy?: string) => {
// Posts to a search service, through an HTTP proxy when one is given; only that service's
// traffic takes it.
const serviceClient = (service: string, base: string, apiKey: string, proxy?: string) => {
const dispatcher = proxy ? new ProxyAgent(proxy) : undefined
return async (endpoint: 'search' | 'extract', body: object, signal: AbortSignal) => {
return async (endpoint: string, body: object, signal: AbortSignal) => {
const init = {
method: 'POST',
signal,
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}
const url = `https://api.tavily.com/${endpoint}`
const url = `${base}/${endpoint}`
const response = dispatcher
? await proxiedFetch(url, { ...init, dispatcher })
: await fetch(url, init)
if (!response.ok) throw new Error(`Tavily answered ${response.status}`)
if (!response.ok) throw new Error(`${service} answered ${response.status}`)
return (await response.json()) as Record<string, unknown>
}
}

const tavilyClient = (apiKey: string, proxy?: string) =>
serviceClient('Tavily', 'https://api.tavily.com', apiKey, proxy)

export const tavilySearch = (apiKey: string, proxy?: string): SearchProvider => {
const call = tavilyClient(apiKey, proxy)
return async (query, count, signal) => {
Expand Down Expand Up @@ -75,6 +79,25 @@ const fromTitle = (content: string) => {
return title > 0 && title < lines.length * 0.3 ? lines.slice(title).join('\n') : content
}

const extractedPage = (
service: string,
url: string,
title: unknown,
raw: unknown,
): ExtractedPage => {
if (typeof raw !== 'string' || !raw.trim())
throw new Error(`${service} could not extract the page.`)
const content = fromTitle(raw)
return {
url,
...(typeof title === 'string' && title.trim() && { title: title.trim() }),
content:
content.length > maximumPageCharacters
? `${content.slice(0, maximumPageCharacters)}\n\n… The rest of the page was left out.`
: content,
}
}

export const tavilyExtract = (apiKey: string, proxy?: string): PageExtractor => {
const call = tavilyClient(apiKey, proxy)
return async (url, signal) => {
Expand All @@ -86,18 +109,55 @@ export const tavilyExtract = (apiKey: string, proxy?: string): PageExtractor =>
const page = Array.isArray(body.results) ? body.results[0] : undefined
const fields =
typeof page === 'object' && page !== null ? (page as Record<string, unknown>) : {}
const raw = fields.raw_content
if (typeof raw !== 'string' || !raw.trim())
throw new Error('Tavily could not extract the page.')
const content = fromTitle(raw)
return {
url,
...(typeof fields.title === 'string' &&
fields.title.trim() && { title: fields.title.trim() }),
content:
content.length > maximumPageCharacters
? `${content.slice(0, maximumPageCharacters)}\n\n… The rest of the page was left out.`
: content,
}
return extractedPage('Tavily', url, fields.title, fields.raw_content)
}
}

const deepseekClient = (apiKey: string) =>
serviceClient('DeepSeek', 'https://api.deepseek.com/v1/tools', apiKey)

type DeepseekResult = {
url?: unknown
title?: unknown
summary?: unknown
snippet?: unknown
date?: unknown
}

const text = (value: unknown) => (typeof value === 'string' ? value : '')

// The summary is written for a model; the snippet, a line for a results page, stands in for it.
const deepseekHit = (result: DeepseekResult): SearchHit[] =>
typeof result.url === 'string' && typeof result.title === 'string'
? [
{
title: result.title,
url: result.url,
...(typeof result.date === 'string' && { published: result.date }),
snippet: snippet(text(result.summary) || text(result.snippet)),
},
]
: []

// DeepSeek refuses a query longer than this, so a longer one is cut instead.
const maximumDeepseekQuery = 128

export const deepseekSearch = (apiKey: string): SearchProvider => {
const call = deepseekClient(apiKey)
return async (query, count, signal) => {
const shortened = Array.from(query).slice(0, maximumDeepseekQuery).join('').trim()
const body = await call('search', { query: shortened, count }, signal)
if (!Array.isArray(body.results)) return []
return body.results.flatMap((result: unknown) =>
typeof result === 'object' && result !== null ? deepseekHit(result as DeepseekResult) : [],
)
}
}

export const deepseekExtract = (apiKey: string): PageExtractor => {
const call = deepseekClient(apiKey)
return async (url, signal) => {
const body = await call('fetch', { url }, signal)
return extractedPage('DeepSeek', url, body.title, body.content)
}
}