Skip to content
Merged
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: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ EMBEDDING_PROVIDER=ollama node /path/to/codebase-context/dist/index.js reindex -

Native Ollama uses `http://localhost:11434` by default. Set `OLLAMA_HOST` to use a different server. This provider needs LanceDB storage and uses Ollama's native API without an API key. To use the OpenAI API or a compatible endpoint instead, set `EMBEDDING_PROVIDER=openai` and `OPENAI_API_KEY`. Set `OPENAI_BASE_URL` to the compatible API base, including `/v1` where required.

Each Ollama request has a 120-second deadline. Set `OLLAMA_REQUEST_TIMEOUT_MS` to a positive integer in milliseconds to change it. For programmatic indexing, `embedding.requestTimeoutMs` takes precedence over the environment variable.

Your AI client may send returned code to its own model provider; CBC does not control that connection. Project memory also travels with the repository if you commit and push it.

Generated index data should stay out of version control. To share project memory while ignoring the generated index:
Expand Down
9 changes: 6 additions & 3 deletions src/embeddings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
DEFAULT_EMBEDDING_CONFIG,
resolveDefaultApiEndpoint,
resolveEmbeddingModel,
resolveEmbeddingProvider
resolveEmbeddingProvider,
resolveOllamaRequestTimeoutMs
} from './types.js';
import { TransformersEmbeddingProvider, MODEL_CONFIGS } from './transformers.js';
import { getOllamaModelDimensions, OllamaEmbeddingProvider } from './ollama.js';
Expand Down Expand Up @@ -46,7 +47,9 @@ export async function getEmbeddingProvider(
const model = config.model || resolveEmbeddingModel(providerName);
const apiEndpoint = config.apiEndpoint ?? resolveDefaultApiEndpoint(providerName);
const { apiKey = DEFAULT_EMBEDDING_CONFIG.apiKey } = config;
const providerKey = JSON.stringify([providerName, model, apiEndpoint, apiKey]);
const requestTimeoutMs =
providerName === 'ollama' ? resolveOllamaRequestTimeoutMs(config.requestTimeoutMs) : undefined;
const providerKey = JSON.stringify([providerName, model, apiEndpoint, apiKey, requestTimeoutMs]);

if (cachedProvider && cachedProviderKey === providerKey) {
return cachedProvider;
Expand All @@ -61,7 +64,7 @@ export async function getEmbeddingProvider(
const { OpenAIEmbeddingProvider } = await import('./openai.js');
provider = new OpenAIEmbeddingProvider(model, apiKey, apiEndpoint);
} else if (providerName === 'ollama') {
provider = new OllamaEmbeddingProvider(model, apiEndpoint);
provider = new OllamaEmbeddingProvider(model, apiEndpoint, requestTimeoutMs);
} else {
provider = new TransformersEmbeddingProvider(model);
}
Expand Down
94 changes: 49 additions & 45 deletions src/embeddings/ollama.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EmbeddingProvider } from './types.js';
import { EmbeddingProvider, resolveOllamaRequestTimeoutMs } from './types.js';

/** Common Ollama embedding models and their vector sizes (for LanceDB dimension checks). */
export const OLLAMA_MODEL_DIMENSIONS: Record<string, number> = {
Expand Down Expand Up @@ -49,13 +49,16 @@ export function getOllamaModelDimensions(modelName: string): number {
export class OllamaEmbeddingProvider implements EmbeddingProvider {
readonly name = 'ollama';
private resolvedDimensions: number;
private readonly requestTimeoutMs: number;
private ready = false;

constructor(
readonly modelName: string,
private host: string = 'http://localhost:11434'
private host: string = 'http://localhost:11434',
requestTimeoutMs?: number
) {
this.host = normalizeOllamaHost(host);
this.requestTimeoutMs = resolveOllamaRequestTimeoutMs(requestTimeoutMs);
this.resolvedDimensions = getOllamaModelDimensions(modelName);
}

Expand All @@ -65,31 +68,7 @@ export class OllamaEmbeddingProvider implements EmbeddingProvider {

async initialize(): Promise<void> {
this.ready = false;
let response: Response;
try {
response = await fetch(`${this.host}/api/show`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: this.modelName })
});
} catch (error) {
throw new Error(
`Cannot reach Ollama at ${this.host}. Start the server (ollama serve) or set OLLAMA_HOST. ${String(error)}`
);
}

if (response.status === 404) {
throw new Error(
`Ollama model "${this.modelName}" is not available. Pull it first: ollama pull ${this.modelName}`
);
}

if (!response.ok) {
const error = await response.text();
throw new Error(`Ollama API Error ${response.status}: ${error}`);
}

const show = (await response.json()) as OllamaShowResponse;
const show = (await this.request('/api/show', { name: this.modelName })) as OllamaShowResponse;
const embeddingLength = parseEmbeddingLengthFromShow(show);
if (embeddingLength !== undefined) {
this.resolvedDimensions = embeddingLength;
Expand All @@ -110,39 +89,64 @@ export class OllamaEmbeddingProvider implements EmbeddingProvider {
if (!texts.length) return [];

try {
const response = await fetch(`${this.host}/api/embed`, {
const data = (await this.request('/api/embed', {
model: this.modelName,
input: texts.length === 1 ? texts[0] : texts
})) as OllamaEmbedResponse;
if (!Array.isArray(data.embeddings) || data.embeddings.length !== texts.length) {
throw new Error(
`Ollama returned ${data.embeddings?.length ?? 0} embeddings for ${texts.length} inputs`
);
}

if (data.embeddings[0]?.length && data.embeddings[0].length !== this.resolvedDimensions) {
this.resolvedDimensions = data.embeddings[0].length;
}

return data.embeddings;
} catch (error) {
console.error('Ollama Embedding Failed:', error);
throw error;
}
}
private async request(
path: '/api/show' | '/api/embed',
body: Record<string, string | string[]>
): Promise<unknown> {
const url = `${this.host}${path}`;
const signal = AbortSignal.timeout(this.requestTimeoutMs);
let response: Response | undefined;
try {
response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: this.modelName,
input: texts.length === 1 ? texts[0] : texts
})
body: JSON.stringify(body),
signal
});

if (!response.ok) {
const error = await response.text();
if (response.status === 404 && error.includes('not found')) {
const missingOnShow = response.status === 404 && path === '/api/show';
const error = missingOnShow ? '' : await response.text();
if (missingOnShow || (response.status === 404 && error.includes('not found'))) {
throw new Error(
`Ollama model "${this.modelName}" is not available. Pull it first: ollama pull ${this.modelName}`
);
}
throw new Error(`Ollama API Error ${response.status}: ${error}`);
}

const data = (await response.json()) as OllamaEmbedResponse;
if (!Array.isArray(data.embeddings) || data.embeddings.length !== texts.length) {
return await response.json();
} catch (error) {
if (signal.aborted) {
throw new Error(`Ollama request to ${url} timed out after ${this.requestTimeoutMs} ms`, {
cause: error
});
}
if (!response && path === '/api/show') {
throw new Error(
`Ollama returned ${data.embeddings?.length ?? 0} embeddings for ${texts.length} inputs`
`Cannot reach Ollama at ${this.host}. Start the server (ollama serve) or set OLLAMA_HOST. ${String(error)}`
);
}

if (data.embeddings[0]?.length && data.embeddings[0].length !== this.resolvedDimensions) {
this.resolvedDimensions = data.embeddings[0].length;
}

return data.embeddings;
} catch (error) {
console.error('Ollama Embedding Failed:', error);
throw error;
}
}
Expand Down
16 changes: 16 additions & 0 deletions src/embeddings/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface EmbeddingConfig {
maxRetries?: number;
apiKey?: string;
apiEndpoint?: string;
requestTimeoutMs?: number;
}

export function parseEmbeddingProviderName(
Expand Down Expand Up @@ -44,6 +45,8 @@ export const DEFAULT_MODEL = process.env.EMBEDDING_MODEL || DEFAULT_TRANSFORMERS

const DEFAULT_OPENAI_API_ENDPOINT = 'https://api.openai.com/v1';
const DEFAULT_OLLAMA_HOST = 'http://localhost:11434';
const DEFAULT_OLLAMA_REQUEST_TIMEOUT_MS = 120_000;
const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;

function stripTrailingSlashes(value: string): string {
return value.replace(/\/+$/, '');
Expand All @@ -65,6 +68,19 @@ export function resolveOllamaHost(): string {
return stripTrailingSlashes(fromEnv);
}

export function resolveOllamaRequestTimeoutMs(configured?: number): number {
const timeoutMs = configured ?? Number(process.env.OLLAMA_REQUEST_TIMEOUT_MS);
if (Number.isInteger(timeoutMs) && timeoutMs > 0 && timeoutMs <= MAX_TIMER_DELAY_MS) {
return timeoutMs;
}
if (configured !== undefined) {
throw new RangeError(
`Ollama requestTimeoutMs must be an integer from 1 to ${MAX_TIMER_DELAY_MS}`
);
}
return DEFAULT_OLLAMA_REQUEST_TIMEOUT_MS;
Comment on lines +71 to +81

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Timeout settings lack edge-case tests

resolveOllamaRequestTimeoutMs adds three untested behaviors: the 120-second default, fallback for invalid environment values, and rejection of invalid explicit values. The new tests use only valid overrides.

Add table-driven tests for unset values, zero, negative numbers, fractions, non-numbers, and the timer limit. These would catch changes that silently alter the deadline or let an invalid delay reach AbortSignal.timeout.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

}

export function resolveEmbeddingModel(
provider: EmbeddingConfig['provider'],
envModel: string | undefined = process.env.EMBEDDING_MODEL
Expand Down
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,7 @@ export interface CodebaseConfig {
provider?: 'transformers' | 'openai' | 'ollama' | 'custom';
model?: string;
batchSize?: number;
requestTimeoutMs?: number;
};

// Optimization flags
Expand Down
16 changes: 16 additions & 0 deletions tests/embedding-provider-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,20 @@ describe('getEmbeddingProvider cache key', () => {
})
);
});

it('rebuilds the Ollama provider when the effective timeout changes', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => Response.json({}))
);
vi.stubEnv('OLLAMA_REQUEST_TIMEOUT_MS', '500');
const { getEmbeddingProvider } = await import('../src/embeddings/index.js');
const config = { provider: 'ollama', model: 'nomic-embed-text' } as const;

const first = await getEmbeddingProvider(config);
await expect(getEmbeddingProvider({ ...config, requestTimeoutMs: 500 })).resolves.toBe(first);

vi.stubEnv('OLLAMA_REQUEST_TIMEOUT_MS', '1000');
await expect(getEmbeddingProvider(config)).resolves.not.toBe(first);
});
});
36 changes: 36 additions & 0 deletions tests/embedding-provider-defaults.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,39 @@ it('indexes with the Ollama default model when only the provider is set in index
await rm(rootPath, { recursive: true, force: true });
}
});

it('uses the indexer’s configured Ollama timeout ahead of the environment timeout', async () => {
vi.stubEnv('OLLAMA_REQUEST_TIMEOUT_MS', '60000');
const apiEndpoint = 'http://127.0.0.1:11434';
const requestTimeoutMs = 200;
vi.stubGlobal('fetch', async (_url: string, { signal }: RequestInit) => {
signal?.throwIfAborted();
return Response.json({}, { status: 404 });
});
const { CodebaseIndexer } = await import('../src/core/indexer.js');
const rootPath = await mkdtemp(join(tmpdir(), 'cbc-ollama-timeout-'));
// Expire the request immediately so a dropped option cannot stall the test.
const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(AbortSignal.abort());

try {
await writeFile(
join(rootPath, 'source.ts'),
'export function greeting() { return "hello"; }\n'
);
const indexer = new CodebaseIndexer({
rootPath,
config: {
skipEmbedding: false,
embedding: { provider: 'ollama', apiEndpoint, requestTimeoutMs }
}
});

await expect(indexer.index()).rejects.toThrow(
`Ollama request to ${apiEndpoint}/api/show timed out after ${requestTimeoutMs} ms`
);
expect(timeout).toHaveBeenCalledWith(requestTimeoutMs);
} finally {
timeout.mockRestore();
await rm(rootPath, { recursive: true, force: true });
}
});
Loading
Loading