Merge branch 'dev' into code-gecko

This commit is contained in:
Luke Lashley 2024-10-27 22:33:48 -04:00 • committed by GitHub
commit 07cb40e4d2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 569 additions and 237 deletions

View file

@ -338,11 +338,7 @@ declare global {
capabilities?: ModelCapability;
// IBM watsonx options
watsonxUrl?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
deploymentId?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -768,7 +764,8 @@ declare global {
| "gemini"
| "continue-proxy"
| "deepinfra"
| "voyage";
| "voyage"
| "watsonx";
export interface EmbedOptions {
apiBase?: string;
@ -779,6 +776,7 @@ declare global {
apiVersion?: string;
requestOptions?: RequestOptions;
maxChunkSize?: number;
projectId?: string;
}
export interface EmbeddingsProviderDescription extends EmbedOptions {

17
core/index.d.ts vendored
View file

@ -363,16 +363,13 @@ export interface LLMOptions {
region?: string;
// GCP Options
projectId?: string;
capabilities?: ModelCapability;
// IBM watsonx options
watsonxUrl?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
// GCP and Watsonx Options
projectId?: string;
// IBM watsonx Options
deploymentId?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -606,6 +603,7 @@ type TemplateType =
| "codellama-70b"
| "llava"
| "gemma"
| "granite"
| "llama3";
type ModelProvider =
@ -830,6 +828,7 @@ export type EmbeddingsProviderName =
| "voyage"
| "mistral"
| "vertexai";
| "watsonx";
export interface EmbedOptions {
apiBase?: string;
@ -847,7 +846,7 @@ export interface EmbedOptions {
// AWS and GCP Options
region?: string;
// GCP Options
// GCP and Watsonx Options
projectId?: string;
}

View file

@ -0,0 +1,150 @@
import {
EmbeddingsProviderName,
EmbedOptions,
FetchFunction,
} from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider, {
IBaseEmbeddingsProvider,
} from "./BaseEmbeddingsProvider.js";
let accessToken = {
expiration: 0,
token: "",
};
class WatsonxEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "watsonx";
static maxBatchSize = 1000;
static defaultOptions: Partial<EmbedOptions> | undefined = {
model: "ibm/slate-125m-english-rtrvr-v2",
};
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (
this.options.apiBase?.includes("cloud.ibm.com")
) {
// watsonx SaaS
const wxToken = await (
await fetch(
`https://iam.cloud.ibm.com/identity/token?apikey=${this.options.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
},
)
).json();
return {
token: wxToken["access_token"],
expiration: wxToken["expiration"],
};
} else {
// watsonx Software
if (!this.options.apiKey?.includes(":")) {
// Using ZenApiKey auth
return {
token: this.options.apiKey ?? "",
expiration: -1,
};
} else {
// Using username/password auth
const userPass = this.options.apiKey?.split(":");
const wxToken = await (
await fetch(`${this.options.apiBase}/icp4d-api/v1/authorize`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
username: userPass[0],
password: userPass[1],
}),
})
).json();
const wxTokenExpiry = await (
await fetch(
`${this.options.apiBase}/usermgmt/v1/user/tokenExpiry`,
{
method: "GET",
headers: {
Accept: "application/json",
Authorization: `Bearer ${wxToken["token"]}`,
},
},
)
).json();
return {
token: wxToken["token"],
expiration: wxTokenExpiry["exp"],
};
}
}
}
async getSingleBatchEmbedding(batch: string[]) {
var now = new Date().getTime() / 1000;
if (
accessToken === undefined ||
now > accessToken.expiration ||
accessToken.token === undefined
) {
accessToken = await this.getBearerToken();
} else {
console.log(
`Reusing token (expires in ${(accessToken.expiration - now) / 60
} mins)`,
);
}
return await withExponentialBackoff<number[][]>(async () => {
const payload: any = {
inputs: batch,
parameters: {
truncate_input_tokens: 500,
return_options: { input_text: false },
},
model_id: this.options.model,
project_id: this.options.projectId,
};
const headers = {
"Content-Type": "application/json",
Authorization: `${accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${accessToken.token}`,
};
const resp = await this.fetch(
new URL(
`${this.options.apiBase}/ml/v1/text/embeddings?version=${this.options.apiVersion}`,
),
{
method: "POST",
body: JSON.stringify(payload),
headers: headers,
},
);
if (!resp.ok) {
throw new Error(`Failed to embed chunk: ${await resp.text()}`);
}
const data = await resp.json();
const embeddings = data.results;
if (!embeddings || embeddings.length === 0) {
throw new Error("Watsonx generated empty embedding");
}
return embeddings.map((e: any) => e.embedding);
});
}
async embed(chunks: string[]) {
const batchedChunks = this.getBatchedChunks(chunks);
const results = await Promise.all(
batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)),
);
return results.flat();
}
}
export default WatsonxEmbeddingsProvider;

View file

@ -15,6 +15,7 @@ import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider
import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js";
import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js";
import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js";
import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js";
type EmbeddingsProviderConstructor = new (
...args: any[]
@ -39,4 +40,5 @@ export const allEmbeddingsProviders: Record<
voyage: VoyageEmbeddingsProvider,
mistral: MistralEmbeddingsProvider,
vertexai: VertexEmbeddingsProvider
watsonx: WatsonxEmbeddingsProvider,
};

View file

@ -5,6 +5,7 @@ import {
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
gemmaTemplateMessage,
graniteTemplateMessages,
llama2TemplateMessages,
llama3TemplateMessages,
llavaTemplateMessages,
@ -47,6 +48,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"mistral",
"sambanova",
"vertexai"
"watsonx",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
@ -217,6 +219,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return "neural-chat";
}
if (lower.includes("granite")) {
return "granite";
}
return "chatml";
}
@ -250,6 +256,7 @@ function autodetectTemplateFunction(
llava: llavaTemplateMessages,
"codellama-70b": codeLlama70bTemplateMessages,
gemma: gemmaTemplateMessage,
granite: graniteTemplateMessages,
llama3: llama3TemplateMessages,
none: null,
};

View file

@ -114,13 +114,8 @@ export abstract class BaseLLM implements ILLM {
accountId?: string;
aiGatewaySlug?: string;
// For IBM watsonx only.
watsonxUrl?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
// For IBM watsonx
deploymentId?: string;
private _llmOptions: LLMOptions;
@ -186,13 +181,8 @@ export abstract class BaseLLM implements ILLM {
this.apiBase = options.apiBase;
this.cacheBehavior = options.cacheBehavior;
// for watsonx only
this.watsonxUrl = options.watsonxUrl;
this.watsonxCreds = options.watsonxCreds;
this.watsonxProjectId = options.watsonxProjectId;
this.watsonxStopToken = options.watsonxStopToken;
this.watsonxApiVersion = options.watsonxApiVersion;
this.watsonxFullUrl = options.watsonxFullUrl;
// watsonx deploymentId
this.deploymentId = options.deploymentId;
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;

View file

@ -6,6 +6,7 @@ class DeepInfra extends OpenAI {
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.deepinfra.com/v1/openai/",
};
maxStopWords: number | undefined = 16;
}
export default DeepInfra;

View file

@ -15,6 +15,7 @@ class Gemini extends BaseLLM {
static defaultOptions: Partial<LLMOptions> = {
model: "gemini-pro",
apiBase: "https://generativelanguage.googleapis.com/v1beta/",
maxStopWords: 5,
};
// Function to convert completion options to Gemini format
@ -35,7 +36,9 @@ class Gemini extends BaseLLM {
finalOptions.maxOutputTokens = options.maxTokens;
}
if (options.stop) {
finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== "");
finalOptions.stopSequences = options.stop
.filter((x) => x.trim() !== "")
.slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords);
}
return { generationConfig: finalOptions }; // Wrap options under 'generationConfig'

View file

@ -8,6 +8,59 @@ import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
interface OllamaChatMessage extends ChatMessage {
images?: string[];
}
// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter
interface ModelFileParams {
mirostat?: number;
mirostat_eta?: number;
mirostat_tau?: number;
num_ctx?: number;
repeat_last_n?: number;
repeat_penalty?: number;
temperature?: number;
seed?: number;
stop?: string | string[];
tfs_z?: number;
num_predict?: number;
top_k?: number;
top_p?: number;
min_p?: number;
// deprecated?
num_thread?: number;
num_gqa?: number;
num_gpu?: number;
}
// See https://github.com/ollama/ollama/blob/main/docs/api.md
interface BaseOptions {
model: string; // the model name
options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature
format?: "json"; // the format to return a response in. Currently, the only accepted value is json
stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects
keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m)
}
interface GenerateOptions extends BaseOptions {
prompt: string; // the prompt to generate a response for
suffix?: string; // the text after the model response
images?: string[]; // a list of base64-encoded images (for multimodal models such as llava)
system?: string; // system message to (overrides what is defined in the Modelfile)
template?: string; // the prompt template to use (overrides what is defined in the Modelfile)
context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory
raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API
}
interface ChatOptions extends BaseOptions {
messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory
// Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
// And correspondingly, tool calls in OllamaChatMessage
}
class Ollama extends BaseLLM {
static providerName: ModelProvider = "ollama";
static defaultOptions: Partial<LLMOptions> = {
@ -63,7 +116,7 @@ class Ollama extends BaseLLM {
this.completionOptions.stop.push(JSON.parse(value));
} catch (e) {
console.warn(
'Error parsing stop parameter value "{value}: ${e}',
`Error parsing stop parameter value "{value}: ${e}`,
);
}
break;
@ -128,49 +181,73 @@ class Ollama extends BaseLLM {
);
}
private _convertMessage(message: ChatMessage) {
private _getModelFileParams(options: CompletionOptions): ModelFileParams {
return {
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
num_predict: options.maxTokens,
stop: options.stop,
num_ctx: this.contextLength,
mirostat: options.mirostat,
num_thread: options.numThreads,
min_p: options.minP,
};
}
private _convertMessage(
message: ChatMessage
) {
if (typeof message.content === "string") {
return message;
}
const images: string[] = [];
message.content.forEach((part) => {
if (part.type === "imageUrl" && part.imageUrl) {
const image = part.imageUrl?.url.split(",").at(-1);
if (image) {
images.push(image);
}
}
});
return {
role: message.role,
content: stripImages(message.content),
images: message.content
.filter((part) => part.type === "imageUrl")
.map((part) => part.imageUrl?.url.split(",").at(-1)),
images
};
}
private _convertArgs(
private _getChatOptions(
options: CompletionOptions,
prompt: string | ChatMessage[],
suffix?: string,
) {
const finalOptions: any = {
messages: ChatMessage[]
): ChatOptions {
return {
model: this._getModel(),
raw: true,
messages: messages.map(this._convertMessage),
options: this._getModelFileParams(options),
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
suffix,
options: {
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
num_predict: options.maxTokens,
stop: options.stop,
num_ctx: this.contextLength,
mirostat: options.mirostat,
num_thread: options.numThreads,
},
stream: options.stream,
format: "json",
};
}
if (typeof prompt === "string") {
finalOptions.prompt = prompt;
} else {
finalOptions.messages = prompt.map(this._convertMessage);
}
return finalOptions;
private _getGenerateOptions(
options: CompletionOptions,
prompt: string,
suffix?: string
): GenerateOptions {
return {
model: this._getModel(),
prompt,
suffix,
raw: options.raw,
options: this._getModelFileParams(options),
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
stream: options.stream,
format: "json"
// Not supported yet: context, images, system, template
};
}
private getEndpoint(endpoint: string): URL {
@ -192,7 +269,7 @@ class Ollama extends BaseLLM {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._convertArgs(options, prompt)),
body: JSON.stringify(this._getGenerateOptions(options, prompt)),
});
let buffer = "";
@ -231,7 +308,7 @@ class Ollama extends BaseLLM {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._convertArgs(options, messages)),
body: JSON.stringify(this._getChatOptions(options, messages)),
});
let buffer = "";
@ -278,7 +355,7 @@ class Ollama extends BaseLLM {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._convertArgs(options, prefix, suffix)),
body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)),
});
let buffer = "";

View file

@ -7,26 +7,26 @@ import {
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
const watsonxConfig = {
accessToken: {
expiration: 0,
token: "",
},
};
let watsonxToken = {
expiration: 0,
token: ""
}
class WatsonX extends BaseLLM {
constructor(options: LLMOptions) {
super(options);
}
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (
this.watsonxFullUrl?.includes("cloud.ibm.com") ||
this.watsonxUrl?.includes("cloud.ibm.com")
this.apiBase?.includes("cloud.ibm.com")
) {
// watsonx SaaS
const wxToken = await (
await fetch(
`https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxCreds}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
`https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
{
method: "POST",
headers: {
@ -42,17 +42,17 @@ class WatsonX extends BaseLLM {
};
} else {
// watsonx Software
if (!this.watsonxCreds?.includes(":")) {
if (!this.apiKey?.includes(":")) {
// Using ZenApiKey auth
return {
token: this.watsonxCreds ?? "",
token: this.apiKey ?? "",
expiration: -1,
};
} else {
// Using username/password auth
const userPass = this.watsonxCreds?.split(":");
const userPass = this.apiKey?.split(":");
const wxToken = await (
await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, {
await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -65,7 +65,7 @@ class WatsonX extends BaseLLM {
})
).json();
const wxTokenExpiry = await (
await fetch(`${this.watsonxUrl}/usermgmt/v1/user/tokenExpiry`, {
await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
method: "GET",
headers: {
Accept: "application/json",
@ -83,8 +83,9 @@ class WatsonX extends BaseLLM {
getWatsonxEndpoint(): string {
return (
this.watsonxFullUrl ??
`${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`
this.deploymentId ?
`${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`:
`${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`
);
}
@ -132,8 +133,8 @@ class WatsonX extends BaseLLM {
protected _getHeaders() {
return {
"Content-Type": "application/json",
Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${watsonxConfig.accessToken.token}`,
Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${watsonxToken.token}`,
};
}
@ -170,24 +171,22 @@ class WatsonX extends BaseLLM {
): AsyncGenerator<ChatMessage> {
var now = new Date().getTime() / 1000;
if (
watsonxConfig.accessToken === undefined ||
now > watsonxConfig.accessToken.expiration ||
watsonxConfig.accessToken.token === undefined
watsonxToken === undefined ||
now > watsonxToken.expiration ||
watsonxToken.token === undefined
) {
watsonxConfig.accessToken = await this.getBearerToken();
watsonxToken = await this.getBearerToken();
} else {
console.log(
`Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60
`Reusing token (expires in ${(watsonxToken.expiration - now) / 60
} mins)`,
);
}
if (watsonxConfig.accessToken.token === undefined) {
if (watsonxToken.token === undefined) {
throw new Error("Something went wrong. Check your credentials, please.");
}
const stopToken =
this.watsonxStopToken ??
(options.model?.includes("granite") ? "<|im_end|>" : undefined);
const stopSequences =
options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []);
const url = this.getWatsonxEndpoint();
const headers = this._getHeaders();
@ -195,24 +194,25 @@ class WatsonX extends BaseLLM {
decoding_method: "greedy",
max_new_tokens: options.maxTokens ?? 1024,
min_new_tokens: 1,
stop_sequences: stopToken ? [stopToken] : [],
stop_sequences: stopSequences,
include_stop_sequence: false,
repetition_penalty: 1,
truncate_input_tokens: this.contextLength - (options.maxTokens ?? 1024),
repetition_penalty: options.frequencyPenalty || 1,
};
if (!!options.temperature) {
parameters.decoding_method = "sample";
parameters.temperature = options.temperature;
parameters.top_p = options.topP || 1.0;
parameters.top_k = options.topK;
parameters.top_k = options.topK || 100;
}
const payload: any = {
input: messages[messages.length - 1].content,
parameters: parameters,
};
if (!this.watsonxFullUrl) {
if (!this.deploymentId) {
payload.model_id = options.model;
payload.project_id = this.watsonxProjectId;
payload.project_id = this.projectId;
}
var response = await this.fetch(url, {
@ -245,7 +245,8 @@ class WatsonX extends BaseLLM {
generatedChunk += result.generated_text || "";
});
} catch (e) {
console.error(`Error parsing JSON string: ${dataStr}`, e);
// parsing error is expected with streaming response
// console.error(`Error parsing JSON string: ${dataStr}`, e);
}
}
});

View file

@ -274,12 +274,22 @@ const gemmaTemplateMessage = templateFactory(
"<end_of_turn>\n",
);
const graniteTemplateMessages = templateFactory(
(msg) => (!!msg ? `\n\nSystem:\n ${msg.content}\n\n` : ""),
"Question:\n",
"Answer:\n",
"\n\n",
"",
"",
);
export {
anthropicTemplateMessages,
chatmlTemplateMessages,
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
gemmaTemplateMessage,
graniteTemplateMessages,
llama2TemplateMessages,
llama3TemplateMessages,
llavaTemplateMessages,

View file

@ -10,35 +10,35 @@ Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or
To get started with watsonx SaaS, visit the [registration page](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx). If you do not have an existing IBM Cloud account, you can sign up for a free trial.
To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [setup an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue:
To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [set up an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue:
- Set **watsonx URL** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region.
- Set **watsonx Project ID** to your watsonx project ID.
- Set **watsonx API Key** to your watsonx API Key.
- Set **apiBase** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region.
- Set **projectId** to your watsonx project ID.
- Set **apiKey** to your watsonx API Key.
### watsonx.ai Software
To authenticate to your watsonx.ai Software instance with Continue, you can use either `username/password` or `ZenApiKey` method:
1. _Option 1_ (Recommended): using `ZenApiKey` authentication:
- Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`.
- Set **watsonx Project ID** to your watsonx project ID.
- Set **watsonx API Key** to your watsonx Zen API Key. To generate it:
1. Log in to the CPD web client.
2. From the toolbar, click your avatar.
3. Click **Profile and settings**.
4. Click **API key** > **Generate new key**.
5. Click **Generate**.
6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it.
7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo "<username>:<apikey>" | base64`, replacing `<username>` with your CPD username and `<apikey>` with the API Key you just created.
- Set **apiBase** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`.
- Set **projectId** to your watsonx project ID.
- Set **apiKey** to your watsonx Zen API Key. To generate it:
1. Log in to the CPD web client.
2. From the toolbar, click your avatar.
3. Click **Profile and settings**.
4. Click **API key** > **Generate new key**.
5. Click **Generate**.
6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it.
7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo "<username>:<apikey>" | base64`, replacing `<username>` with your CPD username and `<apikey>` with the API Key you just created.
2. _Option 2_: using `username/password` authentication:
- Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`.
- Set **watsonx Project ID** to your watsonx project ID.
- Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format.
- Set **apiBase** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`.
- Set **projectId** to your watsonx project ID.
- Set **API Key** to your watsonx Username and Password using `username:password` as format.
## Configuration
Add the following configuration to your `config.json` file to use the watsonx provider. Fill in the `watsonxCreds` with the authentication details you obtained in the setup step.
Add the following configuration to your `config.json` file to use the watsonx provider.
```json title="~/.continue/config.json"
{
@ -46,39 +46,101 @@ Add the following configuration to your `config.json` file to use the watsonx pr
{
"model": "model ID",
"title": "watsonx - Model Name",
"watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"watsonxProjectId": "PROJECT_ID",
"watsonxCreds": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD",
"watsonxApiVersion": "2023-05-29",
"provider": "watsonx"
"provider": "watsonx",
"apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"projectId": "PROJECT_ID",
"apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD",
"apiVersion": "2024-03-14"
}
]
}
```
`watsonxAPIVersion` is optional and defaults to the latest version.
`apiVersion` is optional and defaults to the latest version.
If you are using a custom deployment endpoint, set `deploymentID` to the model's deployment ID. You can find it in the watsonx.ai Prompt Lab UI by selecting the corresponding model and opening the `</>` tab on the right, which will display the endpoint's URL containing the deployment ID.
```json title="~/.continue/config.json"
{
"models": [
{
"model": "model ID",
"title": "watsonx - Model Name",
"provider": "watsonx",
"apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD",
"apiVersion": "2024-03-14",
"deploymentId": "DEPLOYMENT_ID"
}
]
}
```
### Configuration Options
Add the full watsonx URL to `watsonxFullUrl` if you are using a custom endpoint. When `watsonxFullUrl` is set, `watsonxUrl` and `watsonxApiVersion` are ignored.
Make sure to specify a template name, such as `granite` or `llama3`, and to set the `contextLength` to the model's context window size.
You can also configure generation parameters, such as temperature, topP, topK, frequency penalty, and stop sequences:
```json title="~/.continue/config.json"
{
"models": [
{
"model": "model ID",
"title": "watsonx - Model Name",
"watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"watsonxProjectId": "PROJECT_ID",
"watsonxCreds": "API_KEY",
"watsonxApiVersion": "2023-05-29",
"model": "ibm/granite-20b-code-instruct",
"title": "Granite Code 20b",
"provider": "watsonx",
"watsonxFullUrl": "https://us-south.ml.cloud.ibm.com/m1/v1/text/generation"
"apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"projectId": "PROJECT_ID",
"apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD",
"apiVersion": "2024-03-14",
"template": "granite",
"contextLength": 8000,
"completionOptions": {
"temperature": 0.1,
"topP": 0.3,
"topK": 20,
"maxTokens": 2000,
"frequencyPenalty": 1.1,
"stop": [
"Question:",
"\n\n\n"
]
}
}
]
}
```
## Usage
## Tab Auto Complete Model
![usage-gif](../assets/watsonx2.gif)
Granite models are recommended for tab auto complete. The configuration is similar to that of the chat models:
```json title="~/.continue/config.json"
{
"tabAutocompleteModel": {
"model": "ibm/granite-8b-code-instruct",
"title": "Granite Code 8b",
"provider": "watsonx",
"apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"projectId": "PROJECT_ID",
"apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD",
"apiVersion": "2024-03-14",
"contextLength": 4000
}
}
```
## Embeddings Model
To view the list of available embeddings models, visit [this page](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models-embed.html?context=wx&pos=2#ibm-provided).
```json title="~/.continue/config.json
{
"embeddingsProvider": {
"provider": "watsonx",
"model": "ibm/slate-30m-english-rtrvr-v2",
"apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"projectId": "PROJECT_ID",
"apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD",
"apiVersion": "2024-03-14"
}
}
```

View file

@ -1547,38 +1547,35 @@
},
"then": {
"properties": {
"watsonxUrl": {
"apiBase": {
"type": "string"
},
"watsonxApiKey": {
"apiKey": {
"type": "string"
},
"watsonxApiVersion": {
"apiVersion": {
"type": "string"
},
"watsonxProjectId": {
"projectId": {
"type": "string"
},
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"deploymentId": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
"ibm/granite-3b-code-instruct",
"ibm/granite-8b-code-instruct",
"ibm/granite-20b-code-instruct",
"ibm/granite-34b-code-instruct",
"mistralai/mistral-large",
"meta-llama/llama-3-8b-instruct",
"meta-llama/llama-3-70b-instruct"
]
}
},
"required": [
"watsonxUrl",
"watsonxProjectId"
]
"required": ["apiBase", "apiKey", "apiVersion"]
}
},
{

View file

@ -25,7 +25,7 @@ repositories { mavenCentral() }
// https://docs.gradle.org/current/userguide/platforms.html#sub:version-catalog
dependencies {
// implementation(libs.annotations)
implementation("com.squareup.okhttp3:okhttp:4.9.1") {
implementation("com.squareup.okhttp3:okhttp:4.9.2") {
exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib")
}
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32")

View file

@ -451,22 +451,26 @@ class IdeProtocolClient(
}
"getDiff" -> {
val builder = ProcessBuilder("git", "diff")
builder.directory(File(workspacePath ?: "."))
val process = builder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
val workspaceDirs = workspaceDirectories()
val output = StringBuilder()
var line: String? = reader.readLine()
while (line != null) {
output.append(line)
output.append("\n")
line = reader.readLine()
for (workspaceDir in workspaceDirs) {
val builder = ProcessBuilder("git", "diff")
builder.directory(File(workspaceDir))
val process = builder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
var line: String? = reader.readLine()
while (line != null) {
output.append(line)
output.append("\n")
line = reader.readLine()
}
process.waitFor()
}
process.waitFor()
respond(output.toString());
respond(output.toString())
}
"getProblems" -> {

View file

@ -1547,38 +1547,35 @@
},
"then": {
"properties": {
"watsonxUrl": {
"apiBase": {
"type": "string"
},
"watsonxApiKey": {
"apiKey": {
"type": "string"
},
"watsonxApiVersion": {
"apiVersion": {
"type": "string"
},
"watsonxProjectId": {
"projectId": {
"type": "string"
},
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"deploymentId": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
"ibm/granite-3b-code-instruct",
"ibm/granite-8b-code-instruct",
"ibm/granite-20b-code-instruct",
"ibm/granite-34b-code-instruct",
"mistralai/mistral-large",
"meta-llama/llama-3-8b-instruct",
"meta-llama/llama-3-70b-instruct"
]
}
},
"required": [
"watsonxUrl",
"watsonxProjectId"
]
"required": ["apiBase", "apiKey", "apiVersion"]
}
},
{

View file

@ -1547,38 +1547,35 @@
},
"then": {
"properties": {
"watsonxUrl": {
"apiBase": {
"type": "string"
},
"watsonxApiKey": {
"apiKey": {
"type": "string"
},
"watsonxApiVersion": {
"apiVersion": {
"type": "string"
},
"watsonxProjectId": {
"projectId": {
"type": "string"
},
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"deploymentId": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
"ibm/granite-3b-code-instruct",
"ibm/granite-8b-code-instruct",
"ibm/granite-20b-code-instruct",
"ibm/granite-34b-code-instruct",
"mistralai/mistral-large",
"meta-llama/llama-3-8b-instruct",
"meta-llama/llama-3-70b-instruct"
]
}
},
"required": [
"watsonxUrl",
"watsonxProjectId"
]
"required": ["apiBase", "apiKey", "apiVersion"]
}
},
{

View file

@ -1550,28 +1550,28 @@
},
"then": {
"properties": {
"watsonxUrl": {
"apiBase": {
"type": "string"
},
"watsonxApiKey": {
"apiKey": {
"type": "string"
},
"watsonxApiVersion": {
"apiVersion": {
"type": "string"
},
"watsonxProjectId": {
"projectId": {
"type": "string"
},
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"deploymentId": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
"ibm/granite-3b-code-instruct",
"ibm/granite-8b-code-instruct",
"ibm/granite-20b-code-instruct",
"ibm/granite-34b-code-instruct",
"mistralai/mistral-large",
"meta-llama/llama-3-8b-instruct",
"meta-llama/llama-3-70b-instruct"
@ -1579,8 +1579,9 @@
}
},
"required": [
"watsonxUrl",
"watsonxProjectId"
"apiBase",
"apiKey",
"apiVersion"
]
}
},

View file

@ -58,6 +58,7 @@ export class ContinueGUIWebviewViewProvider
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
): void | Thenable<void> {
this._webviewView = webviewView;
this._webview = webviewView.webview;
this._webview.onDidReceiveMessage((message) =>
this.handleWebviewMessage(message),

View file

@ -11,6 +11,8 @@ import { RootState } from "../redux/store";
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
import { useLastSessionContext } from "../context/LastSessionContext";
const MAX_TITLE_LENGTH = 100;
function truncateText(text: string, maxLength: number) {
if (text.length > maxLength) {
return text.slice(0, maxLength - 3) + "...";
@ -84,7 +86,7 @@ function useHistory(dispatch: Dispatch) {
.split("\n")
.filter((l) => l.trim() !== "")
.slice(-1)[0] || "",
50,
MAX_TITLE_LENGTH,
)
: stateCopy.title?.length > 0
? stateCopy.title

View file

@ -74,7 +74,8 @@ export const models: { [key: string]: ModelPackage } = {
},
llama32Chat: {
title: "Llama3.2 Chat",
description: "The latest model from Meta, fine-tuned for chat. Llama3.1 recommended - chat stayed the same",
description:
"The latest model from Meta, fine-tuned for chat. Llama3.1 recommended - chat stayed the same",
refUrl: "",
params: {
title: "Llama3.2-11b",
@ -106,11 +107,7 @@ export const models: { [key: string]: ModelPackage } = {
},
},
],
providerOptions: [
"ollama",
"groq",
"llama.cpp",
],
providerOptions: ["ollama", "groq", "llama.cpp"],
isOpenSource: true,
},
deepseek: {
@ -358,7 +355,8 @@ export const models: { [key: string]: ModelPackage } = {
},
llama321bChat: {
title: "Llama3.2 1b Chat",
description: "The latest super-lightweight model from Meta, fine-tuned for chat",
description:
"The latest super-lightweight model from Meta, fine-tuned for chat",
refUrl: "",
params: {
title: "Llama3.2-1b",
@ -804,50 +802,89 @@ export const models: { [key: string]: ModelPackage } = {
isOpenSource: false,
},
graniteChat: {
title: "watsonx - Granite Chat",
title: "Granite Chat 13b",
description:
"The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
model: "ibm/granite-13b-chat-v2",
contextLength: 20_000,
title: "Granite Chat",
contextLength: 8_000,
title: "Granite Chat 13b",
},
providerOptions: ["watsonx"],
icon: "",
icon: "WatsonX.png",
isOpenSource: false,
},
graniteCode: {
title: "watsonx - Granite Code 20b",
graniteCode3b: {
title: "Granite Code 3b",
description:
"The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
model: "ibm/granite-3b-code-instruct",
contextLength: 2_000,
title: "Granite Code 3b",
},
providerOptions: ["watsonx"],
icon: "WatsonX.png",
isOpenSource: false,
},
graniteCode8b: {
title: "Granite Code 8b",
description:
"The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
model: "ibm/granite-8b-code-instruct",
contextLength: 4_000,
title: "Granite Code 8b",
},
providerOptions: ["watsonx"],
icon: "WatsonX.png",
isOpenSource: false,
},
graniteCode20b: {
title: "Granite Code 20b",
description:
"The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
model: "ibm/granite-20b-code-instruct",
contextLength: 20_000,
title: "watsonx - Granite Code 20b",
contextLength: 8_000,
title: "Granite Code 20b",
},
providerOptions: ["watsonx"],
icon: "watsonx.png",
icon: "WatsonX.png",
isOpenSource: false,
},
graniteCode34b: {
title: "Granite Code 34b",
description:
"The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
model: "ibm/granite-34b-code-instruct",
contextLength: 8_000,
title: "Granite Code 34b",
},
providerOptions: ["watsonx"],
icon: "WatsonX.png",
isOpenSource: false,
},
MistralLarge: {
title: "watsonx - Mistral Large",
title: "Mistral Large",
description:
"Mistral Large, the most advanced Large Language Model (LLM) developed by Mistral Al, is an exceptionally powerful model.",
params: {
model: "mistralai/mistral-large",
contextLength: 20_000,
title: "watsonx - Mistral Large",
title: "Mistral Large",
},
providerOptions: ["watsonx"],
icon: "mistral.png",
isOpenSource: false,
},
MetaLlama3: {
title: "watsonx - Llama 3.1",
title: "Llama 3.1",
description:
"Llama 3 is an auto-regressive language model that uses an optimized transformer architecture.",
params: {
title: "watsonx - Llama 3.1 8b",
title: "Llama 3.1",
model: "meta-llama/llama-3-1-8b-instruct",
contextLength: 20_000,
},
@ -859,11 +896,11 @@ export const models: { [key: string]: ModelPackage } = {
options: {
"8b": {
model: "meta-llama/llama-3-1-8b-instruct",
title: "watsonx - Llama 3.1 8b",
title: "Llama 3.1 8b",
},
"70b": {
model: "meta-llama/llama-3-1-70b-instruct",
title: "watsonx - Llama 3.1 70b",
title: "Llama 3.1 70b",
},
},
},

View file

@ -487,54 +487,51 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
collectInputFor: [
{
inputType: "text",
key: "watsonxUrl",
key: "apiBase",
label: "watsonx URL",
placeholder: "e.g. http://us-south.dataplatform.cloud.ibm.com",
required: true,
},
{
inputType: "text",
key: "watsonxProjectId",
label: "watsonx Project ID",
key: "projectId",
label: "Project ID",
placeholder: "Enter your project ID",
required: true,
},
{
inputType: "text",
key: "watsonxCreds",
label: "watsonx API key",
key: "apiKey",
label: "API key",
placeholder: "Enter your API key (SaaS) or ZenApiKey (Software)",
required: true,
},
{
inputType: "text",
key: "watsonxApiVersion",
label: "watsonx API version",
key: "apiVersion",
label: "API version",
placeholder: "Enter the API Version",
defaultValue: "2023-05-29",
required: true
defaultValue: "2024-03-14",
required: true,
},
{
inputType: "text",
key: "watsonxFullUrl",
label: "Full watsonx URL",
placeholder:
"http://us-south.dataplatform.cloud.ibm.com/m1/v1/text/generation_stream?version=2023-05-29",
key: "deploymentId",
label: "Deployment ID",
placeholder: "Enter model deployment ID",
required: false,
},
{
inputType: "text",
key: "watsonxStopToken",
label: "Stop Token",
placeholder: "<|im_end|>",
},
...completionParamsInputsConfigs,
],
icon: "watsonx.png",
apiKeyUrl:
"https://dataplatform.cloud.ibm.com/registration/stepone?context=wx",
icon: "WatsonX.png",
tags: [ModelProviderTags.RequiresApiKey],
packages: [
models.graniteCode,
models.graniteCode3b,
models.graniteCode8b,
models.graniteCode20b,
models.graniteCode34b,
models.graniteChat,
models.MistralLarge,
models.MetaLlama3,
@ -601,8 +598,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
icon: "cerebras.png",
description:
"Cerebras Inference is a custom silicon for fast inference of LLM models.",
longDescription:
"Get your API key [here](https://cloud.cerebras.ai/).",
longDescription: "Get your API key [here](https://cloud.cerebras.ai/).",
tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource],
collectInputFor: [
{