Open History to see the last commit
1import { Ollama } from 'ollama'
2import { generateId as _generateId } from '@tanstack/ai-utils'
3
4export interface OllamaClientConfig {
5 /**
6 * Base URL for every request. Same option name as the other adapters, so a
7 * gateway config can be spread into any of them. Wins over `host` when both
8 * are set.
9 */
10 baseURL?: string
11 /** Alias of `baseURL`. */
12 host?: string
13 /**
14 * Headers sent with every request. Same option name as the other adapters.
15 * Wins over `headers` when both are set.
16 */
17 defaultHeaders?: Record<string, string>
18 /** Alias of `defaultHeaders`. */
19 headers?: Record<string, string> | undefined
20}
21
22/**
23 * Creates an Ollama client instance
24 */
25export function createOllamaClient(config: OllamaClientConfig = {}): Ollama {
26 return new Ollama({
27 host: config.baseURL || config.host || 'http://localhost:11434',
28 headers: config.defaultHeaders ?? config.headers,
29 })
30}
31
32/**
33 * Gets Ollama host from environment variables
34 * Falls back to default localhost
35 */
36export function getOllamaHostFromEnv(): string {
37 const env =
38 typeof globalThis !== 'undefined' &&
39 (globalThis as Record<string, unknown>).window
40 ? ((
41 (globalThis as Record<string, unknown>).window as Record<
42 string,
43 unknown
44 >
45 ).env as Record<string, string> | undefined)
46 : typeof process !== 'undefined'
47 ? process.env
48 : undefined
49 return env?.['OLLAMA_HOST'] || 'http://localhost:11434'
50}
51
52/**
53 * Generates a unique ID with a prefix
54 */
55export function generateId(prefix: string = 'msg'): string {
56 return _generateId(prefix)
57}
58
59/**
60 * Estimates token count for text (rough approximation)
61 */
62export function estimateTokens(text: string): number {
63 // Rough approximation: 1 token ≈ 4 characters
64 return Math.ceil(text.length / 4)
65}