| 1 | import { Service } from '@deepseek-ai/cordis' |
| 2 | import { ErrorCode } from '../protocol.ts' |
| 3 | import { RpcError } from '../rpc.ts' |
| 4 | import type { AdapterHost, DshAdapter } from './adapters.ts' |
| 5 | |
| 6 | export const SESSION_PROVIDER = 'session' |
| 7 | |
| 8 | export interface BrokeredModel { |
| 9 | provider: string |
| 10 | id: string |
| 11 | name: string |
| 12 | context_window: number | null |
| 13 | default_max_output_tokens: number |
| 14 | max_output_tokens: number |
| 15 | } |
| 16 | |
| 17 | export interface BrokeredCatalog { |
| 18 | providers: { id: string, name: string }[] |
| 19 | models: BrokeredModel[] |
| 20 | limits: Record<string, number> |
| 21 | } |
| 22 | |
| 23 | export interface BrokeredUsage { |
| 24 | coverage: string |
| 25 | input_tokens: number | null |
| 26 | output_tokens: number | null |
| 27 | cache_read_tokens: number | null |
| 28 | cache_write_tokens: number | null |
| 29 | reasoning_tokens: number | null |
| 30 | } |
| 31 | |
| 32 | export interface BrokeredCompletion { |
| 33 | text: string |
| 34 | finish: string |
| 35 | route: { provider: string, model: string } | null |
| 36 | usage: BrokeredUsage |
| 37 | receipt: { requests: number, duration_ms: number } |
| 38 | } |
| 39 | |
| 40 | interface StreamOptions { |
| 41 | provider?: unknown |
| 42 | model?: unknown |
| 43 | messages?: unknown |
| 44 | system?: unknown |
| 45 | tools?: unknown |
| 46 | toolHistory?: unknown |
| 47 | maxTokens?: unknown |
| 48 | signal?: AbortSignal |
| 49 | } |
| 50 | |
| 51 | type Chunk = |
| 52 | | { type: 'block-start', index: number, blockType: 'text' } |
| 53 | | { type: 'text-delta', index: number, text: string } |
| 54 | | { type: 'block-end', index: number, block: { type: 'text', text: string } } |
| 55 | | { type: 'usage', usage: { inputTokens: number, outputTokens: number, totalTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number, reasoningTokens?: number } } |
| 56 | | { type: 'finish', reason: { kind: 'stop' } | { kind: 'aborted' | 'error', failure: { message: string, code: string } } } |
| 57 | |
| 58 | const invalid = (message: string) => new RpcError(ErrorCode.InvalidParams, message) |
| 59 | const notBrokered = (method: string): never => { |
| 60 | throw new RpcError(ErrorCode.NotAvailable, `llm.${method} is not available: Codewhale brokers model calls on the session's approved route and registers no plugin adapters, providers or keys`) |
| 61 | } |
| 62 | |
| 63 | function catalogOf(value: unknown): BrokeredCatalog { |
| 64 | const catalog = value as Partial<BrokeredCatalog> | null |
| 65 | if (catalog === null || typeof catalog !== 'object' || !Array.isArray(catalog.providers) || !Array.isArray(catalog.models) |
| 66 | || catalog.models.some((model) => model === null || typeof model !== 'object' || typeof model.id !== 'string' || typeof model.provider !== 'string')) { |
| 67 | throw new RpcError(ErrorCode.Internal, 'invalid llm broker catalog') |
| 68 | } |
| 69 | return catalog as BrokeredCatalog |
| 70 | } |
| 71 | |
| 72 | function completionOf(value: unknown): BrokeredCompletion { |
| 73 | const completion = value as Partial<BrokeredCompletion> | null |
| 74 | if (completion === null || typeof completion !== 'object' || typeof completion.text !== 'string' |
| 75 | || typeof completion.finish !== 'string' || completion.finish.length === 0 |
| 76 | || completion.usage === null || typeof completion.usage !== 'object' || typeof completion.usage.coverage !== 'string') { |
| 77 | throw new RpcError(ErrorCode.Internal, 'invalid llm broker completion') |
| 78 | } |
| 79 | return completion as BrokeredCompletion |
| 80 | } |
| 81 | |
| 82 | function textOf(content: unknown): string { |
| 83 | if (typeof content === 'string') return content |
| 84 | if (!Array.isArray(content)) throw invalid('the llm broker takes text message content') |
| 85 | return content.map((block) => { |
| 86 | if (block === null || typeof block !== 'object' || block.type !== 'text' || typeof block.text !== 'string') { |
| 87 | throw invalid('the llm broker takes text blocks only; images, files and tool calls are not brokered') |
| 88 | } |
| 89 | return block.text as string |
| 90 | }).join('') |
| 91 | } |
| 92 | |
| 93 | export function promptOf(messages: unknown): string { |
| 94 | if (!Array.isArray(messages) || messages.length === 0) throw invalid('the llm broker needs at least one message') |
| 95 | const turns = messages.map((message) => { |
| 96 | if (message === null || typeof message !== 'object' || typeof message.role !== 'string') throw invalid('each message has a role and content') |
| 97 | if (message.role === 'tool') throw invalid('tool results are not brokered') |
| 98 | return { role: message.role as string, text: textOf(message.content) } |
| 99 | }) |
| 100 | const only = turns.length === 1 ? turns[0] : undefined |
| 101 | if (only !== undefined && only.role === 'user') return only.text |
| 102 | return turns.map((turn) => `${turn.role}: ${turn.text}`).join('\n\n') |
| 103 | } |
| 104 | |
| 105 | function modelInfo(model: BrokeredModel) { |
| 106 | return { |
| 107 | provider: model.provider, |
| 108 | id: model.id, |
| 109 | name: model.name, |
| 110 | inputModalities: ['text'] as const, |
| 111 | ...(typeof model.context_window === 'number' ? { context: { contextWindow: model.context_window } } : {}), |
| 112 | defaultMaxTokens: model.default_max_output_tokens, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | function usageChunk(usage: BrokeredUsage): Chunk | undefined { |
| 117 | if (usage.coverage !== 'reported' || typeof usage.input_tokens !== 'number' || typeof usage.output_tokens !== 'number') return undefined |
| 118 | return { |
| 119 | type: 'usage', |
| 120 | usage: { |
| 121 | inputTokens: usage.input_tokens, |
| 122 | outputTokens: usage.output_tokens, |
| 123 | totalTokens: usage.input_tokens + usage.output_tokens, |
| 124 | ...(typeof usage.cache_read_tokens === 'number' ? { cacheReadTokens: usage.cache_read_tokens } : {}), |
| 125 | ...(typeof usage.cache_write_tokens === 'number' ? { cacheWriteTokens: usage.cache_write_tokens } : {}), |
| 126 | ...(typeof usage.reasoning_tokens === 'number' ? { reasoningTokens: usage.reasoning_tokens } : {}), |
| 127 | }, |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | export const llmAdapter: DshAdapter = { |
| 132 | service: 'llm', |
| 133 | define(host: AdapterHost) { |
| 134 | class LlmService extends Service { |
| 135 | constructor(ctx: any) { super(ctx, 'llm') } |
| 136 | |
| 137 | async catalog(): Promise<BrokeredCatalog> { |
| 138 | return catalogOf(await host.broker(this.ctx, 'llm', 'catalog', {})) |
| 139 | } |
| 140 | |
| 141 | async complete(input: { prompt: string, system?: string, provider?: string, model?: string, maxTokens?: number, timeoutMs?: number }): Promise<BrokeredCompletion> { |
| 142 | if (input === null || typeof input !== 'object' || typeof input.prompt !== 'string') throw invalid('llm.complete takes { prompt }') |
| 143 | if (input.system !== undefined && typeof input.system !== 'string') throw invalid('system must be a string') |
| 144 | if (input.provider !== undefined && typeof input.provider !== 'string') throw invalid('provider must be a string') |
| 145 | if (input.model !== undefined && typeof input.model !== 'string') throw invalid('model must be a string') |
| 146 | if (input.maxTokens !== undefined && (typeof input.maxTokens !== 'number' || !Number.isInteger(input.maxTokens) || input.maxTokens <= 0 || input.maxTokens > 0xffff_ffff)) { |
| 147 | throw invalid('maxTokens must be a positive integer') |
| 148 | } |
| 149 | if (input.timeoutMs !== undefined && (typeof input.timeoutMs !== 'number' || !Number.isSafeInteger(input.timeoutMs) || input.timeoutMs <= 0)) { |
| 150 | throw invalid('timeoutMs must be a positive integer') |
| 151 | } |
| 152 | return completionOf(await host.broker(this.ctx, 'llm', 'complete', { |
| 153 | prompt: input.prompt, |
| 154 | ...(input.system !== undefined ? { system: input.system } : {}), |
| 155 | ...(input.provider !== undefined ? { provider: input.provider } : {}), |
| 156 | ...(input.model !== undefined ? { model: input.model } : {}), |
| 157 | ...(input.maxTokens !== undefined ? { max_output_tokens: input.maxTokens } : {}), |
| 158 | ...(input.timeoutMs !== undefined ? { timeout_ms: input.timeoutMs } : {}), |
| 159 | })) |
| 160 | } |
| 161 | |
| 162 | async listModels(provider: unknown) { |
| 163 | const catalog = await this.catalog() |
| 164 | return catalog.models.filter((model) => model.provider === provider).map(modelInfo) |
| 165 | } |
| 166 | |
| 167 | async resolveModelInfo(provider: unknown, model: unknown) { |
| 168 | const found = (await this.catalog()).models.find((candidate) => candidate.provider === provider && candidate.id === model) |
| 169 | if (found === undefined) throw new RpcError(ErrorCode.NotAvailable, 'the llm broker serves only the models in its catalog') |
| 170 | return modelInfo(found) |
| 171 | } |
| 172 | |
| 173 | async* stream(options: StreamOptions): AsyncGenerator<Chunk> { |
| 174 | if (options === null || typeof options !== 'object') throw invalid('llm.stream takes generate options') |
| 175 | if ((options.tools !== undefined && (!Array.isArray(options.tools) || options.tools.length > 0)) || options.toolHistory !== undefined) throw invalid('the llm broker runs text completions without tools') |
| 176 | const prompt = promptOf(options.messages) |
| 177 | if (options.system !== undefined && typeof options.system !== 'string') throw invalid('system must be a string') |
| 178 | if (options.provider !== undefined && typeof options.provider !== 'string') throw invalid('provider must be a string') |
| 179 | if (options.model !== undefined && typeof options.model !== 'string') throw invalid('model must be a string') |
| 180 | if (options.maxTokens !== undefined && (typeof options.maxTokens !== 'number' || !Number.isInteger(options.maxTokens) || options.maxTokens <= 0 || options.maxTokens > 0xffff_ffff)) { |
| 181 | throw invalid('maxTokens must be a positive integer') |
| 182 | } |
| 183 | const isAborted = () => options.signal?.aborted === true |
| 184 | const aborted = (): Chunk => ({ type: 'finish', reason: { kind: 'aborted', failure: { message: 'the model call was aborted', code: 'ABORTED' } } }) |
| 185 | if (isAborted()) { |
| 186 | yield aborted() |
| 187 | return |
| 188 | } |
| 189 | let completion: BrokeredCompletion |
| 190 | try { |
| 191 | completion = await this.complete({ |
| 192 | prompt, |
| 193 | ...(options.system !== undefined ? { system: options.system } : {}), |
| 194 | ...(options.provider !== undefined ? { provider: options.provider } : {}), |
| 195 | ...(options.model !== undefined ? { model: options.model } : {}), |
| 196 | ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}), |
| 197 | }) |
| 198 | } catch (error) { |
| 199 | if (isAborted()) { |
| 200 | yield aborted() |
| 201 | return |
| 202 | } |
| 203 | const message = error instanceof Error ? error.message : 'the model call did not complete' |
| 204 | yield { type: 'finish', reason: { kind: 'error', failure: { message, code: 'BROKER_REFUSED' } } } |
| 205 | return |
| 206 | } |
| 207 | if (isAborted()) { |
| 208 | yield aborted() |
| 209 | return |
| 210 | } |
| 211 | yield { type: 'block-start', index: 0, blockType: 'text' } |
| 212 | yield { type: 'text-delta', index: 0, text: completion.text } |
| 213 | yield { type: 'block-end', index: 0, block: { type: 'text', text: completion.text } } |
| 214 | const usage = usageChunk(completion.usage) |
| 215 | if (usage !== undefined) yield usage |
| 216 | yield { type: 'finish', reason: { kind: 'stop' } } |
| 217 | } |
| 218 | |
| 219 | listProviders(): never { return notBrokered('listProviders') } |
| 220 | registerAdapter(): never { return notBrokered('registerAdapter') } |
| 221 | registerConfigurableProviders(): never { return notBrokered('registerConfigurableProviders') } |
| 222 | listConfigurableProviders(): never { return notBrokered('listConfigurableProviders') } |
| 223 | registerModelDiscovery(): never { return notBrokered('registerModelDiscovery') } |
| 224 | discoverModels(): never { return notBrokered('discoverModels') } |
| 225 | prepareCall(): never { return notBrokered('prepareCall') } |
| 226 | resolveCallConfig(): never { return notBrokered('resolveCallConfig') } |
| 227 | } |
| 228 | Object.freeze(LlmService.prototype) |
| 229 | return LlmService |
| 230 | }, |
| 231 | } |
| 232 |