|
| 1 | +import type { ChatJob, ModelsJob } from "~/src/job/schema"; |
| 2 | +import { createHTTPJob } from "~/src/job/http"; |
| 3 | +import { |
| 4 | + transformToolsToFunctions, |
| 5 | + createStreamingGenerator, |
| 6 | +} from "~/src/job/utils"; |
| 7 | + |
| 8 | +const DEFAULT_BASE_URL = "http://localhost:11434"; |
| 9 | + |
| 10 | +function getBaseUrl(options?: ChatJob["options"]): string { |
| 11 | + return options?.baseUrl || process.env.OLLAMA_BASE_URL || DEFAULT_BASE_URL; |
| 12 | +} |
| 13 | + |
| 14 | +export const runner = { |
| 15 | + chat: async (input: ChatJob["input"], options?: ChatJob["options"]) => { |
| 16 | + const baseUrl = getBaseUrl(options); |
| 17 | + const tools = transformToolsToFunctions(input.tools); |
| 18 | + |
| 19 | + const request = new Request(`${baseUrl}/api/chat`, { |
| 20 | + method: "POST", |
| 21 | + headers: { |
| 22 | + "Content-Type": "application/json", |
| 23 | + }, |
| 24 | + body: JSON.stringify({ |
| 25 | + model: input.model, |
| 26 | + messages: input.messages, |
| 27 | + temperature: input.temperature, |
| 28 | + tools: tools, |
| 29 | + stream: input.stream ?? false, |
| 30 | + options: { |
| 31 | + num_predict: input.maxTokens, |
| 32 | + }, |
| 33 | + }), |
| 34 | + }); |
| 35 | + |
| 36 | + return createHTTPJob(request, async (response: Response) => { |
| 37 | + if (input.stream) { |
| 38 | + return createStreamingGenerator(response); |
| 39 | + } |
| 40 | + |
| 41 | + const data = await response.json(); |
| 42 | + |
| 43 | + return { |
| 44 | + messages: [ |
| 45 | + { |
| 46 | + role: data.message.role, |
| 47 | + content: data.message.content, |
| 48 | + tool_calls: data.message.tool_calls, |
| 49 | + }, |
| 50 | + ], |
| 51 | + usage: data.prompt_eval_count |
| 52 | + ? { |
| 53 | + promptTokens: data.prompt_eval_count || 0, |
| 54 | + completionTokens: data.eval_count || 0, |
| 55 | + totalTokens: |
| 56 | + (data.prompt_eval_count || 0) + (data.eval_count || 0), |
| 57 | + } |
| 58 | + : undefined, |
| 59 | + }; |
| 60 | + }); |
| 61 | + }, |
| 62 | + |
| 63 | + models: async ( |
| 64 | + input?: ModelsJob["input"], |
| 65 | + options?: ModelsJob["options"], |
| 66 | + ) => { |
| 67 | + const baseUrl = getBaseUrl(options); |
| 68 | + |
| 69 | + const request = new Request(`${baseUrl}/api/tags`, { |
| 70 | + method: "GET", |
| 71 | + headers: { |
| 72 | + "Content-Type": "application/json", |
| 73 | + }, |
| 74 | + }); |
| 75 | + |
| 76 | + return createHTTPJob(request, async (response: Response) => { |
| 77 | + const data = await response.json(); |
| 78 | + |
| 79 | + return data.models.map((model: any) => ({ |
| 80 | + id: model.name, |
| 81 | + name: model.name, |
| 82 | + })); |
| 83 | + }); |
| 84 | + }, |
| 85 | +}; |
0 commit comments