Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

24.2 KB
Raw Blame
import { chatBackendsBack } from '../../lib/chat-backends-gate'
import { ollamaSamplerOptions } from './sampler-fields'
import { ollamaCustomOptions } from '../../lib/custom-params'
import { resolveMessageAttachments } from '../../lib/chat-attachments'
/**
 * Ollama Provider, wraps existing ollama.ts into the ProviderClient interface.
 *
 * No behavior change. Pure adapter pattern.
 * Reuses localFetch/localFetchStream from backend.ts for Tauri compatibility.
 */

import type {
  ProviderClient, ProviderModel, ProviderConfig, ChatMessage, ChatOptions,
  ChatStreamChunk, ToolCall, ToolDefinition,
} from './types'
import { ProviderError } from './types'
import { localFetch, localFetchStream, ollamaUrl } from '../backend'
import { ollamaWindowOption } from '../ollama'
import { parseOllamaShowContext } from './context-probe'
import { oneEntryPerName } from '../../lib/one-entry-per-name'
import { isLocalTransportFailure, localBackendUnreachableMessage } from '../../lib/local-backend-transport'
import { parseNDJSONStream } from '../stream'
import { chatFirstReplyMs } from '../../lib/chat-reply-timeout'
import { useSettingsStore } from '../../stores/settingsStore'
import { ollamaKeepAlive } from '../../lib/idle-unload'
import { idleAbortGuard, isStreamIdleTimeout, STREAM_IDLE_TIMEOUT_MS } from '../stream-idle'
import { repairToolCallArgs, extractToolCallsFromContent } from '../../lib/tool-call-repair'
import { applyTemplateContract } from './normalize-system'
import { parseOllamaChatChunk, isRecord, prop, asString, asNumber, asRecordArray } from './wire'
import { FIRST_REPLY_TIMEOUT } from '../../lib/chat-reply-timeout'

// ── Ollama-specific types ──────────────────────────────────────

/**
 * What we SEND. Separate from the wire types in `./wire`, which describe what
 * the server sends back: this payload is ours, so it gets a real shape rather
 * than a `Record<string, any>` bag that would swallow a typo in a field name.
 */
export interface OllamaRequestOptions {
  temperature?: number
  top_p?: number
  top_k?: number
  num_predict?: number
  num_ctx?: number
  /** GH #175, see sampler-fields.ts. */
  min_p?: number
  repeat_penalty?: number
  presence_penalty?: number
  frequency_penalty?: number
  /** GH #198: custom rows (dry_base, xtc_threshold ...), see lib/custom-params.ts. */
  [custom: string]: unknown
}

export interface OllamaRequestMessage {
  role: string
  content: string
  /** base64 payloads only, Ollama takes the data, not our {data,mimeType}. */
  images?: string[]
  tool_calls?: ToolCall[]
}

export interface OllamaChatRequest {
  model: string
  messages: OllamaRequestMessage[]
  stream: boolean
  keep_alive: string
  tools?: ToolDefinition[]
  options?: OllamaRequestOptions
  /** Tri-state; deleted again on the 400-retry, hence optional. */
  think?: boolean
  /** Constrained output: a JSON schema the answer must match. */
  format?: Record<string, unknown>
}

// Was auf dieser Route ZURUECKKOMMT, liegt als `OllamaChatChunk` in ./wire,
// hinter `parseOllamaChatChunk`. Hier stand dieselbe Form ein zweites Mal, // als Typargument an `parseNDJSONStream`, also als BEHAUPTUNG ueber
// `JSON.parse`, mit drei Feldern (`prompt_eval_duration`, `total_duration`,
// `load_duration`), die diese Datei nie gelesen hat. Die sieben, die sie
// liest, kommen jetzt geprueft aus dem Parser. Dass das ueberhaupt auffiel:
// `tool_calls` wurde direkt `.map`-t, ein Server, der dort kein Array
// schickt, riss die ganze Stream-Schleife mit einem TypeError auf.

interface OllamaModelEntry {
  name: string
  model: string
  size: number
  digest: string
  modified_at: string
  /** ['completion','tools','thinking','vision',...]. Ollama states this per
   *  model in /api/tags. Older servers omit it. */
  capabilities?: string[]
  details: {
    parent_model: string
    format: string
    family: string
    families: string[]
    parameter_size: string
    quantization_level: string
  }
}

// ── Provider Implementation ────────────────────────────────────

export class OllamaProvider implements ProviderClient {
  readonly id = 'ollama' as const

  /**
   * The config is accepted for a uniform provider constructor signature but
   * deliberately not stored: every URL goes through `ollamaUrl()` (see
   * `apiUrl()` below, Issue #31), so a stored `config.baseUrl` would only be
   * a second, silently diverging source of truth.
   */
  constructor(_config: ProviderConfig) {}

  /**
   * Build a full Ollama API URL. Delegates to `ollamaUrl()` from backend.ts
   * so Tauri-mode (direct URL honoring `_ollamaBase`) and dev-mode
   * (`/api/*` → Vite proxy with OLLAMA_HOST target) stay in sync with the
   * rest of the app.
   *
   * Issue #31 fix: previously this function used `config.baseUrl` in Tauri
   * mode only, and in dev mode always forwarded to the Vite proxy which
   * itself was hardcoded to localhost:11434, so a user-configured remote
   * Ollama never actually got called. Both modes now go through the single
   * ollamaUrl() resolver.
   */
  private apiUrl(path: string): string {
    return ollamaUrl(path)
  }

  async *chatStream(
    model: string,
    messages: ChatMessage[],
    options?: ChatOptions,
  ): AsyncGenerator<ChatStreamChunk> {
    // Bug B3: one system message first, and, because this call carries no
    // `tools` payload, no `tool` role and no two turns of the same role in a
    // row either. Ollama renders the model's own template exactly the way
    // llama.cpp does, and a strict one raises instead of improvising. See
    // providers/normalize-system.ts for the whole contract.
    messages = await resolveMessageAttachments(messages)
    // A Create render may have moved the chat model out (vram-handoff).
    await chatBackendsBack()
    const ollamaMessages = applyTemplateContract(messages, {
      toolRole: 'text',
      alternate: true,
      model,
    }).map(m => {
      const msg: OllamaRequestMessage = { role: m.role, content: m.content }
      if (m.images?.length) msg.images = m.images.map(img => img.data)
      return msg
    })

    const body: OllamaChatRequest = {
      model,
      messages: ollamaMessages,
      stream: true,
      // Audit A6: match the agent transport so a long turn never pays a
      // cold multi-GB reload after Ollama's 5-minute default idle unload.
      keep_alive: ollamaKeepAlive('30m'),
    }

    // v2.4.6 Bug L: dropped hardcoded `num_gpu: 99`. Old code forced ALL
    // layers onto the GPU on every chat request, which on 8 GB laptop cards
    // pushed the KV cache out into system RAM (Discord
    // 2026-05-18: 30 tok/s in ollama CLI vs 6.9 tok/s in LU on RTX 4070
    // Laptop + gemma3:4b). Letting Ollama do its own VRAM-aware layer
    // placement restores CLI parity on tight cards and is a no-op on
    // cards with headroom.
    const ollamaOptions: OllamaRequestOptions = {}
    if (options?.temperature !== undefined) ollamaOptions.temperature = options.temperature
    if (options?.topP !== undefined) ollamaOptions.top_p = options.topP
    if (options?.topK !== undefined) ollamaOptions.top_k = options.topK
    if (options?.maxTokens && options.maxTokens > 0) ollamaOptions.num_predict = options.maxTokens
    if (options) Object.assign(ollamaOptions, ollamaSamplerOptions(options))
    // GH #198: the custom rows, inside options, where Ollama reads samplers.
    Object.assign(ollamaOptions, ollamaCustomOptions(options?.customParams))
    // The window: resolved in ONE place for every request to Ollama, so the
    // model is never loaded again by a call that sends another one. Without
    // any, Ollama runs at its own small default and cuts real chats short.
    Object.assign(ollamaOptions, await ollamaWindowOption(model, options?.window))
    body.options = ollamaOptions
    // Tri-state: true → explicit think on, false → explicit think off
    // (saves tokens on QwQ / DeepSeek-R1 / Gemma 4 etc.), undefined →
    // omit the field and let Ollama pick the default.
    if (options?.thinking === true) body.think = true
    else if (options?.thinking === false) body.think = false

    // Zeitbombe 4, the idle watchdog needs something to abort, and a provider
    // only ever gets a signal, never the controller behind it. This chains one
    // onto the caller's: Stop still propagates inward, and a stream that goes
    // silent can now cancel its own request (which on the Tauri path is what
    // fires cancel_proxy_stream, so Ollama actually stops generating).
    const guard = idleAbortGuard(options?.signal)
    try {
      let res = await localFetchStream(this.apiUrl('/chat'), {
        method: 'POST',
        body: JSON.stringify(body),
        signal: guard.signal,
      })

      // Older Ollama builds / non-thinking models reject ANY `think` field
      // with HTTP 400. Retry once without it so the user's request still
      // succeeds, we just fall back to model-default behaviour.
      if (!res.ok && res.status === 400 && 'think' in body) {
        delete body.think
        res = await localFetchStream(this.apiUrl('/chat'), {
          method: 'POST',
          body: JSON.stringify(body),
          signal: guard.signal,
        })
      }

      if (!res.ok) {
        throw await this.buildError(res, 'Chat failed', model)
      }

      // Ollama marks the end of a turn with a `"done":true` line. Nothing
      // guarantees it arrives: a runner OOM, VRAM eviction, `ollama stop`, a
      // proxy or LAN cut all end the NDJSON mid-line. Without the guarantee
      // below the generator simply returned and the chat layer, which only
      // explains a turn it was given a finishReason for, left a permanently
      // empty assistant bubble with no hint at all. openai-provider.ts has
      // ended its stream with an explicit terminal chunk for several releases
      // (see its end-of-stream 'disconnect' path); this is the same semantics.
      let sawDone = false
      const terminal = (reason: string): ChatStreamChunk => ({
        content: '', done: true, finishReason: reason,
      })

      try {
        for await (const raw of parseNDJSONStream<unknown>(res, {
          idleMs: STREAM_IDLE_TIMEOUT_MS,
          // Issue 177: Ollama answers the headers at once and then reads the
          // prompt in silence; that wait follows the setting (0 = Off).
          firstChunkMs: chatFirstReplyMs(useSettingsStore.getState().settings),
          onIdle: guard.abort,
        })) {
          if (options?.signal?.aborted) break
          const chunk = parseOllamaChatChunk(raw)

          // Mid-stream `{"error":"..."}` line (runner crash, OOM) inside an
          // HTTP-200 stream, surface it instead of yielding a silent empty
          // chat turn (Discord 2026-06-10, Win11 proxy path). `error`
          // kommt als `string | undefined` aus dem Parser, der `typeof`-Test
          // von frueher sass auf einem `unknown` aus einer Typzusicherung.
          if (chunk.error) {
            throw new Error(`Ollama: ${chunk.error}`)
          }

          // `arguments` arrives as `unknown` from the wire because Ollama is
          // not the only thing that answers on this endpoint: llama.cpp-based
          // and proxied servers send the field as a JSON *string*, and this
          // path used to hand that string on as `Record<string, any>`, a lie
          // `any` was covering for. repairToolCallArgs is the same
          // normalization the non-streaming path below already performs; for a
          // real object it returns the object untouched.
          const toolCalls: ToolCall[] | undefined = chunk.message?.tool_calls?.map(tc => ({
            function: {
              name: tc.function?.name ?? '',
              arguments: repairToolCallArgs(tc.function?.arguments),
            },
          }))

          if (chunk.done) sawDone = true

          yield {
            content: chunk.message?.content || '',
            thinking: chunk.message?.thinking || undefined,
            toolCalls: toolCalls?.length ? toolCalls : undefined,
            done: chunk.done || false,
            finishReason: chunk.done_reason || undefined,
            // Bug M v2.4.7, pass through server-side generation metrics so the
            // benchmark can report Ollama's own measurement instead of trusting
            // client-side TTFT, which WebView2 release-mode buffers into
            // uselessness for fast small models.
            evalCount: chunk.eval_count,
            promptEvalCount: chunk.prompt_eval_count,
            evalDurationMs: chunk.eval_duration !== undefined ? chunk.eval_duration / 1_000_000 : undefined,
          }
        }
      } catch (err) {
        // The watchdog fired: the stream did not fail, it went quiet. That is
        // a disconnect, not an error to throw at the user.
        if (isStreamIdleTimeout(err)) {
          yield terminal('disconnect')
          return
        }
        throw err
      }

      // Truncated NDJSON, no done:true ever arrived. A user-pressed Stop is
      // not a disconnect, so it gets no terminal chunk (the chat layer has
      // already stopped reading by then anyway).
      if (!sawDone && !options?.signal?.aborted) {
        yield terminal('disconnect')
      }
    } finally {
      guard.release()
    }
  }

  async chatWithTools(
    model: string,
    messages: ChatMessage[],
    tools: ToolDefinition[],
    options?: ChatOptions,
  ): Promise<{ content: string; toolCalls: ToolCall[]; promptEvalCount?: number; evalCount?: number; thinking?: string }> {
    // Bug B3: same contract as chatStream. A turn that really carries a
    // `tools` payload keeps the native tool channel. The strategy resolution
    // only sends one after Ollama itself reported the `tools` capability for
    // this model (/api/show, see lib/tool-support.ts).
    messages = await resolveMessageAttachments(messages)
    // A Create render may have moved the chat model out (vram-handoff).
    await chatBackendsBack()
    const ollamaMessages = applyTemplateContract(messages, {
      toolRole: tools.length > 0 ? 'native' : 'text',
      alternate: tools.length === 0,
      model,
    }).map(m => {
      const msg: OllamaRequestMessage = { role: m.role, content: m.content }
      if (m.tool_calls) msg.tool_calls = m.tool_calls
      if (m.images?.length) msg.images = m.images.map(img => img.data)
      return msg
    })

    const body: OllamaChatRequest = {
      model,
      messages: ollamaMessages,
      tools,
      stream: false,
      // Audit A6: see chatStream above.
      keep_alive: ollamaKeepAlive('30m'),
    }

    // v2.4.6 Bug L: see chatStream() above, same num_gpu:99 removal.
    const ollamaOptions: OllamaRequestOptions = {}
    if (options?.temperature !== undefined) ollamaOptions.temperature = options.temperature
    if (options?.topP !== undefined) ollamaOptions.top_p = options.topP
    if (options?.topK !== undefined) ollamaOptions.top_k = options.topK
    if (options?.maxTokens && options.maxTokens > 0) ollamaOptions.num_predict = options.maxTokens
    if (options) Object.assign(ollamaOptions, ollamaSamplerOptions(options))
    // GH #198: the custom rows, inside options, where Ollama reads samplers.
    Object.assign(ollamaOptions, ollamaCustomOptions(options?.customParams))
    // The window, see chatStream().
    Object.assign(ollamaOptions, await ollamaWindowOption(model, options?.window))
    body.options = ollamaOptions
    // Tri-state think flag, see chatStream() for details.
    if (options?.thinking === true) body.think = true
    else if (options?.thinking === false) body.think = false
    if (options?.jsonSchema) body.format = options.jsonSchema

    type LocalFetchInit = NonNullable<Parameters<typeof localFetch>[1]>
    const fetchOptions = (bodyObj: OllamaChatRequest): LocalFetchInit => {
      const opts: LocalFetchInit = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(bodyObj),
      }
      if (options?.signal) opts.signal = options.signal
      return opts
    }

    let res = await localFetch(this.apiUrl('/chat'), fetchOptions(body))
    if (!res.ok && res.status === 400 && 'think' in body) {
      delete body.think
      res = await localFetch(this.apiUrl('/chat'), fetchOptions(body))
    }

    if (!res.ok) {
      throw await this.buildError(res, 'Tool calling failed', model)
    }

    // Boundary: everything below reads a body we did not produce, so each
    // field is checked on the way out of `unknown` instead of being asserted
    // into a shape.
    const data: unknown = await res.json()
    const message = prop(data, 'message')
    const content = asString(prop(message, 'content')) || ''
    let toolCalls: ToolCall[] = asRecordArray(prop(message, 'tool_calls')).map(tc => {
      const fn = prop(tc, 'function')
      return {
        function: {
          name: asString(prop(fn, 'name')) ?? '',
          arguments: repairToolCallArgs(isRecord(fn) ? fn.arguments : undefined),
        },
      }
    })

    // If no tool calls found but content looks like a tool call, try to extract
    if (toolCalls.length === 0 && content) {
      const extracted = extractToolCallsFromContent(content)
      if (extracted.length > 0) {
        toolCalls = extracted.map(tc => ({ function: tc }))
      }
    }

    return {
      content,
      thinking: asString(prop(message, 'thinking')) || '',
      toolCalls,
      // Real token usage from the non-streaming response, same fields
      // chatStream() already forwards, without them the agent TokenCounter
      // falls back to a char/4 estimate for every Ollama tool turn.
      promptEvalCount: asNumber(prop(data, 'prompt_eval_count')),
      evalCount: asNumber(prop(data, 'eval_count')),
    }
  }

  async listModels(): Promise<ProviderModel[]> {
    const res = await localFetch(this.apiUrl('/tags'))
    if (!res.ok) {
      throw new ProviderError('Failed to fetch Ollama models', 'ollama', 'network', res.status)
    }

    const data = await res.json()
    return oneEntryPerName<OllamaModelEntry>(data.models || []).map((m) => ({
      id: m.name,
      name: m.name,
      provider: 'ollama' as const,
      providerName: 'Ollama',
      contextLength: undefined, // fetched on demand via getContextLength
      // Ollama says per model whether it can call tools, and this dropped that
      // answer on the floor, so every Ollama model reached resolveToolSupport
      // with `undefined` and the decision fell through to the family-name list
      // in model-compatibility. That list matches on substrings, so a
      // completion-only build whose name merely contains a known family was
      // declared native and got a `tools` payload it cannot accept. Measured
      // 2026-08-06 on DESKTOP-D1TO33K: `hf.co/DevQuasar/huihui-ai.Qwen3-4B-
      // abliterated-GGUF:Q4_K_M` reports ['completion'] and was still routed
      // native, purely because the name contains 'qwen3'.
      //
      // The server's own answer wins; the heuristic stays as the fallback for
      // an older Ollama that says nothing, which is why this is `undefined`
      // and not `true` when the field is absent. openai-provider.ts already
      // works exactly this way.
      supportsTools: Array.isArray(m.capabilities) ? m.capabilities.includes('tools') : undefined,
      // K12 (3.0.1): no `unfiltered` here, on purpose but with a real gap
      // behind it. The "No Filter" mark (ModelRowMarks.tsx) only fires for
      // 'full', and only the cloud catalog path (openai-provider.ts
      // listModels) ever sets that field, because it is the only one backed
      // by a real measurement. Ollama's own /api/tags carries nothing like
      // it, so a locally installed abliterated/uncensored GGUF, several of
      // which this app's own Discover catalog tags 'Unfiltered', can never
      // show the mark, even though it deserves it. Rather than guess from
      // the model name (the house rule this app is built against), the mark
      // stays measured-only and simply absent here. Closing this needs a
      // real curated measurement feeding local models too, not a heuristic
      // bolted onto this method.
    }))
  }

  async checkConnection(): Promise<boolean> {
    try {
      const res = await localFetch(this.apiUrl('/tags'))
      return res.ok
    } catch {
      return false
    }
  }

  async getContextLength(model: string): Promise<number> {
    // Bug K: dieselbe Cascade-Logik wie in src/api/ollama.ts::getModelContext.
    // Vorher hat dieser Provider NUR `general.context_length` gecheckt, aber
    // viele Ollama-Modelle (z.B. qwen2.5:*, llama3.x:*) lassen das leer und
    // setzen stattdessen architecture-specific keys wie `qwen2.context_length`
    // oder `llama.context_length`. Mit dem alten Code zeigte LU 4096 obwohl
    // Modelle real 32K-128K koennen. Live-verified auf Arch 2026-05-17 gegen
    // pacman-ollama 0.23.2 + qwen2.5:0.5b (general.context_length=None,
    // qwen2.context_length=32768).
    try {
      const res = await localFetch(this.apiUrl('/show'), {
        method: 'POST',
        body: JSON.stringify({ name: model }),
      })
      if (!res.ok) return 4096
      const info = await res.json()

      // The same reading as api/ollama.ts (`parseOllamaShowContext`), so the
      // two paths cannot drift apart again.
      const fromShow = parseOllamaShowContext(info)
      if (fromShow) return fromShow

      return 4096
    } catch {
      return 4096
    }
  }

  // ── Helpers ────────────────────────────────────────────────

  /**
   * Classify a non-ok Ollama response and wrap it in `ProviderError`. The
   * resulting error carries:
   *   - `code`, one of `ollama_missing_blob`, `ollama_stale_manifest`,
   *     or generic `network` so UI catch sites can branch (and feed the
   *     model-health store via lib/sync-ollama-health.ts) without
   *     re-parsing the message.
   *   - `model`, threaded through from chatStream/chatWithTools so the
   *     UI can name the affected model in a one-click "ollama pull <model>"
   *     repair flow. Missing-blob errors only carry the on-disk blob hash,
   *     not the model name, so we pass `model` into parseOllamaError as the
   *     fallback (Bug C), that populates `parsed.model`, which
   *     chatStyleMessage then uses for the user-facing wording.
   *
   * Pure function: no store side-effects, no UI imports. The caller
   * (useChat via syncOllamaHealthFromError) translates the error code into
   * a store update.
   *
   * Shares the detection logic with loadModel / unloadModel via
   * ollama-errors. The regex there matches chat, completion, AND generate
   * (the Lichtschalter path uses /api/generate with an empty prompt for
   * preload, same error class).
   */
  private async buildError(res: Response, fallback: string, model?: string): Promise<ProviderError> {
    const status = res.status
    try {
      const { parseOllamaError, chatStyleMessage } = await import('../../lib/ollama-errors')
      const parsed = await parseOllamaError(res, fallback, model)
      // Ollama is not running, or moved: the proxy's raw line arrives as the
      // error body and would go straight into the bubble, Rust command name and
      // all. Caught here rather than in ollama-errors, because only this side
      // knows which address was asked (04.09.2026, same round as proxy.rs).
      const wo = this.apiUrl('')
      if (isLocalTransportFailure(parsed.raw ?? '', wo)) {
        return new ProviderError(
          localBackendUnreachableMessage('Ollama', wo), 'ollama', 'network', status, model,
        )
      }
      const message = chatStyleMessage(parsed)
      let code = 'network'
      if (parsed.kind === 'missing-blob') code = 'ollama_missing_blob'
      else if (parsed.kind === 'stale-manifest') code = 'ollama_stale_manifest'
      // Issue 177: Chat Reply Timeout ran out (api/backend.ts). Terminal for
      // the agent's retry ladder, which would only wait the window again.
      else if (/sent nothing for \d+ s/.test(parsed.raw ?? message)) code = FIRST_REPLY_TIMEOUT
      // Prefer the parsed model name (e.g. from a stale-manifest string that
      // carries it) and fall back to the request's model arg.
      return new ProviderError(message, 'ollama', code, status, parsed.model || model)
    } catch {
      return new ProviderError(fallback, 'ollama', 'network', status, model)
    }
  }
}