Use some base class functions

This commit is contained in:
Luke 2024-10-26 23:21:30 -04:00
parent 9be15f7e8a
commit 4004e2e301
6 changed files with 47 additions and 167 deletions

View file

@ -20,7 +20,7 @@ class Anthropic extends BaseLLM {
apiBase: "https://api.anthropic.com/v1/",
};
private _convertArgs(options: CompletionOptions) {
public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI
const finalOptions = {
top_k: options.topK,
top_p: options.topP,
@ -34,7 +34,7 @@ class Anthropic extends BaseLLM {
return finalOptions;
}
private _convertMessages(msgs: ChatMessage[]): any[] {
public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI
const filteredmessages = msgs.filter((m) => m.role !== "system")
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
@ -115,8 +115,8 @@ class Anthropic extends BaseLLM {
: {}),
},
body: JSON.stringify({
...this._convertArgs(options),
messages: this._convertMessages(messages),
...this.convertArgs(options),
messages: this.convertMessages(messages),
system: shouldCacheSystemMessage
? [
{

View file

@ -18,7 +18,7 @@ class Gemini extends BaseLLM {
};
// Function to convert completion options to Gemini format
private _convertArgs(options: CompletionOptions) {
public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI
const finalOptions: any = {}; // Initialize an empty object
// Map known options
@ -53,7 +53,7 @@ class Gemini extends BaseLLM {
}
}
private removeSystemMessage(messages: ChatMessage[]) {
public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI
const msgs = [...messages];
if (msgs[0]?.role === "system") {
@ -100,7 +100,7 @@ class Gemini extends BaseLLM {
}
}
private _continuePartToGeminiPart(part: MessagePart) {
continuePartToGeminiPart(part: MessagePart) {
return part.type === "text"
? {
text: part.text,
@ -139,13 +139,13 @@ class Gemini extends BaseLLM {
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this._continuePartToGeminiPart),
: msg.content.map(this.continuePartToGeminiPart),
};
})
.filter((c) => c !== null);
const body = {
...this._convertArgs(options),
...this.convertArgs(options),
contents,
// if this.systemMessage is defined, reformat it for Gemini API
...(this.systemMessage &&

View file

@ -10,11 +10,15 @@ import {
ModelProvider,
} from "../../index.js";
import { streamResponse } from "../stream.js";
import Anthropic from "./Anthropic.js";
import Gemini from "./Gemini.js";
class VertexAI extends BaseLLM {
static providerName: ModelProvider = "vertexai";
declare apiBase: string;
declare vertexProvider: string;
declare anthropicInstance: Anthropic;
declare geminiInstance: Gemini;
private clientPromise = new GoogleAuth({
scopes: "https://www.googleapis.com/auth/cloud-platform",
@ -35,12 +39,15 @@ class VertexAI extends BaseLLM {
this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
this.vertexProvider =
_options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral")
? "Mistral"
? "mistral"
: _options.model.includes("claude")
? "anthropic"
: _options.model.includes("gemini")
? "gemini" :
"unknown";
this.anthropicInstance = new Anthropic(_options);
this.geminiInstance = new Gemini(_options)
}
async fetch(url: RequestInfo | URL, init?: RequestInit) {
@ -63,68 +70,16 @@ class VertexAI extends BaseLLM {
// Anthropic functions
private _anthropicConvertArgs(options: CompletionOptions) {
const finalOptions = {
const convertedArgs = this.anthropicInstance.convertArgs(options);
// Remove the `model` property and add `anthropic_version`
const { model, ...finalOptions } = convertedArgs;
return {
...finalOptions,
anthropic_version: "vertex-2023-10-16",
top_k: options.topK,
top_p: options.topP,
temperature: options.temperature,
max_tokens: options.maxTokens ?? 2048,
stop_sequences: options.stop?.filter((x) => x.trim() !== ""),
stream: options.stream ?? true,
};
return finalOptions;
}
private _anthropicConvertMessages(msgs: ChatMessage[]): any[] {
const filteredmessages = msgs.filter((m) => m.role !== "system")
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1).slice(-2);
const messages = filteredmessages.map((message, filteredMsgIdx) => {
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx);
if (typeof message.content === "string") {
var chatMessage = {
...message,
content: [{
type: "text",
text: message.content,
...(addCaching ? { cache_control: { type: "ephemeral" } } : {})
}]
};
return chatMessage;
}
return {
...message,
content: message.content.map((part, contentIdx) => {
if (part.type === "text") {
const newpart = {
...part,
// If multiple text parts, only add cache_control to the last one
...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {})
};
return newpart;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}),
};
});
return messages;
}
protected async *StreamChatAnthropic(
messages: ChatMessage[],
@ -148,7 +103,7 @@ class VertexAI extends BaseLLM {
},
body: JSON.stringify({
...this._anthropicConvertArgs(options),
messages: this._anthropicConvertMessages(messages),
messages: this.anthropicInstance.convertMessages(messages),
system: shouldCacheSystemMessage
? [
{
@ -177,58 +132,6 @@ class VertexAI extends BaseLLM {
//Gemini
// Function to convert completion options to Gemini format
private _geminiConvertArgs(options: CompletionOptions) {
const finalOptions: any = {}; // Initialize an empty object
// Map known options
if (options.topK) {
finalOptions.topK = options.topK;
}
if (options.topP) {
finalOptions.topP = options.topP;
}
if (options.temperature !== undefined && options.temperature !== null) {
finalOptions.temperature = options.temperature;
}
if (options.maxTokens) {
finalOptions.maxOutputTokens = options.maxTokens;
}
if (options.stop) {
finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== "");
}
return { generationConfig: finalOptions }; // Wrap options under 'generationConfig'
}
private removeSystemMessage(messages: ChatMessage[]) {
const msgs = [...messages];
if (msgs[0]?.role === "system") {
const sysMsg = msgs.shift()?.content;
// @ts-ignore
if (msgs[0]?.role === "user") {
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
}
}
return msgs;
}
private _continuePartToGeminiPart(part: MessagePart) {
return part.type === "text"
? {
text: part.text,
}
: {
inlineData: {
mimeType: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
private async *streamChatGemini(
messages: ChatMessage[],
@ -252,13 +155,13 @@ class VertexAI extends BaseLLM {
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this._continuePartToGeminiPart),
: msg.content.map(this.geminiInstance.continuePartToGeminiPart),
};
})
.filter((c) => c !== null);
const body = {
...this._geminiConvertArgs(options),
...this.geminiInstance.convertArgs(options),
contents,
// if this.systemMessage is defined, reformat it for Gemini API
...(this.systemMessage &&
@ -392,7 +295,10 @@ class VertexAI extends BaseLLM {
});
for await (const chunk of streamSse(response)) {
yield chunk.choices[0].delta;
if (chunk.choices?.[0]) {
// At the end vertexai will return a empty chunk.
yield chunk.choices[0].delta;
}
}
}
@ -471,7 +377,7 @@ class VertexAI extends BaseLLM {
// Conditionally apply removeSystemMessage
const convertedMsgs = isV1API
? this.removeSystemMessage(messages)
? this.geminiInstance.removeSystemMessage(messages)
: messages;
if (this.vertexProvider == "gemini") {
yield* this.streamChatGemini(convertedMsgs, options);

View file

@ -11,35 +11,7 @@ You need to enable the [Vertex AI API](https://console.cloud.google.com/marketpl
## Chat model
We recommend configuring **Mistral Large**, **Gemini 1.5 Pro**, or **Claude 3.5 Sonnet** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Mistral Large (Vertex AI)",
"provider": "vertexai",
"model": "mistral-large",
"projectId": "[PROJECT_ID]",
"region": "us-central1"
}
]
}
```
```json title="config.json"
{
"models": [
{
"title": "Gemini 1.5 Pro (Vertex AI)",
"provider": "vertexai",
"model": "gemini-1.5-pro",
"projectId": "[PROJECT_ID]",
"region": "us-central1"
}
]
}
```
We recommend configuring **Claude 3.5 Sonnet** as your chat model.
```json title="config.json"
{
@ -71,19 +43,6 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo
}
}
```
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Code Gecko (Vertex AI)",
"provider": "vertexai",
"model": "codestral",
"projectId": "[PROJECT_ID]",
"region": "us-central1"
}
}
```
## Embeddings model
We recommend configuring **text-embedding-004** as your embeddings model.

View file

@ -816,6 +816,20 @@ export const models: { [key: string]: ModelPackage } = {
providerOptions: ["vertexai"],
isOpenSource: false,
},
vertexMistralLarge: {
title: "Mistral Large",
description:
"Mistral's flagship model that's ideal for complex tasks that require large reasoning capabilities or are highly specialized (Synthetic Text Generation, Code Generation, RAG, or Agents).",
params: {
title: "Mistral Large",
model: "mistral-large",
contextLength: 32000,
},
icon: "mistral.png",
providerOptions: ["vertexai"],
isOpenSource: false,
},
AUTODETECT: {

View file

@ -636,6 +636,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
packages: [
models.VertexGemini15Pro,
models.VertexGemini15Flash,
models.mistralLarge
],
collectInputFor: [