Open History to see the last commit
1import { requireTextOnlyEmbeddingInput } from '@tanstack/ai'
2import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
3import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'
4import { generateId } from '@tanstack/ai-utils'
5import { createOllamaClient, getOllamaHostFromEnv } from '../utils'
6import type { OllamaClientConfig } from '../utils/client'
7import type { EmbedRequest, EmbedResponse, Ollama } from 'ollama'
8import type {
9 EmbeddingOptions,
10 EmbeddingResult,
11 TokenUsage,
12} from '@tanstack/ai'
13import type { OllamaEmbeddingModel } from '../model-meta'
14import type { OllamaEmbeddingProviderOptions } from '../embedding/embedding-provider-options'
15
16/**
17 * Configuration for the Ollama Embedding adapter.
18 * Ollama has no API key — only an optional host (and headers).
19 */
20export interface OllamaEmbeddingConfig extends OllamaClientConfig {}
21
22/**
23 * Extract `prompt_eval_count` through an optional-field view of the response.
24 * The Ollama SDK types it as required, but servers can omit it at runtime;
25 * widening here keeps the presence check honest without any casts.
26 */
27function extractPromptEvalCount(response: {
28 prompt_eval_count?: number
29}): number | undefined {
30 return response.prompt_eval_count
31}
32
33/**
34 * Ollama Embedding Adapter
35 *
36 * Tree-shakeable adapter for Ollama text embeddings (`/api/embed`).
37 *
38 * Notes:
39 * - Batch embedding: one request for the whole input array.
40 * - Ollama models are loaded dynamically, so any model name string is
41 * accepted; `OLLAMA_EMBEDDING_MODELS` lists common embedding models.
42 * - Ollama does not support requesting embedding dimensions, so the
43 * top-level `dimensions` option is rejected.
44 */
45export class OllamaEmbeddingAdapter<
46 TModel extends OllamaEmbeddingModel,
47> extends BaseEmbeddingAdapter<TModel, OllamaEmbeddingProviderOptions> {
48 readonly name = 'ollama' as const
49
50 protected client: Ollama
51
52 constructor(
53 hostOrClientOrConfig: string | Ollama | OllamaEmbeddingConfig | undefined,
54 model: TModel,
55 ) {
56 super(model, {})
57 if (
58 typeof hostOrClientOrConfig === 'string' ||
59 hostOrClientOrConfig === undefined
60 ) {
61 this.client = createOllamaClient({ host: hostOrClientOrConfig })
62 } else if ('embed' in hostOrClientOrConfig) {
63 // Ollama client instance (has an embed method)
64 this.client = hostOrClientOrConfig
65 } else {
66 // OllamaEmbeddingConfig object
67 this.client = createOllamaClient(hostOrClientOrConfig)
68 }
69 }
70
71 async createEmbeddings(
72 options: EmbeddingOptions<OllamaEmbeddingProviderOptions>,
73 ): Promise<EmbeddingResult> {
74 const { model, logger, modelOptions } = options
75 const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)
76
77 if (options.dimensions !== undefined) {
78 throw new Error('Ollama does not support requesting embedding dimensions')
79 }
80
81 try {
82 // Built incrementally so optional keys are omitted entirely when unset
83 // (exactOptionalPropertyTypes). Provider options use camelCase
84 // (`keepAlive`) and are mapped to the SDK's snake_case wire fields.
85 const request: EmbedRequest = {
86 model,
87 input: texts,
88 }
89 if (modelOptions?.truncate !== undefined) {
90 request.truncate = modelOptions.truncate
91 }
92 if (modelOptions?.keepAlive !== undefined) {
93 request.keep_alive = modelOptions.keepAlive
94 }
95 if (modelOptions?.options !== undefined) {
96 // Spread a fresh object to avoid aliasing the caller's options.
97 request.options = { ...modelOptions.options }
98 }
99
100 logger.request(
101 `activity=embed provider=${this.name} model=${model} inputs=${texts.length}`,
102 { provider: this.name, model },
103 )
104
105 const response: EmbedResponse = await this.client.embed(request)
106
107 // Include usage only when Ollama actually reported a prompt token count.
108 const promptEvalCount = extractPromptEvalCount(response)
109 const usage: TokenUsage | undefined =
110 promptEvalCount !== undefined
111 ? {
112 promptTokens: promptEvalCount,
113 completionTokens: 0,
114 totalTokens: promptEvalCount,
115 }
116 : undefined
117
118 return {
119 id: generateId(this.name),
120 model,
121 embeddings: response.embeddings.map((vector, index) => ({
122 vector,
123 index,
124 })),
125 ...(usage !== undefined && { usage }),
126 }
127 } catch (error: unknown) {
128 logger.errors(`${this.name}.createEmbeddings fatal`, {
129 error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),
130 source: `${this.name}.createEmbeddings`,
131 })
132 throw error
133 }
134 }
135}
136
137/**
138 * Creates an Ollama embedding adapter with explicit host (or client config).
139 * Type resolution happens here at the call site.
140 *
141 * @param model - The model name (e.g., 'nomic-embed-text')
142 * @param hostOrConfig - Ollama host URL or client config (defaults to http://localhost:11434)
143 * @returns Configured Ollama embedding adapter instance with resolved types
144 *
145 * @example
146 * ```typescript
147 * const adapter = createOllamaEmbedding('nomic-embed-text', 'http://localhost:11434');
148 *
149 * const result = await embed({
150 * adapter,
151 * input: 'a red guitar'
152 * });
153 * ```
154 */
155export function createOllamaEmbedding<TModel extends OllamaEmbeddingModel>(
156 model: TModel,
157 hostOrConfig?: string | OllamaEmbeddingConfig,
158): OllamaEmbeddingAdapter<TModel> {
159 return new OllamaEmbeddingAdapter(hostOrConfig, model)
160}
161
162/**
163 * Creates an Ollama embedding adapter with host from the `OLLAMA_HOST`
164 * environment variable (falling back to the Ollama default).
165 * Type resolution happens here at the call site.
166 *
167 * @param model - The model name (e.g., 'nomic-embed-text')
168 * @returns Configured Ollama embedding adapter instance with resolved types
169 *
170 * @example
171 * ```typescript
172 * const adapter = ollamaEmbedding('mxbai-embed-large');
173 *
174 * const result = await embed({
175 * adapter,
176 * input: ['a red guitar', 'a blue drum kit']
177 * });
178 *
179 * console.log(result.embeddings[0].vector)
180 * ```
181 */
182export function ollamaEmbedding<TModel extends OllamaEmbeddingModel>(
183 model: TModel,
184): OllamaEmbeddingAdapter<TModel> {
185 const host = getOllamaHostFromEnv()
186 return new OllamaEmbeddingAdapter(host, model)
187}