✨ Claude 3 Support

This commit is contained in:
Nate Sesti 2024-03-04 12:10:24 -08:00
parent 5147a6266a
commit ef609833df
13 changed files with 177 additions and 80 deletions

View file

@ -1,4 +1,6 @@
import { distance } from "fastest-levenshtein";
import { ChatMessage } from "..";
import { stripImages } from "../llm/countTokens";
export type LineStream = AsyncGenerator<string>;
@ -57,10 +59,12 @@ export function matchLine(
* Convert a stream of arbitrary chunks to a stream of lines
*/
export async function* streamLines(
streamCompletion: AsyncGenerator<string>,
streamCompletion: AsyncGenerator<string | ChatMessage>,
): LineStream {
let buffer = "";
for await (const chunk of streamCompletion) {
for await (const update of streamCompletion) {
const chunk =
typeof update === "string" ? update : stripImages(update.content);
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";

27
core/index.d.ts vendored
View file

@ -16,7 +16,7 @@ declare global {
postIntellijMessage?: (
messageType: string,
data: any,
messageIde: string
messageIde: string,
) => void;
}
}
@ -73,17 +73,17 @@ export interface ILLM extends LLMOptions {
streamComplete(
prompt: string,
options?: LLMFullCompletionOptions
options?: LLMFullCompletionOptions,
): AsyncGenerator<string, LLMReturnValue>;
streamChat(
messages: ChatMessage[],
options?: LLMFullCompletionOptions
options?: LLMFullCompletionOptions,
): AsyncGenerator<ChatMessage, LLMReturnValue>;
chat(
messages: ChatMessage[],
options?: LLMFullCompletionOptions
options?: LLMFullCompletionOptions,
): Promise<ChatMessage>;
countTokens(text: string): number;
@ -123,10 +123,10 @@ export interface CustomContextProvider {
type?: ContextProviderType;
getContextItems(
query: string,
extras: ContextProviderExtras
extras: ContextProviderExtras,
): Promise<ContextItem[]>;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs
args: LoadSubmenuItemsArgs,
) => Promise<ContextSubmenuItem[]>;
}
@ -141,7 +141,7 @@ export interface IContextProvider {
getContextItems(
query: string,
extras: ContextProviderExtras
extras: ContextProviderExtras,
): Promise<ContextItem[]>;
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
@ -287,15 +287,15 @@ export interface CustomLLMWithOptionals {
streamCompletion?: (
prompt: string,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
streamChat?: (
messages: ChatMessage[],
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
listModels?: (
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => Promise<string[]>;
}
@ -349,12 +349,12 @@ export interface IDE {
showLines(
filepath: string,
startLine: number,
endLine: number
endLine: number,
): Promise<void>;
showDiff(
filepath: string,
newContents: string,
stepIndex: number
stepIndex: number,
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getPinnedFiles(): Promise<string[]>;
@ -488,6 +488,9 @@ export type ModelName =
| "neural-chat-7b"
// Anthropic
| "claude-2"
| "claude-3-opus-20240229"
| "claude-3-sonnet-20240229"
| "claude-2.1"
// Google PaLM
| "chat-bison-001"
// Gemini

View file

@ -16,6 +16,7 @@ import {
} from "./templates/chat";
import {
alpacaEditPrompt,
claudeEditPrompt,
codeLlama70bEditPrompt,
codellamaEditPrompt,
deepseekEditPrompt,
@ -34,6 +35,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"openai",
"ollama",
"together",
"anthropic",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
@ -236,6 +238,8 @@ function autodetectPromptTemplates(
editTemplate = neuralChatEditPrompt;
} else if (templateType === "codellama-70b") {
editTemplate = codeLlama70bEditPrompt;
} else if (templateType === "anthropic") {
editTemplate = claudeEditPrompt;
} else if (templateType) {
editTemplate = simplestEditPrompt;
}

View file

@ -1,16 +1,19 @@
import { BaseLLM } from "..";
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../..";
import { streamSse } from "../stream";
import { anthropicTemplateMessages } from "../templates/chat";
class Anthropic extends BaseLLM {
static providerName: ModelProvider = "anthropic";
static defaultOptions: Partial<LLMOptions> = {
model: "claude-2",
templateMessages: anthropicTemplateMessages,
contextLength: 100_000,
model: "claude-3-opus-20240229",
contextLength: 200_000,
completionOptions: {
model: "claude-2",
model: "claude-3-opus-20240229",
maxTokens: 4096,
},
apiBase: "https://api.anthropic.com/v1",
@ -20,25 +23,24 @@ class Anthropic extends BaseLLM {
super(options);
}
private _convertArgs(options: CompletionOptions, prompt: string) {
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
prompt,
top_k: options.topK,
top_p: options.topP,
temperature: options.temperature,
max_tokens_to_sample: options.maxTokens,
model: options.model,
max_tokens: options.maxTokens ?? 2048,
model: options.model === "claude-2" ? "claude-2.1" : options.model,
stop_sequences: options.stop,
};
return finalOptions;
}
protected async _complete(
prompt: string,
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): Promise<string> {
const response = await this.fetch(this.apiBase + "/complete", {
): AsyncGenerator<ChatMessage> {
const response = await this.fetch(this.apiBase + "/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -47,35 +49,16 @@ class Anthropic extends BaseLLM {
"x-api-key": this.apiKey as string,
},
body: JSON.stringify({
...this._convertArgs(options, prompt),
stream: false,
}),
});
const result = await response.json();
return result.completion;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.apiBase + "/complete", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.apiKey as string,
},
body: JSON.stringify({
...this._convertArgs(options, prompt),
...this._convertArgs(options),
messages,
system: this.systemMessage,
stream: true,
}),
});
for await (const value of streamSse(response)) {
if (value.completion) {
yield value.completion;
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}
}
}

View file

@ -1,3 +1,6 @@
import { ChatMessage } from "../..";
import { PromptTemplate } from "../../util";
const simplifiedEditPrompt = `Consider the following code:
\`\`\`{{{language}}}
{{{codeToEdit}}}
@ -144,8 +147,33 @@ const codeLlama70bEditPrompt = `<s>Source: system\n\n You are an expert programm
{{{codeToEdit}}}
\`\`\` <step> Source: assistant\nDestination: user\n\n `;
const claudeEditPrompt: PromptTemplate = (
history: ChatMessage[],
otherData: Record<string, string>,
) => [
{
role: "user",
content: `\
\`\`\`${otherData.language}
${otherData.codeToEdit}
\`\`\`
You are an expert programmer. You will rewrite the above code to do the following:
${otherData.userInput}
Output only a code block with the rewritten code:
`,
},
{
role: "assistant",
content: `Sure! Here is the rewritten code:
\`\`\`${otherData.language}`,
},
];
export {
alpacaEditPrompt,
claudeEditPrompt,
codeLlama70bEditPrompt,
codellamaEditPrompt,
codellamaInfillEditPrompt,

View file

@ -92,7 +92,7 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] {
return [lines.map((x) => x.replace(lcp, "")).join("\n"), lcp];
}
type PromptTemplate =
export type PromptTemplate =
| string
| ((
history: ChatMessage[],

View file

@ -1,4 +1,4 @@
import { DiffLine, ILLM } from "..";
import { ChatMessage, DiffLine, ILLM } from "..";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
@ -8,7 +8,6 @@ import {
} from "../autocomplete/lineStream";
import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { stripImages } from "../llm/countTokens";
import { gptEditPrompt } from "../llm/templates/edit";
import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../util";
@ -17,16 +16,13 @@ function constructPrompt(
llm: ILLM,
userInput: string,
language: string | undefined,
): string {
): string | ChatMessage[] {
const template = llm.promptTemplates?.edit ?? gptEditPrompt;
const rendered = renderPromptTemplate(template, [], {
return renderPromptTemplate(template, [], {
userInput,
codeToEdit,
language: language || "",
});
return typeof rendered === "string"
? rendered
: stripImages(rendered[rendered.length - 1].content);
}
async function* addIndentation(
@ -59,7 +55,10 @@ export async function* streamDiffLines(
const prompt = constructPrompt(oldCode, llm, input, language);
const inept = modelIsInept(llm.model);
const completion = llm.streamComplete(prompt);
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt)
: llm.streamChat(prompt);
let lines = streamLines(completion);

View file

@ -493,7 +493,13 @@
"model": {
"anyOf": [
{
"enum": ["claude-2", "claude-instant-1"]
"enum": [
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1"
]
},
{
"type": "string"
@ -837,6 +843,10 @@
"deepseek-7b",
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1",
"chat-bison-001",
"gemini-pro",
"mistral-tiny",

View file

@ -493,7 +493,13 @@
"model": {
"anyOf": [
{
"enum": ["claude-2", "claude-instant-1"]
"enum": [
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1"
]
},
{
"type": "string"
@ -837,6 +843,10 @@
"deepseek-7b",
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1",
"chat-bison-001",
"gemini-pro",
"mistral-tiny",

View file

@ -493,7 +493,13 @@
"model": {
"anyOf": [
{
"enum": ["claude-2", "claude-instant-1"]
"enum": [
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1"
]
},
{
"type": "string"
@ -837,6 +843,10 @@
"deepseek-7b",
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1",
"chat-bison-001",
"gemini-pro",
"mistral-tiny",

View file

@ -539,7 +539,10 @@
{
"enum": [
"claude-2",
"claude-instant-1"
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1"
]
},
{
@ -939,6 +942,10 @@
"deepseek-7b",
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1",
"chat-bison-001",
"gemini-pro",
"mistral-tiny",

View file

@ -696,6 +696,11 @@
resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz"
integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==
"@lancedb/vectordb-darwin-arm64@*":
version "0.4.11"
resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.11.tgz"
integrity sha512-JDOKmFnuJPFkA7ZmrzBJolROwSjWr7yMvAbi40uLBc25YbbVezodd30u2EFtIwWwtk1GqNYRZ49FZOElKYeC/Q==
"@lancedb/vectordb-darwin-arm64@0.4.10":
version "0.4.10"
resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz"

View file

@ -526,12 +526,54 @@ const gpt35turbo: ModelPackage = {
};
const claude2: ModelPackage = {
title: "Claude-2",
title: "Claude 2",
description: "A highly capable model with a 100k context length",
params: {
model: "claude-2.1",
contextLength: 100_000,
title: "Claude 2",
apiKey: "",
},
providerOptions: ["anthropic"],
icon: "anthropic.png",
};
const claude3Opus: ModelPackage = {
title: "Claude 3 Opus",
description:
"Anthropic's most capable model, beating GPT-4 on many benchmarks",
params: {
model: "claude-3-opus-20240229",
contextLength: 200_000,
title: "Claude 3 Opus",
apiKey: "",
},
providerOptions: ["anthropic"],
icon: "anthropic.png",
};
const claude3Sonnet: ModelPackage = {
title: "Claude 3 Sonnet",
description:
"The second most capable model in the Claude 3 series: ideal balance of intelligence and speed",
params: {
model: "claude-3-sonnet-20240229",
contextLength: 200_000,
title: "Claude 3 Sonnet",
apiKey: "",
},
providerOptions: ["anthropic"],
icon: "anthropic.png",
};
const claude3Haiku: ModelPackage = {
title: "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: "claude-2",
contextLength: 100000,
title: "Claude-2",
contextLength: 200_000,
title: "Claude 3 Haiku",
apiKey: "",
},
providerOptions: ["anthropic"],
@ -567,6 +609,8 @@ export const MODEL_INFO: ModelPackage[] = [
gpt4,
gpt35turbo,
geminiPro,
claude3Opus,
claude3Sonnet,
claude2,
deepseek,
mistral,
@ -616,7 +660,7 @@ export const PROVIDER_INFO: { [key: string]: ModelInfo } = {
provider: "anthropic",
refPage: "anthropicllm",
description:
"Claude-2 is a highly capable model with a 100k context length",
"Anthropic builds state-of-the-art models with large context length and high recall",
icon: "anthropic.png",
tags: [ModelProviderTag["Requires API Key"]],
longDescription:
@ -635,17 +679,7 @@ export const PROVIDER_INFO: { [key: string]: ModelInfo } = {
defaultValue: 100_000,
},
],
packages: [
{
title: "Claude-2",
description: "A highly capable model with a 100k context length",
params: {
model: "claude-2",
contextLength: 100000,
title: "Claude-2",
},
},
],
packages: [claude3Opus, claude3Sonnet, claude2],
},
ollama: {
title: "Ollama",