Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

client.ts

69 lines1.9 KB

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
21​
22/**
23 * Creates an Ollama client instance. A `fetch` replaces the client's fetch.
24 */
25export function createOllamaClient(
26 config: OllamaClientConfig = {},
27 fetch?: typeof globalThis.fetch,
28): Ollama {
29 return new Ollama({
30 host: config.baseURL || config.host || 'http://localhost:11434',
31 headers: config.defaultHeaders ?? config.headers,
32 ...(fetch && { fetch }),
33 })
35​
36/**
37 * Gets Ollama host from environment variables
38 * Falls back to default localhost
39 */
40export function getOllamaHostFromEnv(): string {
41 const env =
42 typeof globalThis !== 'undefined' &&
43 (globalThis as Record<string, unknown>).window
44 ? ((
45 (globalThis as Record<string, unknown>).window as Record<
46 string,
47 unknown
48 >
49 ).env as Record<string, string> | undefined)
50 : typeof process !== 'undefined'
51 ? process.env
52 : undefined
53 return env?.['OLLAMA_HOST'] || 'http://localhost:11434'
55​
56/**
57 * Generates a unique ID with a prefix
58 */
59export function generateId(prefix: string = 'msg'): string {
60 return _generateId(prefix)
62​
63/**
64 * Estimates token count for text (rough approximation)
65 */
66export function estimateTokens(text: string): number {
67 // Rough approximation: 1 token ≈ 4 characters
68 return Math.ceil(text.length / 4)