48 lines
1.4 KiB
TypeScript
48 lines
1.4 KiB
TypeScript
import type { OllamaEmbedOptions, OllamaEmbeddingResponse } from './types.js';
|
|
|
|
/**
|
|
* Get embeddings for text using an Ollama embedding model.
|
|
*
|
|
* @param baseUrl - Ollama server base URL
|
|
* @param options - Embedding options (model, input text)
|
|
* @returns Array of embedding vectors (one per input string)
|
|
*/
|
|
export async function getEmbedding(
|
|
baseUrl: string,
|
|
options: OllamaEmbedOptions
|
|
): Promise<OllamaEmbeddingResponse> {
|
|
const res = await fetch(`${baseUrl}/api/embed`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
model: options.model,
|
|
input: options.input,
|
|
...(options.options && { options: options.options }),
|
|
}),
|
|
});
|
|
|
|
if (!res.ok) {
|
|
const text = await res.text().catch(() => '');
|
|
throw new Error(`Ollama embed failed (${res.status}): ${text.slice(0, 200)}`);
|
|
}
|
|
|
|
return (await res.json()) as OllamaEmbeddingResponse;
|
|
}
|
|
|
|
/**
|
|
* Convenience: get a single embedding vector for a text string.
|
|
*
|
|
* @param baseUrl - Ollama server base URL
|
|
* @param text - Text to embed
|
|
* @param model - Embedding model name (default: 'nomic-embed-text')
|
|
* @returns Single embedding vector
|
|
*/
|
|
export async function getEmbeddingVector(
|
|
baseUrl: string,
|
|
text: string,
|
|
model: string = 'nomic-embed-text'
|
|
): Promise<number[]> {
|
|
const response = await getEmbedding(baseUrl, { model, input: text });
|
|
return response.embeddings?.[0] ?? [];
|
|
}
|