From a23ba0818cf55c747976d71e0b296d19ed7fc316 Mon Sep 17 00:00:00 2001 From: Zhang Jianbin <1257817341@qq.com> Date: Wed, 9 Apr 2025 10:31:20 +0800 Subject: [PATCH] feat:add shengsuanyun api providers. --- src/api/index.ts | 3 + src/api/providers/shengsuanyun.ts | 157 ++++++++++++++++++ src/core/controller/index.ts | 2 + src/core/storage/state-keys.ts | 1 + src/core/storage/state.ts | 6 + src/shared/api.ts | 72 ++++++++ .../src/components/settings/ApiOptions.tsx | 37 +++++ .../settings/__tests__/APIOptions.spec.tsx | 56 ++++--- webview-ui/src/utils/validate.ts | 5 + 9 files changed, 319 insertions(+), 20 deletions(-) create mode 100644 src/api/providers/shengsuanyun.ts diff --git a/src/api/index.ts b/src/api/index.ts index 87b67748..33ba7006 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -22,6 +22,7 @@ import { LiteLlmHandler } from "./providers/litellm" import { AskSageHandler } from "./providers/asksage" import { XAIHandler } from "./providers/xai" import { SambanovaHandler } from "./providers/sambanova" +import { ShengsuanyunHandler } from "./providers/shengsuanyun" export interface ApiHandler { createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream @@ -78,6 +79,8 @@ export function buildApiHandler(configuration: ApiConfiguration): ApiHandler { return new XAIHandler(options) case "sambanova": return new SambanovaHandler(options) + case "shengsuanyun": + return new ShengsuanyunHandler(options) default: return new AnthropicHandler(options) } diff --git a/src/api/providers/shengsuanyun.ts b/src/api/providers/shengsuanyun.ts new file mode 100644 index 00000000..28b89600 --- /dev/null +++ b/src/api/providers/shengsuanyun.ts @@ -0,0 +1,157 @@ +import { Anthropic } from "@anthropic-ai/sdk" +import axios from "axios" +import { setTimeout as setTimeoutPromise } from "node:timers/promises" +import OpenAI from "openai" +import { ApiHandler } from "../" +import { + ApiHandlerOptions, + ModelInfo, + shengsuanyunDefaultModelId, + ShengSuanYunModelId, + shengsuanyunModels, +} from "../../shared/api" +import { withRetry } from "../retry" +import { createOpenRouterStream } from "../transform/openrouter-stream" +import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" +import { OpenRouterErrorResponse } from "./types" +import { calculateApiCostOpenAI } from "../../utils/cost" + +export class ShengsuanyunHandler implements ApiHandler { + private options: ApiHandlerOptions + private client: OpenAI + lastGenerationId?: string + + constructor(options: ApiHandlerOptions) { + this.options = options + this.client = new OpenAI({ + baseURL: "https://router.shengsuanyun.com/api/v1", + apiKey: this.options.shengsuanyunApiKey, + defaultHeaders: { + "HTTP-Referer": "https://cline.bot", // Optional, for including your app on openrouter.ai rankings. + "X-Title": "Cline", // Optional. Shows in rankings on openrouter.ai. + }, + }) + } + + @withRetry() + async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + this.lastGenerationId = undefined + const model = this.getModel() + const stream = await createOpenRouterStream( + this.client, + systemPrompt, + messages, + model, + this.options.o3MiniReasoningEffort, + this.options.thinkingBudgetTokens, + this.options.openRouterProviderSorting, + ) + + let didOutputUsage: boolean = false + + for await (const chunk of stream) { + // openrouter returns an error object instead of the openai sdk throwing an error + if ("error" in chunk) { + const error = chunk.error as OpenRouterErrorResponse["error"] + console.error(`OpenRouter API Error: ${error?.code} - ${error?.message}`) + // Include metadata in the error message if available + const metadataStr = error.metadata ? `\nMetadata: ${JSON.stringify(error.metadata, null, 2)}` : "" + throw new Error(`OpenRouter API Error ${error.code}: ${error.message}${metadataStr}`) + } + + if (!this.lastGenerationId && chunk.id) { + this.lastGenerationId = chunk.id + } + + const delta = chunk.choices[0]?.delta + if (delta?.content) { + yield { + type: "text", + text: delta.content, + } + } + + // Reasoning tokens are returned separately from the content + if ("reasoning" in delta && delta.reasoning) { + yield { + type: "reasoning", + // @ts-ignore-next-line + reasoning: delta.reasoning, + } + } + + if (!didOutputUsage && chunk.usage) { + const inputTokens = chunk.usage.prompt_tokens || 0 + const outputTokens = chunk.usage.completion_tokens || 0 + yield { + type: "usage", + inputTokens: inputTokens, + outputTokens: outputTokens, + // @ts-ignore-next-line + // totalCost: chunk.usage.cost || 0, + totalCost: calculateApiCostOpenAI(model.info, inputTokens, outputTokens), + } + didOutputUsage = true + } + } + + // Fallback to generation endpoint if usage chunk not returned ; NotImplemented yet + if (!didOutputUsage) { + const apiStreamUsage = await this.getApiStreamUsage() + if (apiStreamUsage) { + yield apiStreamUsage + } + } + } + + async getApiStreamUsage(): Promise { + if (this.lastGenerationId) { + await setTimeoutPromise(500) // FIXME: necessary delay to ensure generation endpoint is ready + try { + const generationIterator = this.fetchGenerationDetails(this.lastGenerationId) + const generation = (await generationIterator.next()).value + // console.log("OpenRouter generation details:", generation) + return { + type: "usage", + // cacheWriteTokens: 0, + // cacheReadTokens: 0, + // openrouter generation endpoint fails often + inputTokens: generation?.native_tokens_prompt || 0, + outputTokens: generation?.native_tokens_completion || 0, + totalCost: generation?.total_cost || 0, + } + } catch (error) { + // ignore if fails + console.error("Error fetching OpenRouter generation details:", error) + } + } + return undefined + } + + @withRetry({ maxRetries: 4, baseDelay: 250, maxDelay: 1000, retryAllErrors: true }) + async *fetchGenerationDetails(genId: string) { + // console.log("Fetching generation details for:", genId) + try { + const response = await axios.get(`https://router.shengsuanyun.com/api/v1/generation?id=${genId}`, { + headers: { + Authorization: `Bearer ${this.options.shengsuanyunApiKey}`, + }, + timeout: 15_000, // this request hangs sometimes + }) + yield response.data?.data + } catch (error) { + // ignore if fails + console.error("Error fetching OpenRouter generation details:", error) + throw error + } + } + + getModel(): { id: string; info: ModelInfo } { + const modelId = this.options.apiModelId + if (modelId && modelId in shengsuanyunModels) { + const id = modelId as ShengSuanYunModelId + return { id, info: shengsuanyunModels[id] } + } + return { id: shengsuanyunDefaultModelId, info: shengsuanyunModels[shengsuanyunDefaultModelId] } + } +} diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index ce9249ff..4341f053 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -925,6 +925,7 @@ export class Controller { case "openai-native": case "qwen": case "deepseek": + case "shengsuanyun": await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.apiModelId) break case "openrouter": @@ -971,6 +972,7 @@ export class Controller { case "openai-native": case "qwen": case "deepseek": + case "shengsuanyun": await updateGlobalState(this.context, "apiModelId", newModelId) break case "openrouter": diff --git a/src/core/storage/state-keys.ts b/src/core/storage/state-keys.ts index 96cc6b33..064673cc 100644 --- a/src/core/storage/state-keys.ts +++ b/src/core/storage/state-keys.ts @@ -19,6 +19,7 @@ export type SecretKey = | "asksageApiKey" | "xaiApiKey" | "sambanovaApiKey" + | "shengsuanyunApiKey" export type GlobalStateKey = | "apiProvider" | "apiModelId" diff --git a/src/core/storage/state.ts b/src/core/storage/state.ts index 20794097..7c01280a 100644 --- a/src/core/storage/state.ts +++ b/src/core/storage/state.ts @@ -116,6 +116,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { xaiApiKey, thinkingBudgetTokens, sambanovaApiKey, + shengsuanyunApiKey, planActSeparateModelsSettingRaw, ] = await Promise.all([ getGlobalState(context, "apiProvider") as Promise, @@ -182,6 +183,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { getSecret(context, "xaiApiKey") as Promise, getGlobalState(context, "thinkingBudgetTokens") as Promise, getSecret(context, "sambanovaApiKey") as Promise, + getSecret(context, "shengsuanyunApiKey") as Promise, getGlobalState(context, "planActSeparateModelsSetting") as Promise, ]) @@ -275,6 +277,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { asksageApiUrl, xaiApiKey, sambanovaApiKey, + shengsuanyunApiKey, }, lastShownAnnouncementId, customInstructions, @@ -347,6 +350,7 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a thinkingBudgetTokens, clineApiKey, sambanovaApiKey, + shengsuanyunApiKey, } = apiConfiguration await updateGlobalState(context, "apiProvider", apiProvider) await updateGlobalState(context, "apiModelId", apiModelId) @@ -399,6 +403,7 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a await updateGlobalState(context, "thinkingBudgetTokens", thinkingBudgetTokens) await storeSecret(context, "clineApiKey", clineApiKey) await storeSecret(context, "sambanovaApiKey", sambanovaApiKey) + await storeSecret(context, "shengsuanyunApiKey", shengsuanyunApiKey) } export async function resetExtensionState(context: vscode.ExtensionContext) { @@ -425,6 +430,7 @@ export async function resetExtensionState(context: vscode.ExtensionContext) { "asksageApiKey", "xaiApiKey", "sambanovaApiKey", + "shengsuanyunApiKey", ] for (const key of secretKeys) { await storeSecret(context, key, undefined) diff --git a/src/shared/api.ts b/src/shared/api.ts index 648cc92c..e4b245bb 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -20,6 +20,7 @@ export type ApiProvider = | "asksage" | "xai" | "sambanova" + | "shengsuanyun" export interface ApiHandlerOptions { apiModelId?: string @@ -74,6 +75,7 @@ export interface ApiHandlerOptions { xaiApiKey?: string thinkingBudgetTokens?: number sambanovaApiKey?: string + shengsuanyunApiKey?: string } export type ApiConfiguration = ApiHandlerOptions & { @@ -1476,3 +1478,73 @@ export const sambanovaModels = { outputPrice: 1.5, }, } as const satisfies Record + +// ShengSuanYun +// https://router.shengsuanyun.com/model +export type ShengSuanYunModelId = keyof typeof shengsuanyunModels +export const shengsuanyunDefaultModelId: ShengSuanYunModelId = "deepseek/deepseek-v3" +export const shengsuanyunModels = { + "anthropic/claude-3.7-sonnet": { + maxTokens: 128_000, + contextWindow: 200_000, + supportsImages: false, + supportsPromptCache: false, // supports context caching, but not in the way anthropic does it (deepseek reports input tokens and reads/writes in the same usage report) FIXME: we need to show users cache stats how deepseek does it + inputPrice: 3, // technically there is no input price, it's all either a cache hit or miss (ApiOptions will not show this) + outputPrice: 15, + }, + "anthropic/claude-3.7-sonnet:thinking": { + maxTokens: 128_000, + contextWindow: 200_000, + supportsImages: false, + supportsPromptCache: false, + inputPrice: 0.3, + outputPrice: 15, + }, + "google/gemini-2.0-flash-001": { + maxTokens: 8_000, + contextWindow: 1000_000, + supportsImages: false, + supportsPromptCache: false, + inputPrice: 0.1, + outputPrice: 0.4, + }, + "deepseek/deepseek-v3": { + maxTokens: 164_000, + contextWindow: 164_000, + supportsImages: false, + supportsPromptCache: false, + inputPrice: 0.4, + outputPrice: 0.89, + }, + "deepseek/deepseek-r1": { + maxTokens: 16_000, + contextWindow: 64_000, + supportsImages: false, + supportsPromptCache: false, + inputPrice: 0.55, + outputPrice: 1.1, + }, + "qwen/qwen-plus": { + maxTokens: 8_000, + contextWindow: 33_000, + supportsImages: false, + supportsPromptCache: false, + inputPrice: 0.48, + outputPrice: 0.96, + }, + "qwen/qvq-72b": { + maxTokens: 8_000, + contextWindow: 131_000, + supportsImages: false, + supportsPromptCache: false, + outputPrice: 4.94, + }, + "meta-llama/llama-3.3-70b-instruct": { + maxTokens: 131_000, + contextWindow: 131_000, + supportsImages: false, + supportsPromptCache: false, + inputPrice: 0.12, + outputPrice: 0.3, + }, +} as const satisfies Record diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index d84bad2e..492625bd 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -48,6 +48,8 @@ import { doubaoModels, doubaoDefaultModelId, liteLlmModelInfoSaneDefaults, + shengsuanyunModels, + shengsuanyunDefaultModelId, } from "@shared/api" import { ExtensionMessage } from "@shared/ExtensionMessage" import { useExtensionState } from "@/context/ExtensionStateContext" @@ -216,6 +218,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is AskSage X AI SambaNova + ShengSuanYun @@ -1434,6 +1437,37 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is )} + {selectedProvider === "shengsuanyun" && ( +
+ + ShengSuanYun API Key + +

+ This key is stored locally and only used to make API requests from this extension. + {!apiConfiguration?.shengsuanyunApiKey && ( + + You can get a ShengSuanYun API key by signing up here. + + )} +

+
+ )} + {apiErrorMessage && (

{((selectedProvider === "anthropic" && selectedModelId === "claude-3-7-sonnet-20250219") || @@ -1807,6 +1842,8 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration): return getProviderData(xaiModels, xaiDefaultModelId) case "sambanova": return getProviderData(sambanovaModels, sambanovaDefaultModelId) + case "shengsuanyun": + return getProviderData(shengsuanyunModels, shengsuanyunDefaultModelId) default: return getProviderData(anthropicModels, anthropicDefaultModelId) } diff --git a/webview-ui/src/components/settings/__tests__/APIOptions.spec.tsx b/webview-ui/src/components/settings/__tests__/APIOptions.spec.tsx index 0165ed2e..7589c109 100644 --- a/webview-ui/src/components/settings/__tests__/APIOptions.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/APIOptions.spec.tsx @@ -1,13 +1,22 @@ import { render, screen, fireEvent } from "@testing-library/react" -import { describe, it, expect, vi } from "vitest" +import { describe, it, expect, vi, beforeEach } from "vitest" import ApiOptions from "../ApiOptions" import { ExtensionStateContextProvider } from "@/context/ExtensionStateContext" -vi.mock("../../../context/ExtensionStateContext", async (importOriginal) => { - const actual = await importOriginal() +// Define proper typing for the global vscode object +declare global { + interface Window { + vscode: { + postMessage: (message: any) => void + } + } +} + +// First mock setup for "requesty" provider +vi.mock("../../../context/ExtensionStateContext", async () => { + const actual = (await vi.importActual("../../../context/ExtensionStateContext")) as any return { - ...actual, - // your mocked methods + ...(actual || {}), useExtensionState: vi.fn(() => ({ apiConfiguration: { apiProvider: "requesty", @@ -20,12 +29,13 @@ vi.mock("../../../context/ExtensionStateContext", async (importOriginal) => { } }) -describe("ApiOptions Component", () => { - vi.clearAllMocks() +describe("ApiOptions Component - Requesty", () => { const mockPostMessage = vi.fn() beforeEach(() => { - global.vscode = { postMessage: mockPostMessage } as any + vi.clearAllMocks() + // Use window.vscode instead of global.vscode + window.vscode = { postMessage: mockPostMessage } }) it("renders Requesty API Key input", () => { @@ -49,11 +59,14 @@ describe("ApiOptions Component", () => { }) }) -vi.mock("../../../context/ExtensionStateContext", async (importOriginal) => { - const actual = await importOriginal() +// Reset the mock before creating a new one +vi.resetModules() + +// Second mock setup for "together" provider +vi.mock("../../../context/ExtensionStateContext", async () => { + const actual = (await vi.importActual("../../../context/ExtensionStateContext")) as any return { - ...actual, - // your mocked methods + ...(actual || {}), useExtensionState: vi.fn(() => ({ apiConfiguration: { apiProvider: "together", @@ -66,12 +79,12 @@ vi.mock("../../../context/ExtensionStateContext", async (importOriginal) => { } }) -describe("ApiOptions Component", () => { - vi.clearAllMocks() +describe("ApiOptions Component - Together", () => { const mockPostMessage = vi.fn() beforeEach(() => { - global.vscode = { postMessage: mockPostMessage } as any + vi.clearAllMocks() + window.vscode = { postMessage: mockPostMessage } }) it("renders Together API Key input", () => { @@ -95,11 +108,14 @@ describe("ApiOptions Component", () => { }) }) -vi.mock("../../../context/ExtensionStateContext", async (importOriginal) => { - const actual = await importOriginal() +// Reset the mock before creating a new one +vi.resetModules() + +// Third mock setup for "openai" provider +vi.mock("../../../context/ExtensionStateContext", async () => { + const actual = (await vi.importActual("../../../context/ExtensionStateContext")) as any return { - ...actual, - // your mocked methods + ...(actual || {}), useExtensionState: vi.fn(() => ({ apiConfiguration: { apiProvider: "openai", @@ -117,7 +133,7 @@ describe("OpenApiInfoOptions", () => { beforeEach(() => { vi.clearAllMocks() - global.vscode = { postMessage: mockPostMessage } + window.vscode = { postMessage: mockPostMessage } }) it("renders OpenAI Supports Images input", () => { diff --git a/webview-ui/src/utils/validate.ts b/webview-ui/src/utils/validate.ts index f9fc9b32..c8f07f98 100644 --- a/webview-ui/src/utils/validate.ts +++ b/webview-ui/src/utils/validate.ts @@ -103,6 +103,11 @@ export function validateApiConfiguration(apiConfiguration?: ApiConfiguration): s return "You must provide a valid API key or choose a different provider." } break + case "shengsuanyun": + if (!apiConfiguration.shengsuanyunApiKey) { + return "You must provide a valid API key or choose a different provider." + } + break } } return undefined