Bedrock chat completion, Anthropic models

This commit is contained in:
EC2 Default User 2024-03-24 08:49:57 +00:00
parent adcd079271
commit 7a2ed535fc
12 changed files with 397 additions and 22 deletions

View file

@ -422,6 +422,7 @@ declare global {
| "phi2"
| "phind"
| "anthropic"
| "bedrock"
| "chatml"
| "none"
| "openchat"
@ -482,6 +483,10 @@ declare global {
| "neural-chat-7b"
// Anthropic
| "claude-2"
// Bedrock Anthropic
| "anthropic.claude-3-sonnet-20240229-v1:0"
| "anthropic.claude-3-haiku-20240307-v1:0"
| "anthropic.claude-v2:1"
// Google PaLM
| "chat-bison-001"
// Gemini

5
core/index.d.ts vendored
View file

@ -451,6 +451,7 @@ type TemplateType =
| "phi2"
| "phind"
| "anthropic"
| "bedrock"
| "chatml"
| "none"
| "openchat"
@ -516,6 +517,10 @@ export type ModelName =
| "claude-3-sonnet-20240229"
| "claude-3-haiku-20240307"
| "claude-2.1"
// Bedrock Anthropic
| "anthropic.claude-3-sonnet-20240229-v1:0"
| "anthropic.claude-3-haiku-20240307-v1:0"
| "anthropic.claude-v2:1"
// Google PaLM
| "chat-bison-001"
// Gemini

View file

@ -38,6 +38,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"ollama",
"together",
"anthropic",
"bedrock",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
@ -46,6 +47,7 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
"google-palm",
"free-trial",
"anthropic",
"bedrock",
];
function modelSupportsImages(provider: ModelProvider, model: string): boolean {
@ -201,6 +203,7 @@ function autodetectTemplateFunction(
phind: phindTemplateMessages,
zephyr: zephyrTemplateMessages,
anthropic: anthropicTemplateMessages,
bedrock: anthropicTemplateMessages,
chatml: chatmlTemplateMessages,
deepseek: deepseekTemplateMessages,
openchat: openchatTemplateMessages,
@ -253,6 +256,8 @@ function autodetectPromptTemplates(
editTemplate = codeLlama70bEditPrompt;
} else if (templateType === "anthropic") {
editTemplate = claudeEditPrompt;
} else if (templateType === "bedrock") {
editTemplate = claudeEditPrompt;
} else if (templateType === "gemma") {
editTemplate = gemmaEditPrompt;
} else if (templateType) {

View file

@ -1,35 +1,189 @@
import { BaseLLM } from "..";
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
import { streamSse } from "../stream";
import { ChatMessage, CompletionOptions, LLMOptions, ModelProvider } from "../..";
import * as fs from "fs";
import { join as joinPath } from "path";
import { promisify } from "util";
import { stripImages } from "../countTokens";
const aws4 = require("aws4");
const readFile = promisify(fs.readFile);
namespace BedrockCommon {
export enum Method {
Chat = "invoke",
Completion = "invoke-with-response-stream",
}
export const Service: string = "bedrock";
export const AuthAlgo: string = "AWS4-HMAC-SHA256";
export const HashAlgo: string = "sha256";
}
class Bedrock extends BaseLLM {
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {};
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
completionOptions: {
model: "anthropic.claude-3-sonnet-20240229-v1:0",
maxTokens: 4096,
temperature: 1,
topP: 0.9,
topK: 250,
stop: [],
},
};
constructor(options: LLMOptions) {
super(options);
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
top_k: options.topK,
top_p: options.topP,
temperature: options.temperature,
max_tokens: options.maxTokens ?? 2048,
stop_sequences: options.stop,
};
return finalOptions;
}
private _convertMessages(msgs: ChatMessage[]): any[] {
const messages = msgs
.filter((m) => m.role !== "system")
.map((message) => {
if (typeof message.content === "string") {
return message;
} else {
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
} else {
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
}),
};
}
});
return messages;
}
private _parseCredentialsFile(fileContents: string) {
const profiles: { [key: string]: any } = {};
const lines = fileContents.trim().split('\n');
let currentProfile: string | null = null;
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('[') && trimmedLine.endsWith(']')) {
currentProfile = trimmedLine.slice(1, -1);
profiles[currentProfile] = {};
} else if (currentProfile !== null && trimmedLine.includes('=')) {
const [key, value] = trimmedLine.split('=');
const trimmedKey = key.trim();
const trimmedValue = value.trim();
if (trimmedKey === 'aws_access_key_id') {
profiles[currentProfile].accessKeyId = trimmedValue;
} else if (trimmedKey === 'aws_secret_access_key') {
profiles[currentProfile].secretAccessKey = trimmedValue;
} else if (trimmedKey === 'aws_session_token') {
profiles[currentProfile].sessionToken = trimmedValue;
}
}
}
return profiles;
}
private async _fetchWithAwsAuthSigV4(apiMethod: BedrockCommon.Method, body: string): Promise<Response> {
let model = this.completionOptions.model;
if (apiMethod == BedrockCommon.Method.Completion && model.includes("claude-3")) {
model = "anthropic.claude-v2:1";
}
const path = `/model/${model}/${apiMethod}`
const opts = {
headers: {
"accept": apiMethod === BedrockCommon.Method.Chat ? "application/json" : "application/vnd.amazon.eventstream",
"content-type": "application/json",
"x-amzn-bedrock-accept": "*/*",
},
path: path,
body: body,
service: "bedrock",
host: this.apiBase!.replace("https://", ""),
region: this.region,
};
let accessKeyId: string, secretAccessKey: string, sessionToken: string;
try {
const data = await readFile(joinPath(process.env.HOME!, ".aws", "credentials"), "utf8");
const credentials = this._parseCredentialsFile(data);
accessKeyId = credentials.bedrock.accessKeyId;
secretAccessKey = credentials.bedrock.secretAccessKey;
sessionToken = credentials.bedrock.sessionToken || "";
} catch (err) {
console.error("Error reading AWS credentials", err);
return new Response("403");
}
return await this.fetch(new URL(`${this.apiBase}${path}`), {
method: "POST",
headers: aws4.sign(opts, {accessKeyId, secretAccessKey, sessionToken})["headers"],
body: body,
});
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(
`${this.apiBase}/model/${options.model}/invoke-with-response-stream`,
{
method: "POST",
headers: {
accept: "application/vnd.amazon.eventstream",
"content-type": "application/json",
"x-amzn-bedrock-accept": "*/*",
},
body: JSON.stringify({
inputText: prompt,
}),
},
);
for await (const value of streamSse(response)) {
if (value.chunk) {
yield value.chunk;
}
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
// TODO: Couldn't seem to get this stream API working yet. Deferring to _streamChat.
// import { streamSse } from "../stream";
// const response = await this._fetchWithAwsAuthSigV4(BedrockCommon.Method.Completion, JSON.stringify({
// ...this._convertArgs(options),
// max_tokens: undefined, // Delete this key in favor of the correct one for the Completions API.
// max_tokens_to_sample: options.maxTokens,
// prompt: `\n\nHuman: ${prompt}\n\nAssistant:`,
// })
// );
// for await (const value of streamSse(response)) {
// if (value.completion) {
// yield value.completion
// }
// }
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const response = await this._fetchWithAwsAuthSigV4(BedrockCommon.Method.Chat, JSON.stringify({
...this._convertArgs(options),
messages: this._convertMessages(messages),
anthropic_version: "bedrock-2023-05-31", // Fixed, required parameter for Chat API.
})
);
yield { role: "assistant", content: (await response.json()).content[0].text }
}
}

View file

@ -0,0 +1,26 @@
# AWS Bedrock
To setup Bedrock, add the following to your `config.json` file:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "Bedrock: Claude 3 Sonnet",
"provider": "bedrock",
"model": "anthropic.claude-3-sonnet-20240229-v1:0",
"region": "us-east-1"
}
]
}
```
Authentication will be through temporary or long-term credentials in
~/.aws/credentials under a profile called "bedrock".
```title="~/.aws/credentials
[bedrock]
aws_access_key_id = abcdefg
aws_secret_access_key = hijklmno
aws_session_token = pqrstuvwxyz # Optional: means short term creds.
```

View file

@ -128,6 +128,7 @@
"openai",
"free-trial",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",
@ -145,6 +146,7 @@
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)",
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
@ -529,6 +531,34 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["bedrock"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"anthropic.claude-3-sonnet-20240229-v1:0",
"anthropic.claude-3-haiku-20240307-v1:0",
"anthropic.claude-v2:1"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {

View file

@ -128,6 +128,7 @@
"openai",
"free-trial",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",
@ -145,6 +146,7 @@
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)",
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
@ -529,6 +531,34 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["bedrock"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"anthropic.claude-3-sonnet-20240229-v1:0",
"anthropic.claude-3-haiku-20240307-v1:0",
"anthropic.claude-v2:1"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {

View file

@ -128,6 +128,7 @@
"openai",
"free-trial",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",
@ -145,6 +146,7 @@
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)",
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
@ -529,6 +531,34 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["bedrock"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"anthropic.claude-3-sonnet-20240229-v1:0",
"anthropic.claude-3-haiku-20240307-v1:0",
"anthropic.claude-v2:1"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {

View file

@ -128,6 +128,7 @@
"openai",
"free-trial",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",
@ -145,6 +146,7 @@
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)",
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
@ -573,6 +575,38 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"bedrock"
]
}
},
"required": [
"provider"
]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"anthropic.claude-3-sonnet-20240229-v1:0",
"anthropic.claude-3-haiku-20240307-v1:0",
"anthropic.claude-v2:1"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {

View file

@ -594,6 +594,49 @@ const claude3Haiku: ModelPackage = {
icon: "anthropic.png",
};
const bedrockClaude3Sonnet: ModelPackage = {
title: "Bedrock: Claude 3 Sonnet",
description:
"The second most capable model in the Claude 3 series: ideal balance of intelligence and speed",
params: {
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
title: "Claude 3 Sonnet",
apiKey: "",
},
providerOptions: ["bedrock"],
icon: "anthropic.png",
};
const bedrockClaude3Haiku: ModelPackage = {
title: "Bedrock: Claude 3 Haiku",
description:
"The third most capable model in the Claude 3 series: fastest and most compact model for near-instant responsiveness",
params: {
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
title: "Claude 3 Sonnet",
apiKey: "",
},
providerOptions: ["bedrock"],
icon: "anthropic.png",
};
const bedrockClaude2v1: ModelPackage = {
title: "Bedrock: Claude 2.1",
description:
"Claude 2.1 is a large language model (LLM) by Anthropic with a 200K token context window, reduced hallucination rates, and improved accuracy over long documents.",
params: {
model: "anthropic.claude-v2:1",
contextLength: 200_000,
title: "Claude 2.1",
apiKey: "",
},
providerOptions: ["bedrock"],
icon: "anthropic.png",
}
const chatBison: ModelPackage = {
title: "chat-bison-001",
description:
@ -627,6 +670,9 @@ export const MODEL_INFO: ModelPackage[] = [
claude3Sonnet,
claude3Haiku,
claude2,
bedrockClaude3Sonnet,
bedrockClaude3Haiku,
bedrockClaude2v1,
deepseek,
mistral,
codellama70bTrial,
@ -696,6 +742,14 @@ export const PROVIDER_INFO: { [key: string]: ModelInfo } = {
],
packages: [claude3Opus, claude3Sonnet, claude3Haiku, claude2],
},
bedrock: {
title: "Bedrock",
provider: "bedrock",
refPage: "amazon.com",
description: "Bedrock is Amazon's provider of multiple diverse language models.",
tags: [ModelProviderTag["Requires API Key"]],
packages: [bedrockClaude3Sonnet],
},
ollama: {
title: "Ollama",
provider: "ollama",

View file

@ -99,6 +99,7 @@
"free-trial",
"openai-aiohttp",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",

View file

@ -99,6 +99,7 @@
"free-trial",
"openai-aiohttp",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",