|
| 1 | +import { Anthropic } from "@anthropic-ai/sdk" |
| 2 | +import OpenAI from "openai" |
| 3 | + |
| 4 | +import { |
| 5 | + heliconeDefaultModelId, |
| 6 | + heliconeDefaultModelInfo, |
| 7 | + heliconeModels, |
| 8 | + DEEP_SEEK_DEFAULT_TEMPERATURE, |
| 9 | +} from "@roo-code/types" |
| 10 | + |
| 11 | +import type { ApiHandlerOptions, ModelRecord } from "../../shared/api" |
| 12 | + |
| 13 | +import { convertToOpenAiMessages } from "../transform/openai-format" |
| 14 | +import { ApiStreamChunk } from "../transform/stream" |
| 15 | +import { convertToR1Format } from "../transform/r1-format" |
| 16 | +import { getModelParams } from "../transform/model-params" |
| 17 | + |
| 18 | +import { DEFAULT_HEADERS } from "./constants" |
| 19 | +import { BaseProvider } from "./base-provider" |
| 20 | +import type { SingleCompletionHandler } from "../index" |
| 21 | +import { handleOpenAIError } from "./utils/openai-error-handler" |
| 22 | + |
| 23 | +export class HeliconeHandler extends BaseProvider implements SingleCompletionHandler { |
| 24 | + protected options: ApiHandlerOptions |
| 25 | + private client: OpenAI |
| 26 | + protected models: ModelRecord = {} |
| 27 | + private readonly providerName = "Helicone" |
| 28 | + |
| 29 | + constructor(options: ApiHandlerOptions) { |
| 30 | + super() |
| 31 | + this.options = options |
| 32 | + |
| 33 | + const baseURL = this.options.heliconeBaseUrl || "https://ai-gateway.helicone.ai/v1" |
| 34 | + const apiKey = this.options.heliconeApiKey ?? "not-provided" |
| 35 | + |
| 36 | + this.client = new OpenAI({ baseURL, apiKey, defaultHeaders: DEFAULT_HEADERS }) |
| 37 | + } |
| 38 | + |
| 39 | + override async *createMessage( |
| 40 | + systemPrompt: string, |
| 41 | + messages: Anthropic.Messages.MessageParam[], |
| 42 | + ): AsyncGenerator<ApiStreamChunk> { |
| 43 | + const model = await this.fetchModel() |
| 44 | + |
| 45 | + let { id: modelId, maxTokens, temperature } = model |
| 46 | + |
| 47 | + // Convert Anthropic messages to OpenAI format. |
| 48 | + let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ |
| 49 | + { role: "system", content: systemPrompt }, |
| 50 | + ...convertToOpenAiMessages(messages), |
| 51 | + ] |
| 52 | + |
| 53 | + // DeepSeek and similar reasoning models recommend using user instead of system role. |
| 54 | + if (this.isDeepSeekR1(modelId) || this.isPerplexityReasoning(modelId)) { |
| 55 | + openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages]) |
| 56 | + // DeepSeek recommended default temperature |
| 57 | + temperature = this.options.modelTemperature ?? DEEP_SEEK_DEFAULT_TEMPERATURE |
| 58 | + } |
| 59 | + |
| 60 | + // TODO [HELICONE]: add automatic gemini/anthropic cache breakpoints |
| 61 | + |
| 62 | + const completionParams: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = { |
| 63 | + model: modelId, |
| 64 | + ...(maxTokens && maxTokens > 0 && { max_tokens: maxTokens }), |
| 65 | + temperature, |
| 66 | + messages: openAiMessages, |
| 67 | + stream: true, |
| 68 | + stream_options: { include_usage: true }, |
| 69 | + } |
| 70 | + |
| 71 | + let stream |
| 72 | + try { |
| 73 | + stream = await this.client.chat.completions.create(completionParams) |
| 74 | + } catch (error) { |
| 75 | + throw handleOpenAIError(error, this.providerName) |
| 76 | + } |
| 77 | + |
| 78 | + let lastUsage: any | undefined = undefined |
| 79 | + |
| 80 | + for await (const chunk of stream) { |
| 81 | + const delta = chunk.choices[0]?.delta |
| 82 | + |
| 83 | + if ( |
| 84 | + "reasoning" in (delta || {}) && |
| 85 | + (delta as any).reasoning && |
| 86 | + typeof (delta as any).reasoning === "string" |
| 87 | + ) { |
| 88 | + yield { type: "reasoning", text: (delta as any).reasoning as string } |
| 89 | + } |
| 90 | + |
| 91 | + if (delta?.content) { |
| 92 | + yield { type: "text", text: delta.content } |
| 93 | + } |
| 94 | + |
| 95 | + if (chunk.usage) { |
| 96 | + lastUsage = chunk.usage |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + if (lastUsage) { |
| 101 | + yield { |
| 102 | + type: "usage", |
| 103 | + inputTokens: lastUsage.prompt_tokens || 0, |
| 104 | + outputTokens: lastUsage.completion_tokens || 0, |
| 105 | + cacheReadTokens: lastUsage.prompt_tokens_details?.cached_tokens, |
| 106 | + reasoningTokens: lastUsage.completion_tokens_details?.reasoning_tokens, |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + public async fetchModel() { |
| 112 | + this.models = heliconeModels as unknown as ModelRecord |
| 113 | + return this.getModel() |
| 114 | + } |
| 115 | + |
| 116 | + override getModel() { |
| 117 | + const id = this.options.apiModelId ?? heliconeDefaultModelId |
| 118 | + const info = this.models[id] ?? heliconeDefaultModelInfo |
| 119 | + |
| 120 | + const params = getModelParams({ |
| 121 | + format: "openai", |
| 122 | + modelId: id, |
| 123 | + model: info, |
| 124 | + settings: this.options, |
| 125 | + defaultTemperature: |
| 126 | + this.isDeepSeekR1(id) || this.isPerplexityReasoning(id) ? DEEP_SEEK_DEFAULT_TEMPERATURE : 0, |
| 127 | + }) |
| 128 | + |
| 129 | + // Apply a small topP tweak for DeepSeek-style reasoning models |
| 130 | + const topP = this.isDeepSeekR1(id) || this.isPerplexityReasoning(id) ? 0.95 : undefined |
| 131 | + return { id, info, topP, ...params } |
| 132 | + } |
| 133 | + |
| 134 | + async completePrompt(prompt: string) { |
| 135 | + let { id: modelId, maxTokens, temperature } = await this.fetchModel() |
| 136 | + |
| 137 | + const completionParams: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = { |
| 138 | + model: modelId, |
| 139 | + ...(maxTokens && maxTokens > 0 && { max_tokens: maxTokens }), |
| 140 | + temperature, |
| 141 | + messages: [{ role: "user", content: prompt }], |
| 142 | + stream: false, |
| 143 | + } |
| 144 | + |
| 145 | + let response |
| 146 | + try { |
| 147 | + response = await this.client.chat.completions.create(completionParams) |
| 148 | + } catch (error) { |
| 149 | + throw handleOpenAIError(error, this.providerName) |
| 150 | + } |
| 151 | + |
| 152 | + if ("error" in (response as any)) { |
| 153 | + const error = (response as any).error as { message?: string; code?: number } |
| 154 | + throw new Error(`Helicone API Error ${error?.code}: ${error?.message}`) |
| 155 | + } |
| 156 | + |
| 157 | + const completion = response as OpenAI.Chat.ChatCompletion |
| 158 | + return completion.choices[0]?.message?.content || "" |
| 159 | + } |
| 160 | + |
| 161 | + private isDeepSeekR1(modelId: string): boolean { |
| 162 | + return modelId.includes("deepseek-r1") |
| 163 | + } |
| 164 | + |
| 165 | + private isPerplexityReasoning(modelId: string): boolean { |
| 166 | + return modelId.includes("sonar-reasoning") |
| 167 | + } |
| 168 | +} |
0 commit comments