Merge branch 'main' into completion_provider_replacement_diffpattern
This commit is contained in:
commit
7eecce5819
8 changed files with 619 additions and 82 deletions
|
|
@ -134,6 +134,13 @@ export class CompletionProvider {
|
|||
token: AbortSignal | undefined,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
try {
|
||||
// Create abort signal if not given
|
||||
if (!token) {
|
||||
const controller = this.loggingService.createAbortController(
|
||||
input.completionId,
|
||||
);
|
||||
token = controller.signal;
|
||||
}
|
||||
const startTime = Date.now();
|
||||
const options = await this._getAutocompleteOptions();
|
||||
|
||||
|
|
@ -158,14 +165,6 @@ export class CompletionProvider {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
// Create abort signal if not given
|
||||
if (!token) {
|
||||
const controller = this.loggingService.createAbortController(
|
||||
input.completionId,
|
||||
);
|
||||
token = controller.signal;
|
||||
}
|
||||
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippets({
|
||||
helper,
|
||||
|
|
|
|||
375
core/llm/llms/Bedrock.test.ts
Normal file
375
core/llm/llms/Bedrock.test.ts
Normal file
|
|
@ -0,0 +1,375 @@
|
|||
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
import Bedrock from "./Bedrock.js";
|
||||
import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js";
|
||||
|
||||
// Mock AWS SDK
|
||||
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
|
||||
BedrockRuntimeClient: jest.fn().mockImplementation(() => ({
|
||||
send: jest.fn(),
|
||||
middlewareStack: { add: jest.fn() },
|
||||
})),
|
||||
ConverseStreamCommand: jest.fn(),
|
||||
InvokeModelCommand: jest.fn(),
|
||||
}));
|
||||
|
||||
// Mock credential provider
|
||||
jest.mock("@aws-sdk/credential-providers", () => ({
|
||||
fromIni: jest.fn().mockImplementation(() => async () => ({
|
||||
accessKeyId: "test-access-key",
|
||||
secretAccessKey: "test-secret-key",
|
||||
sessionToken: "test-session-token",
|
||||
})),
|
||||
}));
|
||||
|
||||
// Extend CompletionOptions for testing
|
||||
interface TestCompletionOptions extends CompletionOptions {
|
||||
mockError?: string;
|
||||
mockToolUse?: boolean;
|
||||
}
|
||||
|
||||
// Create a test class that overrides the protected methods
|
||||
class TestBedrock extends Bedrock {
|
||||
// Make _streamChat public for testing
|
||||
public async *streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: TestCompletionOptions
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (options.mockError) {
|
||||
throw new Error(options.mockError);
|
||||
}
|
||||
|
||||
if (options.mockToolUse) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg1":"value1"}'
|
||||
}
|
||||
}],
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
yield { role: "assistant", content: "Hello" };
|
||||
yield { role: "assistant", content: " world" };
|
||||
}
|
||||
|
||||
// Override embed to avoid making real API calls
|
||||
async embed(chunks: string[]): Promise<number[][]> {
|
||||
if (chunks[0] === "error") {
|
||||
throw new Error("Embedding Error");
|
||||
}
|
||||
return [[0.1, 0.2, 0.3]];
|
||||
}
|
||||
|
||||
// Override rerank to avoid making real API calls
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || !chunks.length) {
|
||||
throw new Error("Query and chunks must not be empty");
|
||||
}
|
||||
|
||||
if (query === "error") {
|
||||
throw new Error("Reranking Error");
|
||||
}
|
||||
|
||||
return chunks.map((_, i) => 0.8 - i * 0.3);
|
||||
}
|
||||
}
|
||||
|
||||
describe("Bedrock", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("constructor", () => {
|
||||
it("should initialize with default options", () => {
|
||||
const bedrock = new TestBedrock({
|
||||
apiKey: "test-key",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
region: "us-east-1",
|
||||
});
|
||||
|
||||
expect(bedrock.region).toBe("us-east-1");
|
||||
expect(bedrock.profile).toBe("bedrock");
|
||||
expect(bedrock.apiBase).toBe("https://bedrock-runtime.us-east-1.amazonaws.com");
|
||||
});
|
||||
|
||||
it("should use custom options when provided", () => {
|
||||
const bedrock = new TestBedrock({
|
||||
apiKey: "test-key",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
region: "us-west-2",
|
||||
profile: "custom-profile",
|
||||
apiBase: "https://custom-endpoint.amazonaws.com/",
|
||||
});
|
||||
|
||||
expect(bedrock.region).toBe("us-west-2");
|
||||
expect(bedrock.profile).toBe("custom-profile");
|
||||
expect(bedrock.apiBase).toBe("https://custom-endpoint.amazonaws.com/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("streamChat", () => {
|
||||
let bedrock: TestBedrock;
|
||||
const mockAbortSignal = new AbortController().signal;
|
||||
const defaultOptions: TestCompletionOptions = {
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
bedrock = new TestBedrock({
|
||||
apiKey: "test-key",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
region: "us-east-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle text streaming correctly", async () => {
|
||||
const messages: ChatMessage[] = [{
|
||||
role: "user",
|
||||
content: "Hi"
|
||||
} as UserChatMessage];
|
||||
|
||||
const results = [];
|
||||
|
||||
for await (const message of bedrock.streamChat(messages, mockAbortSignal, defaultOptions)) {
|
||||
results.push(message);
|
||||
}
|
||||
|
||||
expect(results).toEqual([
|
||||
{ role: "assistant", content: "Hello" },
|
||||
{ role: "assistant", content: " world" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle tool use streaming correctly", async () => {
|
||||
const messages: ChatMessage[] = [{
|
||||
role: "user",
|
||||
content: "Use a tool"
|
||||
} as UserChatMessage];
|
||||
|
||||
const results = [];
|
||||
const options: TestCompletionOptions = {
|
||||
...defaultOptions,
|
||||
mockToolUse: true
|
||||
};
|
||||
|
||||
for await (const message of bedrock.streamChat(messages, mockAbortSignal, options)) {
|
||||
results.push(message);
|
||||
}
|
||||
|
||||
expect(results).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg1":"value1"}'
|
||||
}
|
||||
}],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle API errors", async () => {
|
||||
const messages: ChatMessage[] = [{
|
||||
role: "user",
|
||||
content: "Hi"
|
||||
} as UserChatMessage];
|
||||
|
||||
const options: TestCompletionOptions = {
|
||||
...defaultOptions,
|
||||
mockError: "API Error"
|
||||
};
|
||||
|
||||
await expect(async () => {
|
||||
for await (const _ of bedrock.streamChat(messages, mockAbortSignal, options)) {
|
||||
// consume generator
|
||||
}
|
||||
}).rejects.toThrow("API Error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("embed", () => {
|
||||
let bedrock: TestBedrock;
|
||||
|
||||
beforeEach(() => {
|
||||
bedrock = new TestBedrock({
|
||||
apiKey: "test-key",
|
||||
model: "cohere.embed-english-v3",
|
||||
region: "us-east-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle embedding requests correctly", async () => {
|
||||
const result = await bedrock.embed(["test text"]);
|
||||
expect(result).toEqual([[0.1, 0.2, 0.3]]);
|
||||
});
|
||||
|
||||
it("should handle embedding errors", async () => {
|
||||
await expect(bedrock.embed(["error"])).rejects.toThrow("Embedding Error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("rerank", () => {
|
||||
let bedrock: TestBedrock;
|
||||
|
||||
beforeEach(() => {
|
||||
bedrock = new TestBedrock({
|
||||
apiKey: "test-key",
|
||||
model: "cohere.rerank-english-v2.0",
|
||||
region: "us-east-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle reranking requests correctly", async () => {
|
||||
const chunks: Chunk[] = [
|
||||
{
|
||||
content: "doc1",
|
||||
digest: "digest1",
|
||||
filepath: "file1",
|
||||
index: 0,
|
||||
startLine: 1,
|
||||
endLine: 1
|
||||
},
|
||||
{
|
||||
content: "doc2",
|
||||
digest: "digest2",
|
||||
filepath: "file2",
|
||||
index: 1,
|
||||
startLine: 1,
|
||||
endLine: 1
|
||||
}
|
||||
];
|
||||
|
||||
const result = await bedrock.rerank("query", chunks);
|
||||
expect(result).toEqual([0.8, 0.5]);
|
||||
});
|
||||
|
||||
it("should handle reranking errors", async () => {
|
||||
const chunk: Chunk = {
|
||||
content: "doc1",
|
||||
digest: "digest1",
|
||||
filepath: "file1",
|
||||
index: 0,
|
||||
startLine: 1,
|
||||
endLine: 1
|
||||
};
|
||||
|
||||
await expect(
|
||||
bedrock.rerank("error", [chunk])
|
||||
).rejects.toThrow("Reranking Error");
|
||||
});
|
||||
|
||||
it("should throw error for empty input", async () => {
|
||||
await expect(bedrock.rerank("", [])).rejects.toThrow("Query and chunks must not be empty");
|
||||
});
|
||||
});
|
||||
|
||||
describe("message conversion", () => {
|
||||
let bedrock: TestBedrock;
|
||||
|
||||
beforeEach(() => {
|
||||
bedrock = new TestBedrock({
|
||||
apiKey: "test-key",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
region: "us-east-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("should convert text messages correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content: "Hello"
|
||||
} as UserChatMessage;
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [{ text: "Hello" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("should convert tool responses correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "tool",
|
||||
content: "Tool result",
|
||||
toolCallId: "tool-1",
|
||||
};
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [{
|
||||
toolResult: {
|
||||
toolUseId: "tool-1",
|
||||
content: [{ text: "Tool result" }],
|
||||
},
|
||||
}],
|
||||
});
|
||||
});
|
||||
|
||||
it("should convert tool calls correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: "tool-1",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
},
|
||||
}],
|
||||
};
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "assistant",
|
||||
content: [{
|
||||
toolUse: {
|
||||
toolUseId: "tool-1",
|
||||
name: "test_tool",
|
||||
input: { arg: "value" },
|
||||
},
|
||||
}],
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle multimodal content correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Look at this image:" },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
|
||||
},
|
||||
},
|
||||
],
|
||||
} as UserChatMessage;
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [
|
||||
{ text: "Look at this image:" },
|
||||
{
|
||||
image: {
|
||||
format: "jpeg",
|
||||
source: {
|
||||
bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -10,7 +10,6 @@ import {
|
|||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessageContent,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
|
@ -20,6 +19,15 @@ interface ModelConfig {
|
|||
extractEmbeddings: (responseBody: any) => number[][];
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for tool use state tracking
|
||||
*/
|
||||
interface ToolUseState {
|
||||
toolUseId: string;
|
||||
name: string;
|
||||
input: string;
|
||||
}
|
||||
|
||||
class Bedrock extends BaseLLM {
|
||||
static providerName = "bedrock";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
|
|
@ -29,6 +37,10 @@ class Bedrock extends BaseLLM {
|
|||
profile: "bedrock",
|
||||
};
|
||||
|
||||
private _currentToolResponse: Partial<ToolUseState> | null = null;
|
||||
|
||||
public requestOptions: { region?: string; credentials?: any; headers?: Record<string, string> };
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
if (!options.apiBase) {
|
||||
|
|
@ -39,6 +51,10 @@ class Bedrock extends BaseLLM {
|
|||
} else {
|
||||
this.profile = "bedrock";
|
||||
}
|
||||
this.requestOptions = {
|
||||
region: options.region,
|
||||
headers: {},
|
||||
};
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
|
|
@ -58,7 +74,6 @@ class Bedrock extends BaseLLM {
|
|||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const credentials = await this._getCredentials();
|
||||
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
endpoint: this.apiBase,
|
||||
|
|
@ -70,9 +85,9 @@ class Bedrock extends BaseLLM {
|
|||
});
|
||||
|
||||
let config_headers =
|
||||
this.requestOptions && this.requestOptions.headers
|
||||
? this.requestOptions.headers
|
||||
: {};
|
||||
this.requestOptions && this.requestOptions.headers
|
||||
? this.requestOptions.headers
|
||||
: {};
|
||||
// AWS SigV4 requires strict canonicalization of headers.
|
||||
// DO NOT USE "_" in your header name. It will return an error like below.
|
||||
// "The request signature we calculated does not match the signature you provided."
|
||||
|
|
@ -90,32 +105,116 @@ class Bedrock extends BaseLLM {
|
|||
},
|
||||
);
|
||||
|
||||
const input = this._generateConverseInput(messages, options);
|
||||
const input = this._generateConverseInput(messages, { ...options, stream: true });
|
||||
const command = new ConverseStreamCommand(input);
|
||||
const response = await client.send(command, { abortSignal: signal });
|
||||
|
||||
if (response.stream) {
|
||||
let response;
|
||||
try {
|
||||
response = await client.send(command, { abortSignal: signal });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
throw new Error(`Failed to communicate with Bedrock API: ${message}`);
|
||||
}
|
||||
|
||||
if (!response?.stream) {
|
||||
throw new Error("No stream received from Bedrock API");
|
||||
}
|
||||
|
||||
try {
|
||||
for await (const chunk of response.stream) {
|
||||
if (chunk.contentBlockDelta?.delta?.text) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: chunk.contentBlockDelta.delta.text,
|
||||
};
|
||||
|
||||
console.log(chunk);
|
||||
|
||||
if (chunk.contentBlockDelta?.delta) {
|
||||
|
||||
// Handle text content
|
||||
if (chunk.contentBlockDelta.delta.text) {
|
||||
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
|
||||
continue;
|
||||
}
|
||||
|
||||
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
|
||||
// Append the new input to the existing string
|
||||
if (this._currentToolResponse.input === undefined) {
|
||||
this._currentToolResponse.input = "";
|
||||
}
|
||||
this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.contentBlockStart?.start) {
|
||||
const toolUse = chunk.contentBlockStart.start.toolUse;
|
||||
if (toolUse?.toolUseId && toolUse?.name) {
|
||||
this._currentToolResponse = {
|
||||
toolUseId: toolUse.toolUseId,
|
||||
name: toolUse.name,
|
||||
input: ""
|
||||
};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (chunk.contentBlockStop) {
|
||||
if (this._currentToolResponse) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: this._currentToolResponse.toolUseId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: this._currentToolResponse.name,
|
||||
arguments: this._currentToolResponse.input
|
||||
}
|
||||
}],
|
||||
};
|
||||
this._currentToolResponse = null;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
this._currentToolResponse = null;
|
||||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`);
|
||||
}
|
||||
throw new Error(`Error processing Bedrock stream: ${error.message}`);
|
||||
}
|
||||
throw new Error("Error processing Bedrock stream: Unknown error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the input payload for the Bedrock Converse API
|
||||
* @param messages - Array of chat messages
|
||||
* @param options - Completion options
|
||||
* @returns Formatted input payload for the API
|
||||
*/
|
||||
private _generateConverseInput(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
): any {
|
||||
const convertedMessages = this._convertMessages(messages);
|
||||
|
||||
const isClaudeModel = options.model?.toLowerCase().includes("claude");
|
||||
return {
|
||||
modelId: options.model,
|
||||
messages: convertedMessages,
|
||||
system: this.systemMessage ? [{ text: this.systemMessage }] : undefined,
|
||||
toolConfig: isClaudeModel && options.tools ? {
|
||||
tools: options.tools.map(tool => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters
|
||||
}
|
||||
}
|
||||
}))
|
||||
} : undefined,
|
||||
inferenceConfig: {
|
||||
maxTokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
|
|
@ -135,35 +234,93 @@ class Bedrock extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
private _convertMessages(messages: ChatMessage[]): any[] {
|
||||
return messages
|
||||
.filter((message) => message.role !== "system")
|
||||
.map((message) => ({
|
||||
private _convertMessage(message: ChatMessage): any {
|
||||
// Handle system messages explicitly
|
||||
if (message.role === "system") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Tool response handling
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
toolResult: {
|
||||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: message.content || ""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
// Tool calls handling
|
||||
if (message.role === "assistant" && message.toolCalls) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: message.toolCalls.map((toolCall) => ({
|
||||
toolUse: {
|
||||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
}
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
// Standard text message
|
||||
if (typeof message.content === "string") {
|
||||
return {
|
||||
role: message.role,
|
||||
content: this._convertMessageContent(message.content),
|
||||
}));
|
||||
content: [{ text: message.content }]
|
||||
};
|
||||
}
|
||||
|
||||
// Improved multimodal content handling
|
||||
if (Array.isArray(message.content)) {
|
||||
return {
|
||||
role: message.role,
|
||||
content: message.content.map(part => {
|
||||
if (part.type === "text") {
|
||||
return { text: part.text };
|
||||
}
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
try {
|
||||
const [mimeType, base64Data] = part.imageUrl.url.split(",");
|
||||
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
|
||||
return {
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Buffer.from(base64Data, "base64")
|
||||
}
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process image: ${error}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}).filter(Boolean)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private _convertMessageContent(messageContent: MessageContent): any[] {
|
||||
if (typeof messageContent === "string") {
|
||||
return [{ text: messageContent }];
|
||||
}
|
||||
return messageContent
|
||||
.map((part) => {
|
||||
if (part.type === "text") {
|
||||
return { text: part.text };
|
||||
private _convertMessages(messages: ChatMessage[]): any[] {
|
||||
return messages
|
||||
.map((message) => {
|
||||
try {
|
||||
return this._convertMessage(message);
|
||||
} catch (error) {
|
||||
console.error(`Failed to convert message: ${error}`);
|
||||
return null;
|
||||
}
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
return {
|
||||
image: {
|
||||
format: "jpeg",
|
||||
source: {
|
||||
bytes: Buffer.from(part.imageUrl.url.split(",")[1], "base64"),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
|
@ -229,6 +386,7 @@ class Bedrock extends BaseLLM {
|
|||
return modelConfig.extractEmbeddings(responseBody);
|
||||
}
|
||||
|
||||
|
||||
private _getModelConfig() {
|
||||
const modelConfigs: { [key: string]: ModelConfig } = {
|
||||
cohere: {
|
||||
|
|
@ -301,9 +459,15 @@ class Bedrock extends BaseLLM {
|
|||
return responseBody.results
|
||||
.sort((a: any, b: any) => a.index - b.index)
|
||||
.map((result: any) => result.relevance_score);
|
||||
} catch (error) {
|
||||
console.error("Error in BedrockReranker.rerank:", error);
|
||||
throw error;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`);
|
||||
}
|
||||
throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
|
||||
}
|
||||
throw new Error("Error in BedrockReranker.rerank: Unknown error occurred");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,9 @@ class NCompass extends OpenAI {
|
|||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
"qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
|
||||
"qwen2.5-coder:7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
|
||||
"qwen2.5-coder-32b": "Qwen/Qwen2.5-Coder-32B-Instruct",
|
||||
"qwen2.5-coder:32b": "Qwen/Qwen2.5-Coder-32B-Instruct",
|
||||
};
|
||||
protected _convertModelName(model: string): string {
|
||||
return NCompass.modelConversion[model] ?? model;
|
||||
|
|
|
|||
|
|
@ -29,6 +29,16 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
// All gemini models support function calling
|
||||
return model.toLowerCase().includes("gemini");
|
||||
},
|
||||
bedrock: (model) => {
|
||||
// Support only Claude 3.5 models on Bedrock, mirroring anthropic configuration
|
||||
if (
|
||||
["claude-3-5", "claude-3.5"].some((part) =>
|
||||
model.toLowerCase().includes(part),
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
// https://ollama.com/search?c=tools
|
||||
ollama: (model) => {
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -54,17 +54,15 @@ fun Editor.addInlayElement(
|
|||
class AutocompleteService(private val project: Project) {
|
||||
var pendingCompletion: PendingCompletion? = null
|
||||
private val autocompleteLookupListener = project.service<AutocompleteLookupListener>()
|
||||
private var widget: AutocompleteSpinnerWidget? = null
|
||||
private val widget: AutocompleteSpinnerWidget? by lazy {
|
||||
WindowManager.getInstance().getStatusBar(project)
|
||||
?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget
|
||||
}
|
||||
|
||||
// To avoid triggering another completion on partial acceptance,
|
||||
// we need to keep track of whether the last change was a partial accept
|
||||
var lastChangeWasPartialAccept = false
|
||||
|
||||
init {
|
||||
val statusBar = WindowManager.getInstance().getStatusBar(project)
|
||||
widget = statusBar.getWidget("AutocompleteSpinnerWidget") as? AutocompleteSpinnerWidget
|
||||
}
|
||||
|
||||
fun triggerCompletion(editor: Editor) {
|
||||
val settings =
|
||||
ServiceManager.getService(ContinueExtensionSettings::class.java)
|
||||
|
|
@ -80,13 +78,14 @@ class AutocompleteService(private val project: Project) {
|
|||
val completionId = uuid()
|
||||
val offset = editor.caretModel.primaryCaret.offset
|
||||
pendingCompletion = PendingCompletion(editor, offset, completionId, null)
|
||||
widget?.setLoading(true)
|
||||
|
||||
// Request a completion from the core
|
||||
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
|
||||
|
||||
val uri = virtualFile?.toUriOrNull() ?: return
|
||||
|
||||
widget?.setLoading(true)
|
||||
|
||||
val line = editor.caretModel.primaryCaret.logicalPosition.line
|
||||
val column = editor.caretModel.primaryCaret.logicalPosition.column
|
||||
val input = mapOf(
|
||||
|
|
@ -106,7 +105,9 @@ class AutocompleteService(private val project: Project) {
|
|||
input,
|
||||
null,
|
||||
({ response ->
|
||||
widget?.setLoading(false)
|
||||
if (pendingCompletion == null || pendingCompletion?.completionId == completionId) {
|
||||
widget?.setLoading(false)
|
||||
}
|
||||
|
||||
val responseObject = response as Map<*, *>
|
||||
val completions = responseObject["content"] as List<*>
|
||||
|
|
|
|||
|
|
@ -23,17 +23,7 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project),
|
|||
private val iconLabel = JLabel()
|
||||
private var isLoading = false
|
||||
|
||||
private val animatedIcon = AnimatedIcon(
|
||||
100,
|
||||
IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading1(RiderLight).svg", javaClass),
|
||||
IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading2(RiderLight).svg", javaClass),
|
||||
IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading3(RiderLight).svg", javaClass),
|
||||
IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading4(RiderLight).svg", javaClass),
|
||||
IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading5(RiderLight).svg", javaClass),
|
||||
IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading6(RiderLight).svg", javaClass),
|
||||
IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading7(RiderLight).svg", javaClass),
|
||||
IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading8(RiderLight).svg", javaClass),
|
||||
)
|
||||
private val animatedIcon = AnimatedIcon.Default()
|
||||
|
||||
init {
|
||||
Disposer.register(ContinuePluginDisposable.getInstance(project), this)
|
||||
|
|
@ -47,10 +37,10 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project),
|
|||
override fun dispose() {}
|
||||
|
||||
override fun ID(): String {
|
||||
return "AutocompleteSpinnerWidget"
|
||||
return ID
|
||||
}
|
||||
|
||||
override fun getTooltipText(): String? {
|
||||
override fun getTooltipText(): String {
|
||||
val enabled = service<ContinueExtensionSettings>().state.enableTabAutocomplete
|
||||
return if (enabled) "Continue autocomplete enabled" else "Continue autocomplete disabled"
|
||||
}
|
||||
|
|
@ -80,9 +70,13 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project),
|
|||
updateIcon()
|
||||
}
|
||||
|
||||
override fun getPresentation(): StatusBarWidget.WidgetPresentation? {
|
||||
override fun getPresentation(): StatusBarWidget.WidgetPresentation {
|
||||
return this
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ID = "AutocompleteSpinnerWidget"
|
||||
}
|
||||
}
|
||||
|
||||
class AutocompleteSpinnerWidgetFactory : StatusBarWidgetFactory {
|
||||
|
|
@ -91,7 +85,7 @@ class AutocompleteSpinnerWidgetFactory : StatusBarWidgetFactory {
|
|||
}
|
||||
|
||||
override fun getId(): String {
|
||||
return "AutocompleteSpinnerWidget"
|
||||
return AutocompleteSpinnerWidget.ID
|
||||
}
|
||||
|
||||
override fun getDisplayName(): String {
|
||||
|
|
@ -103,7 +97,7 @@ class AutocompleteSpinnerWidgetFactory : StatusBarWidgetFactory {
|
|||
}
|
||||
|
||||
override fun createWidget(project: Project): StatusBarWidget {
|
||||
return AutocompleteSpinnerWidget(project)
|
||||
return create(project)
|
||||
}
|
||||
|
||||
override fun disposeWidget(p0: StatusBarWidget) {
|
||||
|
|
|
|||
|
|
@ -8,8 +8,7 @@ import { ContinueServerClient } from "core/continueServer/stubs/client";
|
|||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { Core } from "core/core";
|
||||
import { walkDirAsync } from "core/indexing/walkDir";
|
||||
import { GlobalContext } from "core/util/GlobalContext";
|
||||
import { getConfigJsonPath, getDevDataFilePath } from "core/util/paths";
|
||||
import { getDevDataFilePath } from "core/util/paths";
|
||||
import { Telemetry } from "core/util/posthog";
|
||||
import readLastLines from "read-last-lines";
|
||||
import * as vscode from "vscode";
|
||||
|
|
@ -918,9 +917,6 @@ const getCommandsMap: (
|
|||
{
|
||||
label: quickPickStatusText(targetStatus),
|
||||
},
|
||||
{
|
||||
label: "$(gear) Configure autocomplete options",
|
||||
},
|
||||
{
|
||||
label: "$(feedback) Give feedback",
|
||||
},
|
||||
|
|
@ -945,10 +941,6 @@ const getCommandsMap: (
|
|||
targetStatus === StatusBarStatus.Enabled,
|
||||
vscode.ConfigurationTarget.Global,
|
||||
);
|
||||
} else if (
|
||||
selectedOption === "$(gear) Configure autocomplete options"
|
||||
) {
|
||||
ide.openFile(vscode.Uri.file(getConfigJsonPath()).toString());
|
||||
} else if (
|
||||
autocompleteModels.some((model) => model.title === selectedOption)
|
||||
) {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue