All files / kernel-language-model-service/src/ollama base.ts

94.11% Statements 48/51
68.75% Branches 22/32
100% Functions 19/19
94.11% Lines 48/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297                                                                                                                  33x                 4x 3x                   4x 4x   4x     4x     4x             4x 2x       2x                 2x                       3x 4x 4x 4x       1x                   4x                                                                                         3x 1x   2x               2x 2x             2x               1x   1x             1x   1x 1x     1x                 3x   3x     3x                                     12x 12x 12x 12x     12x           12x 3x   2x     2x     4x           3x   3x 2x     2x       12x      
import { ifDefined } from '@metamask/kernel-utils';
import type {
  AbortableAsyncIterator,
  GenerateResponse,
  ListResponse,
} from 'ollama';
 
import type {
  AssistantMessage,
  ChatParams,
  ChatResult,
  LanguageModelService,
  SampleParams,
  SampleResult,
} from '../types.ts';
import { parseModelConfig } from './parse.ts';
import type {
  OllamaInstanceConfig,
  OllamaModel,
  OllamaClient,
  OllamaModelOptions,
  OllamaTool,
} from './types.ts';
import { parseToolArguments } from '../utils/parse-tool-arguments.ts';
 
/**
 * Result of a streaming raw token-prediction request.
 */
export type SampleStreamResult = {
  stream: AsyncIterable<GenerateResponse>;
  abort: () => Promise<void>;
};
 
/**
 * Base service for interacting with Ollama language models.
 * Provides a generic interface for creating and managing Ollama model instances.
 * This class implements the LanguageModelService interface and handles the
 * creation of hardened model instances that can be safely passed between vats.
 *
 * @template Ollama - The type of Ollama client to use
 */
export class OllamaBaseService<Ollama extends OllamaClient>
  implements
    LanguageModelService<
      OllamaModelOptions,
      OllamaModelOptions,
      GenerateResponse
    >
{
  readonly #makeClient: () => Promise<Ollama>;
 
  /**
   * Creates a new Ollama base service.
   *
   * @param makeClient - Factory function that creates an Ollama client instance
   */
  constructor(makeClient: () => Promise<Ollama>) {
    this.#makeClient = makeClient;
  }
 
  /**
   * Retrieves a list of available models from the Ollama server.
   *
   * @returns A promise that resolves to the list of available models
   */
  async getModels(): Promise<ListResponse> {
    const client = await this.#makeClient();
    return await client.list();
  }
 
  /**
   * Performs a chat completion request via the Ollama chat API.
   *
   * @param params - The chat parameters.
   * @returns A hardened chat result.
   */
  async chat(params: ChatParams): Promise<ChatResult> {
    const { model, messages, tools, temperature, seed, stop } = params;
    const ollama = await this.#makeClient();
    let stopArr: string[] | undefined;
    Iif (stop !== undefined) {
      stopArr = Array.isArray(stop) ? stop : [stop];
    }
    const response = await ollama.chat({
      model,
      messages: messages.map((chatMessage) => {
        Iif (chatMessage.role === 'tool') {
          return {
            role: 'tool' as const,
            content: chatMessage.content,
            tool_call_id: chatMessage.tool_call_id,
          };
        }
        if (chatMessage.role === 'assistant') {
          return {
            role: 'assistant' as const,
            content: chatMessage.content ?? '',
            ...(chatMessage.tool_calls && {
              tool_calls: chatMessage.tool_calls.map(({ function: fn }) => ({
                function: {
                  name: fn.name,
                  arguments: parseToolArguments(fn.arguments),
                },
              })),
            }),
          };
        }
        return { role: chatMessage.role, content: chatMessage.content };
      }),
      ...(tools && { tools: tools as OllamaTool[] }),
      stream: false,
      options: ifDefined({
        temperature,
        top_p: params.top_p,
        seed,
        num_predict: params.max_tokens,
        stop: stopArr,
      }),
    });
    const promptTokens = response.prompt_eval_count ?? 0;
    const completionTokens = response.eval_count ?? 0;
    const { tool_calls: responseToolCalls } = response.message;
    const assistantMessage: AssistantMessage = {
      role: 'assistant',
      content: response.message.content,
      ...(responseToolCalls && {
        tool_calls: responseToolCalls.map((tc, index) => ({
          id: `tool-${index}`,
          type: 'function' as const,
          function: {
            name: tc.function.name,
            arguments: JSON.stringify(tc.function.arguments),
          },
        })),
      }),
    };
    return harden({
      id: 'ollama-chat',
      model: response.model,
      choices: [
        {
          message: assistantMessage,
          index: 0,
          finish_reason: response.done_reason ?? 'stop',
        },
      ],
      usage: {
        prompt_tokens: promptTokens,
        completion_tokens: completionTokens,
        total_tokens: promptTokens + completionTokens,
      },
    });
  }
 
  /**
   * Performs a raw token-prediction request via Ollama's generate API with raw=true,
   * bypassing the model's chat template.
   *
   * When `params.stream` is `true`, returns a streaming result with an async
   * iterable of {@link GenerateResponse} chunks and an abort handle.
   * When `params.stream` is `false` or omitted, awaits and returns the full
   * {@link SampleResult}.
   *
   * @param params - The raw sample parameters.
   * @returns A streaming result when `stream: true`, or the full result otherwise.
   */
  sample(params: SampleParams & { stream: true }): Promise<SampleStreamResult>;
 
  /**
   * @param params - The raw sample parameters.
   * @returns A promise resolving to the full sample result.
   */
  sample(params: SampleParams & { stream?: false }): Promise<SampleResult>;
 
  /**
   * @param params - The raw sample parameters.
   * @returns A streaming result or full result depending on `params.stream`.
   */
  async sample(
    params: SampleParams & { stream?: boolean },
  ): Promise<SampleResult | SampleStreamResult> {
    if (params.stream === true) {
      return this.#streamingSample(params);
    }
    return this.#nonStreamingSample(params);
  }
 
  /**
   * @param params - The raw sample parameters.
   * @returns A promise resolving to the full sample result.
   */
  async #nonStreamingSample(params: SampleParams): Promise<SampleResult> {
    const ollama = await this.#makeClient();
    const response = await ollama.generate({
      model: params.model,
      prompt: params.prompt,
      raw: true,
      stream: false,
      options: this.#buildSampleOptions(params),
    });
    return harden({ text: response.response });
  }
 
  /**
   * @param params - The raw sample parameters.
   * @returns A promise resolving to a streaming result.
   */
  async #streamingSample(params: SampleParams): Promise<SampleStreamResult> {
    const ollama = await this.#makeClient();
    const response: AbortableAsyncIterator<GenerateResponse> =
      await ollama.generate({
        model: params.model,
        prompt: params.prompt,
        raw: true,
        stream: true,
        options: this.#buildSampleOptions(params),
      });
    return harden({
      stream: (async function* () {
        for await (const chunk of response) {
          yield harden(chunk);
        }
      })(),
      abort: async () => response.abort(),
    });
  }
 
  /**
   * @param params - The raw sample parameters.
   * @returns The options sub-object for an Ollama generate request.
   */
  #buildSampleOptions(params: SampleParams): Record<string, unknown> {
    const { temperature, seed } = params;
    let stopArr: string[] | undefined;
    Iif (params.stop !== undefined) {
      stopArr = Array.isArray(params.stop) ? params.stop : [params.stop];
    }
    return harden(
      ifDefined({
        temperature,
        top_p: params.top_p,
        seed,
        num_predict: params.max_tokens,
        stop: stopArr,
      }),
    );
  }
 
  /**
   * Creates a new language model instance with the specified configuration.
   * The returned instance is hardened for object capability security.
   *
   * @param config - The configuration for the model instance
   * @returns A promise that resolves to a hardened language model instance
   */
  async makeInstance(config: OllamaInstanceConfig): Promise<OllamaModel> {
    const modelInfo = parseModelConfig(config);
    const { model } = modelInfo;
    const ollama = await this.#makeClient();
    const defaultOptions = {
      ...(config.options ?? {}),
    };
    const mandatoryOptions = {
      model,
      stream: true as const,
      raw: true,
    };
 
    const instance = {
      getInfo: async () => modelInfo,
      load: async () => {
        await ollama.generate({ model, keep_alive: -1, prompt: '' });
      },
      unload: async () => {
        await ollama.generate({ model, keep_alive: 0, prompt: '' });
      },
      sample: async (prompt: string, options?: Partial<OllamaModelOptions>) => {
        const response = await ollama.generate({
          ...defaultOptions,
          ...(options ?? {}),
          ...mandatoryOptions,
          prompt,
        });
        return {
          stream: (async function* () {
            for await (const chunk of response) {
              yield chunk;
            }
          })(),
          abort: async () => response.abort(),
        };
      },
    };
    return harden(instance);
  }
}