Elffuss BraidHub

kikocis/continue public

Merge pull request #5807 from continuedev/nate/watsonx-rules-support

Nate/watsonx-rules-support
Changeset7cf339d22ff074dc1f1dac577af8986d22e1a362783d974fbb3df4b78186d806
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-05-22 22:19 -07:00
CommitterGitHub <noreply@github.com> · 2025-05-22 22:19 -07:00
Parents2eaf54ca9959, 5d93d5e48402

Browse the files at this changeset

14 files changed

modified core/llm/llms/stubs/ContinueProxy.ts +5 −0
@@ -27,8 +27,12 @@
2727 // to call whatever LLM API is chosen
2828 private actualApiBase?: string;
2929
30+ // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
31+ private configEnv?: Record<string, any>;
32+
3033 constructor(options: LLMOptions) {
3134 super(options);
35+ this.configEnv = options.env;
3236 this.actualApiBase = options.apiBase;
3337 this.apiKeyLocation = options.apiKeyLocation;
3438 this.orgScopeId = options.orgScopeId;
@@ -48,6 +52,7 @@
4852 apiKeyLocation: this.apiKeyLocation,
4953 apiBase: this.actualApiBase,
5054 orgScopeId: this.orgScopeId ?? null,
55+ env: this.configEnv,
5156 };
5257 return {
5358 continueProperties,
modified core/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/package.json +1 −1
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.38",
5+ "version": "1.1.39",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
modified gui/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/config-yaml/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/config-yaml",
9- "version": "1.0.87",
9+ "version": "1.0.88",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.14",
modified packages/config-yaml/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/config-yaml/src/load/clientRender.ts +1 −0
@@ -160,6 +160,7 @@
160160 apiKeyLocation: z.string().optional(),
161161 apiBase: z.string().optional(),
162162 orgScopeId: z.string().nullable(),
163+ env: z.record(z.string(), z.any()).optional(),
163164 });
164165
165166 export type ContinueProperties = z.infer<typeof continuePropertiesSchema>;
modified packages/openai-adapters/README.md +1 −1
@@ -64,7 +64,7 @@
6464 - [x] Vllm
6565 - [ ] Vertex AI
6666 - [x] Voyage AI
67-- [ ] WatsonX
67+- [x] WatsonX
6868 - [x] xAI
6969 - [x] Fireworks
7070 - [x] Moonshot
modified packages/openai-adapters/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.21",
3+ "version": "1.0.26",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
added packages/openai-adapters/src/apis/WatsonX.ts +314 −0
@@ -0,0 +1,314 @@
1+import { streamSse } from "@continuedev/fetch";
2+import { OpenAI } from "openai/index";
3+import {
4+ ChatCompletion,
5+ ChatCompletionChunk,
6+ ChatCompletionCreateParamsNonStreaming,
7+ ChatCompletionCreateParamsStreaming,
8+ Completion,
9+ CompletionCreateParamsNonStreaming,
10+ CompletionCreateParamsStreaming,
11+} from "openai/resources/index";
12+import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
13+import { WatsonXConfig } from "../types.js";
14+import { chatCompletion, customFetch } from "../util.js";
15+import {
16+ BaseLlmApi,
17+ CreateRerankResponse,
18+ FimCreateParamsStreaming,
19+ RerankCreateParams,
20+} from "./base.js";
21+
22+export class WatsonXApi implements BaseLlmApi {
23+ apiBase: string;
24+ apiVersion: string = "2023-05-29";
25+ projectId?: string;
26+ deploymentId?: string;
27+
28+ constructor(protected config: WatsonXConfig) {
29+ this.apiBase = config.apiBase ?? "https://us-south.ml.cloud.ibm.com";
30+ if (!this.apiBase.endsWith("/")) {
31+ this.apiBase += "/";
32+ }
33+ this.apiVersion = config.env.apiVersion ?? this.apiVersion;
34+ this.projectId = config.env.projectId;
35+ this.deploymentId = config.env.deploymentId;
36+ }
37+
38+ private async getHeaders(): Promise<Record<string, string>> {
39+ const bearer = await this.getBearerToken();
40+ return {
41+ "Content-Type": "application/json",
42+ Authorization: `Bearer ${bearer.token}`,
43+ };
44+ }
45+
46+ async getBearerToken(): Promise<{ token: string; expiration: number }> {
47+ if (this.apiBase?.includes("cloud.ibm.com")) {
48+ // watsonx SaaS
49+ const wxToken = (await (
50+ await customFetch(this.config.requestOptions)(
51+ `https://iam.cloud.ibm.com/identity/token?apikey=${this.config.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
52+ {
53+ method: "POST",
54+ headers: {
55+ "Content-Type": "application/x-www-form-urlencoded",
56+ Accept: "application/json",
57+ },
58+ },
59+ )
60+ ).json()) as any;
61+ return {
62+ token: wxToken["access_token"],
63+ expiration: wxToken["expiration"],
64+ };
65+ } else {
66+ // watsonx Software
67+ if (!this.config.apiKey?.includes(":")) {
68+ // Using ZenApiKey auth
69+ return {
70+ token: this.config.apiKey ?? "",
71+ expiration: -1,
72+ };
73+ } else {
74+ // Using username/password auth
75+ const userPass = this.config.apiKey?.split(":");
76+ const wxToken = (await (
77+ await customFetch(this.config.requestOptions)(
78+ `${this.apiBase}/icp4d-api/v1/authorize`,
79+ {
80+ method: "POST",
81+ headers: {
82+ "Content-Type": "application/json",
83+ Accept: "application/json",
84+ },
85+ body: JSON.stringify({
86+ username: userPass[0],
87+ password: userPass[1],
88+ }),
89+ },
90+ )
91+ ).json()) as any;
92+ const wxTokenExpiry = (await (
93+ await customFetch(this.config.requestOptions)(
94+ `${this.apiBase}/usermgmt/v1/user/tokenExpiry`,
95+ {
96+ method: "GET",
97+ headers: {
98+ Accept: "application/json",
99+ Authorization: `Bearer ${wxToken["token"]}`,
100+ },
101+ },
102+ )
103+ ).json()) as any;
104+ return {
105+ token: wxToken["token"],
106+ expiration: wxTokenExpiry["exp"],
107+ };
108+ }
109+ }
110+ }
111+
112+ private getEndpoint(endpoint: string): string {
113+ return `${this.apiBase}ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
114+ }
115+
116+ private _convertBody(oaiBody: ChatCompletionCreateParams) {
117+ const stopSequences = oaiBody.stop
118+ ? Array.isArray(oaiBody.stop)
119+ ? oaiBody.stop.filter((s) => s.trim() !== "")
120+ : [oaiBody.stop]
121+ : undefined;
122+
123+ const payload: any = {
124+ messages: oaiBody.messages,
125+ max_tokens: oaiBody.max_tokens ?? 1024,
126+ stop: stopSequences,
127+ frequency_penalty: oaiBody.frequency_penalty,
128+ presence_penalty: oaiBody.presence_penalty,
129+ };
130+
131+ if (!this.deploymentId) {
132+ payload.model_id = oaiBody.model;
133+ payload.project_id = this.projectId;
134+ }
135+
136+ if (oaiBody.temperature !== undefined) {
137+ payload.temperature = oaiBody.temperature;
138+ }
139+
140+ if (oaiBody.top_p !== undefined) {
141+ payload.top_p = oaiBody.top_p;
142+ }
143+
144+ if (oaiBody.tools) {
145+ payload.tools = oaiBody.tools;
146+ if (oaiBody.tool_choice) {
147+ payload.tool_choice = oaiBody.tool_choice;
148+ } else {
149+ payload.tool_choice_option = "auto";
150+ }
151+ }
152+
153+ return payload;
154+ }
155+
156+ async chatCompletionNonStream(
157+ body: ChatCompletionCreateParamsNonStreaming,
158+ signal: AbortSignal,
159+ ): Promise<ChatCompletion> {
160+ const generator = this.chatCompletionStream(
161+ {
162+ ...body,
163+ stream: true,
164+ },
165+ signal,
166+ );
167+
168+ let content = "";
169+ for await (const chunk of generator) {
170+ content += chunk.choices[0].delta.content ?? "";
171+ }
172+ return chatCompletion({
173+ content,
174+ model: body.model,
175+ });
176+ }
177+
178+ async *chatCompletionStream(
179+ body: ChatCompletionCreateParamsStreaming,
180+ signal: AbortSignal,
181+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
182+ const url = this.getEndpoint("chat");
183+ const headers = await this.getHeaders();
184+ const stringifiedBody = JSON.stringify(this._convertBody(body));
185+ const response = await customFetch(this.config.requestOptions)(url, {
186+ method: "POST",
187+ headers,
188+ body: stringifiedBody,
189+ signal,
190+ });
191+
192+ if (!response.ok || !response.body) {
193+ throw new Error(
194+ `Failed to stream chat completion: ${await response.text()}`,
195+ );
196+ }
197+
198+ for await (const value of streamSse(response as any)) {
199+ if (!value.choices?.[0]) {
200+ continue;
201+ }
202+ yield value;
203+ }
204+ }
205+
206+ async completionNonStream(
207+ body: CompletionCreateParamsNonStreaming,
208+ signal: AbortSignal,
209+ ): Promise<Completion> {
210+ throw new Error("Method not implemented.");
211+ }
212+
213+ async *completionStream(
214+ body: CompletionCreateParamsStreaming,
215+ signal: AbortSignal,
216+ ): AsyncGenerator<Completion, any, unknown> {
217+ const params = {
218+ decoding_method: body.temperature ? "sample" : "greedy",
219+ max_new_tokens: body.max_tokens ?? 1024,
220+ min_new_tokens: 1,
221+ stop_sequences: body.stop
222+ ? Array.isArray(body.stop)
223+ ? body.stop
224+ : [body.stop]
225+ : [],
226+ include_stop_sequence: false,
227+ repetition_penalty: body.frequency_penalty || 1,
228+ temperature: body.temperature,
229+ top_p: body.top_p,
230+ top_k: 100,
231+ };
232+
233+ const payload: any = {
234+ input: body.prompt,
235+ parameters: params,
236+ };
237+
238+ if (!this.deploymentId) {
239+ payload.model_id = body.model;
240+ payload.project_id = this.projectId;
241+ }
242+
243+ const url = this.getEndpoint("generation");
244+ const response = await customFetch(this.config.requestOptions)(url, {
245+ method: "POST",
246+ headers: await this.getHeaders(),
247+ body: JSON.stringify(payload),
248+ signal,
249+ });
250+
251+ if (!response.ok || !response.body) {
252+ throw new Error(`Failed to stream completion: ${await response.text()}`);
253+ }
254+
255+ let generatedText = "";
256+ for await (const value of streamSse(response as any)) {
257+ const lines = value.toString().split("\n");
258+ let generatedChunk = "";
259+
260+ lines.forEach((line: string) => {
261+ if (line.startsWith("data:")) {
262+ const dataStr = line.replace(/^data:\s+/, "");
263+ try {
264+ const data = JSON.parse(dataStr);
265+ data.results.forEach((result: any) => {
266+ generatedChunk += result.generated_text || "";
267+ });
268+ } catch (e) {
269+ // parsing error is expected with streaming response
270+ }
271+ }
272+ });
273+
274+ if (generatedChunk) {
275+ generatedText += generatedChunk;
276+ yield {
277+ id: `watsonx-${Date.now()}`,
278+ object: "text_completion",
279+ created: Date.now(),
280+ model: body.model,
281+ choices: [
282+ {
283+ text: generatedChunk,
284+ index: 0,
285+ logprobs: null,
286+ finish_reason: "stop",
287+ },
288+ ],
289+ };
290+ }
291+ }
292+ }
293+
294+ async *fimStream(
295+ body: FimCreateParamsStreaming,
296+ signal: AbortSignal,
297+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
298+ throw new Error("Method not implemented.");
299+ }
300+
301+ async embed(
302+ body: OpenAI.Embeddings.EmbeddingCreateParams,
303+ ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
304+ throw new Error("Method not implemented.");
305+ }
306+
307+ async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
308+ throw new Error("Method not implemented.");
309+ }
310+
311+ async list(): Promise<OpenAI.Models.Model[]> {
312+ throw new Error("Method not implemented.");
313+ }
314+}
modified packages/openai-adapters/src/index.ts +8 −3
@@ -11,6 +11,7 @@
1111 import { MoonshotApi } from "./apis/Moonshot.js";
1212 import { OpenAIApi } from "./apis/OpenAI.js";
1313 import { RelaceApi } from "./apis/Relace.js";
14+import { WatsonXApi } from "./apis/WatsonX.js";
1415 import { BaseLlmApi } from "./apis/base.js";
1516 import { LLMConfig, OpenAIConfigSchema } from "./types.js";
1617
@@ -48,6 +49,8 @@
4849 return new RelaceApi(config);
4950 case "inception":
5051 return new InceptionApi(config);
52+ case "watsonx":
53+ return new WatsonXApi(config);
5154 case "x-ai":
5255 return openAICompatible("https://api.x.ai/v1/", config);
5356 case "voyage":
@@ -75,7 +78,10 @@
7578 case "nvidia":
7679 return openAICompatible("https://integrate.api.nvidia.com/v1/", config);
7780 case "ovhcloud":
78- return openAICompatible("https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", config);
81+ return openAICompatible(
82+ "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
83+ config,
84+ );
7985 case "scaleway":
8086 return openAICompatible("https://api.scaleway.ai/v1/", config);
8187 case "fireworks":
@@ -111,10 +117,9 @@
111117 type Completion,
112118 type CompletionCreateParams,
113119 type CompletionCreateParamsNonStreaming,
114- type CompletionCreateParamsStreaming
120+ type CompletionCreateParamsStreaming,
115121 } from "openai/resources/index";
116122
117123 // export
118124 export type { BaseLlmApi } from "./apis/base.js";
119125 export type { LLMConfig } from "./types.js";
120-
modified packages/openai-adapters/src/test/main.test.ts +1 −0
@@ -10,6 +10,7 @@
1010 provider: config.provider as any,
1111 apiKey: config.apiKey,
1212 apiBase: config.apiBase,
13+ env: config.env,
1314 });
1415
1516 if (false) {
modified packages/openai-adapters/src/types.ts +12 −0
@@ -99,6 +99,17 @@
9999 });
100100 export type AnthropicConfig = z.infer<typeof AnthropicConfigSchema>;
101101
102+export const WatsonXConfigSchema = BasePlusConfig.extend({
103+ provider: z.literal("watsonx"),
104+ apiKey: z.string(),
105+ env: z.object({
106+ apiVersion: z.string().optional(),
107+ projectId: z.string().optional(),
108+ deploymentId: z.string().optional(),
109+ }),
110+});
111+export type WatsonXConfig = z.infer<typeof WatsonXConfigSchema>;
112+
102113 export const JinaConfigSchema = OpenAIConfigSchema.extend({
103114 provider: z.literal("jina"),
104115 });
@@ -118,6 +129,7 @@
118129 AzureConfigSchema,
119130 GeminiConfigSchema,
120131 AnthropicConfigSchema,
132+ WatsonXConfigSchema,
121133 JinaConfigSchema,
122134 MockConfigSchema,
123135 InceptionConfigSchema,