Continue CLI support provider Ask Sage
With a custom config.yaml file, a user can now specify models to use the Ask Sage provider (specifically, provider name is specified as 'askSage' in the provider parameter). Users can now use the CLI tool along with the VSCode extension, and can specify what tools/capabilities they would like the models to have within the CLI, as long as that model has the ability to use tools.
This commit is contained in:
parent
d95384f612
commit
b0fb345681
4 changed files with 906 additions and 0 deletions
543
packages/openai-adapters/src/apis/AskSage.ts
Normal file
543
packages/openai-adapters/src/apis/AskSage.ts
Normal file
|
|
@ -0,0 +1,543 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
import {
|
||||
ChatCompletion,
|
||||
ChatCompletionChunk,
|
||||
ChatCompletionCreateParamsNonStreaming,
|
||||
ChatCompletionCreateParamsStreaming,
|
||||
ChatCompletionMessageToolCall,
|
||||
Completion,
|
||||
CompletionCreateParamsNonStreaming,
|
||||
CompletionCreateParamsStreaming,
|
||||
CreateEmbeddingResponse,
|
||||
EmbeddingCreateParams,
|
||||
Model,
|
||||
} from "openai/resources/index";
|
||||
import { AskSageConfig } from "../types.js";
|
||||
import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js";
|
||||
import {
|
||||
BaseLlmApi,
|
||||
CreateRerankResponse,
|
||||
FimCreateParamsStreaming,
|
||||
RerankCreateParams,
|
||||
} from "./base.js";
|
||||
|
||||
const DEFAULT_API_URL = "https://api.asksage.ai/server";
|
||||
const DEFAULT_USER_API_URL = "https://api.asksage.ai/user";
|
||||
const TOKEN_TTL = 3600000; // 1 hour in milliseconds
|
||||
|
||||
/**
|
||||
* AskSage tool format (OpenAI-compatible)
|
||||
*/
|
||||
interface AskSageTool {
|
||||
type: string;
|
||||
function: {
|
||||
name: string;
|
||||
description?: string;
|
||||
parameters?: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
type ToolChoice =
|
||||
| "auto"
|
||||
| "none"
|
||||
| { type: "function"; function: { name: string } };
|
||||
|
||||
/**
|
||||
* AskSage API request body format
|
||||
*/
|
||||
interface AskSageRequestBody {
|
||||
message: string | Array<{ user: string; message: string }>;
|
||||
model: string;
|
||||
temperature?: number;
|
||||
mode?: "chat" | "deep_agent";
|
||||
limit_references?: 0 | 1;
|
||||
persona?: number;
|
||||
system_prompt?: string;
|
||||
tools?: AskSageTool[];
|
||||
tool_choice?: ToolChoice;
|
||||
reasoning_effort?: "low" | "medium" | "high";
|
||||
streaming?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* AskSage API response format
|
||||
*/
|
||||
interface AskSageResponse {
|
||||
text?: string;
|
||||
answer?: string;
|
||||
message?: string;
|
||||
status?: number | string;
|
||||
response?: unknown;
|
||||
tool_calls?: Array<{
|
||||
id: string;
|
||||
type: "function";
|
||||
function: {
|
||||
name: string;
|
||||
arguments: string;
|
||||
};
|
||||
}>;
|
||||
choices?: Array<{
|
||||
message?: {
|
||||
content?: string;
|
||||
tool_calls?: Array<{
|
||||
id: string;
|
||||
type: "function";
|
||||
function: {
|
||||
name: string;
|
||||
arguments: string;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
}>;
|
||||
}
|
||||
|
||||
interface TokenResponse {
|
||||
status: number | string;
|
||||
response: {
|
||||
access_token: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class AskSageApi implements BaseLlmApi {
|
||||
private apiBase: string;
|
||||
private userApiUrl: string;
|
||||
private apiKey?: string;
|
||||
private email?: string;
|
||||
private sessionTokenPromise: Promise<string> | null = null;
|
||||
private tokenTimestamp: number = 0;
|
||||
private fetchFn: typeof fetch;
|
||||
|
||||
constructor(private config: AskSageConfig) {
|
||||
this.apiBase = config.apiBase ?? DEFAULT_API_URL;
|
||||
this.userApiUrl = config.env?.userApiUrl ?? DEFAULT_USER_API_URL;
|
||||
this.apiKey = config.apiKey;
|
||||
this.email = config.env?.email;
|
||||
this.fetchFn = customFetch(config.requestOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get session token from API key + email, or use API key directly
|
||||
*/
|
||||
private async getSessionToken(): Promise<string> {
|
||||
if (!this.apiKey) {
|
||||
throw new Error(
|
||||
"AskSage adapter: missing apiKey. Provide it in your configuration.",
|
||||
);
|
||||
}
|
||||
|
||||
// If no email, use API key directly
|
||||
if (!this.email || this.email.length === 0) {
|
||||
return this.apiKey;
|
||||
}
|
||||
|
||||
const url = this.userApiUrl.replace(/\/$/, "") + "/get-token-with-api-key";
|
||||
const res = await this.fetchFn(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: this.email, api_key: this.apiKey }),
|
||||
});
|
||||
|
||||
const data = (await res.json()) as TokenResponse;
|
||||
if (parseInt(String(data.status)) !== 200) {
|
||||
throw new Error("Error getting access token: " + JSON.stringify(data));
|
||||
}
|
||||
return data.response.access_token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cached token or refresh if expired
|
||||
*/
|
||||
private async getToken(): Promise<string> {
|
||||
if (
|
||||
!this.sessionTokenPromise ||
|
||||
Date.now() - this.tokenTimestamp > TOKEN_TTL
|
||||
) {
|
||||
this.sessionTokenPromise = this.getSessionToken();
|
||||
this.tokenTimestamp = Date.now();
|
||||
}
|
||||
return this.sessionTokenPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear token cache (e.g., on 401 errors)
|
||||
*/
|
||||
private clearTokenCache(): void {
|
||||
this.sessionTokenPromise = null;
|
||||
this.tokenTimestamp = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get request headers with auth token
|
||||
*/
|
||||
private async getHeaders(): Promise<Record<string, string>> {
|
||||
const token = await this.getToken();
|
||||
return {
|
||||
accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"x-access-tokens": token,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert OpenAI messages to AskSage format
|
||||
*/
|
||||
private convertMessages(
|
||||
messages: ChatCompletionCreateParamsNonStreaming["messages"],
|
||||
): {
|
||||
systemPrompt?: string;
|
||||
messageArray: Array<{ user: string; message: string }>;
|
||||
} {
|
||||
let systemPrompt: string | undefined;
|
||||
const messageArray: Array<{ user: string; message: string }> = [];
|
||||
|
||||
for (const msg of messages) {
|
||||
if (msg.role === "system") {
|
||||
// Extract system message as system_prompt
|
||||
if (typeof msg.content === "string") {
|
||||
systemPrompt = msg.content;
|
||||
} else if (Array.isArray(msg.content)) {
|
||||
systemPrompt = msg.content
|
||||
.filter((p) => p.type === "text")
|
||||
.map((p) => (p as { type: "text"; text: string }).text)
|
||||
.join("\n");
|
||||
}
|
||||
} else if (msg.role === "user") {
|
||||
const content =
|
||||
typeof msg.content === "string"
|
||||
? msg.content
|
||||
: Array.isArray(msg.content)
|
||||
? msg.content
|
||||
.filter((p) => p.type === "text")
|
||||
.map((p) => (p as { type: "text"; text: string }).text)
|
||||
.join("\n")
|
||||
: "";
|
||||
messageArray.push({ user: "me", message: content });
|
||||
} else if (msg.role === "assistant") {
|
||||
const content =
|
||||
typeof msg.content === "string"
|
||||
? msg.content
|
||||
: Array.isArray(msg.content)
|
||||
? msg.content
|
||||
.filter((p) => p.type === "text")
|
||||
.map((p) => (p as { type: "text"; text: string }).text)
|
||||
.join("\n")
|
||||
: "";
|
||||
if (content) {
|
||||
messageArray.push({ user: "gpt", message: content });
|
||||
}
|
||||
} else if (msg.role === "tool") {
|
||||
// Include tool results as user messages
|
||||
const content =
|
||||
typeof msg.content === "string"
|
||||
? msg.content
|
||||
: JSON.stringify(msg.content);
|
||||
messageArray.push({
|
||||
user: "me",
|
||||
message: `Tool result for ${msg.tool_call_id}:\n${content}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { systemPrompt, messageArray };
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert OpenAI tools to AskSage format
|
||||
*/
|
||||
private convertTools(
|
||||
tools?: ChatCompletionCreateParamsNonStreaming["tools"],
|
||||
): AskSageTool[] | undefined {
|
||||
if (!tools || tools.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return tools.map((tool) => {
|
||||
if (tool.type === "function" && "function" in tool) {
|
||||
return {
|
||||
type: tool.type,
|
||||
function: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
parameters: tool.function.parameters as Record<string, unknown>,
|
||||
},
|
||||
};
|
||||
}
|
||||
throw new Error(`Unsupported tool type: ${tool.type}`);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert OpenAI tool_choice to AskSage format
|
||||
*/
|
||||
private convertToolChoice(
|
||||
toolChoice?: ChatCompletionCreateParamsNonStreaming["tool_choice"],
|
||||
): ToolChoice | undefined {
|
||||
if (!toolChoice) {
|
||||
return undefined;
|
||||
}
|
||||
if (toolChoice === "auto" || toolChoice === "none") {
|
||||
return toolChoice;
|
||||
}
|
||||
if (typeof toolChoice === "object" && "function" in toolChoice) {
|
||||
return {
|
||||
type: "function",
|
||||
function: { name: toolChoice.function.name },
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build AskSage request body from OpenAI params
|
||||
*/
|
||||
private buildRequestBody(
|
||||
body:
|
||||
| ChatCompletionCreateParamsNonStreaming
|
||||
| ChatCompletionCreateParamsStreaming,
|
||||
): AskSageRequestBody {
|
||||
const { systemPrompt, messageArray } = this.convertMessages(body.messages);
|
||||
|
||||
// If only one message and no system prompt needed in array format
|
||||
const message =
|
||||
messageArray.length === 1 && !systemPrompt
|
||||
? messageArray[0].message
|
||||
: messageArray;
|
||||
|
||||
const requestBody: AskSageRequestBody = {
|
||||
message,
|
||||
model: body.model,
|
||||
temperature: body.temperature ?? 0.0,
|
||||
mode: "chat",
|
||||
limit_references: 0,
|
||||
};
|
||||
|
||||
if (systemPrompt) {
|
||||
requestBody.system_prompt = systemPrompt;
|
||||
}
|
||||
|
||||
const tools = this.convertTools(body.tools);
|
||||
if (tools) {
|
||||
requestBody.tools = tools;
|
||||
}
|
||||
|
||||
const toolChoice = this.convertToolChoice(body.tool_choice);
|
||||
if (toolChoice) {
|
||||
requestBody.tool_choice = toolChoice;
|
||||
}
|
||||
|
||||
return requestBody;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse AskSage response into OpenAI ChatCompletion format
|
||||
*/
|
||||
private parseResponse(data: AskSageResponse, model: string): ChatCompletion {
|
||||
// Extract content from various response formats
|
||||
const content =
|
||||
data.text ||
|
||||
data.answer ||
|
||||
data.message ||
|
||||
data.choices?.[0]?.message?.content ||
|
||||
"";
|
||||
|
||||
// Extract tool calls
|
||||
const rawToolCalls =
|
||||
data.tool_calls || data.choices?.[0]?.message?.tool_calls;
|
||||
|
||||
const toolCalls: ChatCompletionMessageToolCall[] | undefined =
|
||||
rawToolCalls?.map((tc) => ({
|
||||
id: tc.id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.function.name,
|
||||
arguments: tc.function.arguments,
|
||||
},
|
||||
}));
|
||||
|
||||
return {
|
||||
id: uuidv4(),
|
||||
object: "chat.completion",
|
||||
model,
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
logprobs: null,
|
||||
finish_reason:
|
||||
toolCalls && toolCalls.length > 0 ? "tool_calls" : "stop",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: content || null,
|
||||
tool_calls:
|
||||
toolCalls && toolCalls.length > 0 ? toolCalls : undefined,
|
||||
refusal: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
usage: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async chatCompletionNonStream(
|
||||
body: ChatCompletionCreateParamsNonStreaming,
|
||||
signal: AbortSignal,
|
||||
): Promise<ChatCompletion> {
|
||||
const requestBody = this.buildRequestBody(body);
|
||||
const endpoint = `${this.apiBase.replace(/\/$/, "")}/query`;
|
||||
|
||||
try {
|
||||
const headers = await this.getHeaders();
|
||||
const response = await this.fetchFn(endpoint, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(requestBody),
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errText = await response.text();
|
||||
|
||||
// Clear token cache on 401
|
||||
if (response.status === 401) {
|
||||
this.clearTokenCache();
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`AskSage API error: ${response.status} ${response.statusText}: ${errText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as AskSageResponse;
|
||||
return this.parseResponse(data, body.model);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw new Error(`AskSage client error: ${error.message}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async *chatCompletionStream(
|
||||
body: ChatCompletionCreateParamsStreaming,
|
||||
signal: AbortSignal,
|
||||
): AsyncGenerator<ChatCompletionChunk> {
|
||||
// AskSage API may not support true SSE streaming
|
||||
// Implement as non-streaming call that yields chunks
|
||||
const requestBody = this.buildRequestBody(body);
|
||||
const endpoint = `${this.apiBase.replace(/\/$/, "")}/query`;
|
||||
|
||||
try {
|
||||
const headers = await this.getHeaders();
|
||||
const response = await this.fetchFn(endpoint, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(requestBody),
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errText = await response.text();
|
||||
|
||||
if (response.status === 401) {
|
||||
this.clearTokenCache();
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`AskSage API error: ${response.status} ${response.statusText}: ${errText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as AskSageResponse;
|
||||
|
||||
// Extract content
|
||||
const content =
|
||||
data.text ||
|
||||
data.answer ||
|
||||
data.message ||
|
||||
data.choices?.[0]?.message?.content ||
|
||||
"";
|
||||
|
||||
// Extract tool calls
|
||||
const rawToolCalls =
|
||||
data.tool_calls || data.choices?.[0]?.message?.tool_calls;
|
||||
|
||||
// Yield content as a single chunk
|
||||
if (content) {
|
||||
yield chatChunk({
|
||||
content,
|
||||
model: body.model,
|
||||
});
|
||||
}
|
||||
|
||||
// Yield tool calls if present
|
||||
if (rawToolCalls && rawToolCalls.length > 0) {
|
||||
for (const tc of rawToolCalls) {
|
||||
yield chatChunkFromDelta({
|
||||
model: body.model,
|
||||
delta: {
|
||||
tool_calls: [
|
||||
{
|
||||
index: 0,
|
||||
id: tc.id,
|
||||
type: "function",
|
||||
function: {
|
||||
name: tc.function.name,
|
||||
arguments: tc.function.arguments,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Yield finish chunk
|
||||
yield chatChunk({
|
||||
content: null,
|
||||
model: body.model,
|
||||
finish_reason:
|
||||
rawToolCalls && rawToolCalls.length > 0 ? "tool_calls" : "stop",
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw new Error(`AskSage client error: ${error.message}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
completionNonStream(
|
||||
_body: CompletionCreateParamsNonStreaming,
|
||||
_signal: AbortSignal,
|
||||
): Promise<Completion> {
|
||||
throw new Error("AskSage does not support legacy completions API");
|
||||
}
|
||||
|
||||
completionStream(
|
||||
_body: CompletionCreateParamsStreaming,
|
||||
_signal: AbortSignal,
|
||||
): AsyncGenerator<Completion> {
|
||||
throw new Error("AskSage does not support legacy completions API");
|
||||
}
|
||||
|
||||
fimStream(
|
||||
_body: FimCreateParamsStreaming,
|
||||
_signal: AbortSignal,
|
||||
): AsyncGenerator<ChatCompletionChunk> {
|
||||
throw new Error("AskSage does not support FIM");
|
||||
}
|
||||
|
||||
async embed(_body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
|
||||
throw new Error("AskSage does not support embeddings");
|
||||
}
|
||||
|
||||
async rerank(_body: RerankCreateParams): Promise<CreateRerankResponse> {
|
||||
throw new Error("AskSage does not support reranking");
|
||||
}
|
||||
|
||||
async list(): Promise<Model[]> {
|
||||
// AskSage has a /get-models endpoint, but it requires authentication
|
||||
// For now, return empty array - models are typically configured explicitly
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import dotenv from "dotenv";
|
||||
import { z } from "zod";
|
||||
import { AnthropicApi } from "./apis/Anthropic.js";
|
||||
import { AskSageApi } from "./apis/AskSage.js";
|
||||
import { AzureApi } from "./apis/Azure.js";
|
||||
import { BedrockApi } from "./apis/Bedrock.js";
|
||||
import { CohereApi } from "./apis/Cohere.js";
|
||||
|
|
@ -73,6 +74,8 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined {
|
|||
return new CohereApi(config);
|
||||
case "cometapi":
|
||||
return new CometAPIApi(config);
|
||||
case "askSage":
|
||||
return new AskSageApi(config);
|
||||
case "anthropic":
|
||||
return new AnthropicApi(config);
|
||||
case "gemini":
|
||||
|
|
|
|||
348
packages/openai-adapters/src/test/asksage-adapter.vitest.ts
Normal file
348
packages/openai-adapters/src/test/asksage-adapter.vitest.ts
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { runAdapterTest } from "./adapter-test-utils.js";
|
||||
|
||||
// Mock the fetch package
|
||||
vi.mock("@continuedev/fetch", async () => {
|
||||
const actual = await vi.importActual("@continuedev/fetch");
|
||||
return {
|
||||
...actual,
|
||||
fetchwithRequestOptions: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("AskSage Adapter Tests", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("should construct API correctly", async () => {
|
||||
const { constructLlmApi } = await import("../index.js");
|
||||
const api = constructLlmApi({
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
});
|
||||
expect(api).toBeDefined();
|
||||
});
|
||||
|
||||
test("should construct API with email config", async () => {
|
||||
const { constructLlmApi } = await import("../index.js");
|
||||
const api = constructLlmApi({
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.asksage.ai/server",
|
||||
env: {
|
||||
email: "test@example.com",
|
||||
userApiUrl: "https://api.asksage.ai/user",
|
||||
},
|
||||
});
|
||||
expect(api).toBeDefined();
|
||||
});
|
||||
|
||||
test("chatCompletionNonStream should send a valid request", async () => {
|
||||
await runAdapterTest({
|
||||
config: {
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.asksage.ai/server",
|
||||
},
|
||||
methodToTest: "chatCompletionNonStream",
|
||||
params: [
|
||||
{
|
||||
model: "gpt-4o",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.asksage.ai/server/query",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
accept: "application/json",
|
||||
"x-access-tokens": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
message: "hello",
|
||||
model: "gpt-4o",
|
||||
temperature: 0,
|
||||
mode: "chat",
|
||||
limit_references: 0,
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
text: "Hello! How can I help you today?",
|
||||
status: 200,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("chatCompletionNonStream with system message should convert correctly", async () => {
|
||||
await runAdapterTest({
|
||||
config: {
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.asksage.ai/server",
|
||||
},
|
||||
methodToTest: "chatCompletionNonStream",
|
||||
params: [
|
||||
{
|
||||
model: "gpt-4o",
|
||||
messages: [
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "hello" },
|
||||
],
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.asksage.ai/server/query",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
accept: "application/json",
|
||||
"x-access-tokens": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
message: [{ user: "me", message: "hello" }],
|
||||
model: "gpt-4o",
|
||||
temperature: 0,
|
||||
mode: "chat",
|
||||
limit_references: 0,
|
||||
system_prompt: "You are a helpful assistant.",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
text: "Hello! I'm here to help.",
|
||||
status: 200,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("chatCompletionNonStream with multi-turn conversation", async () => {
|
||||
await runAdapterTest({
|
||||
config: {
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.asksage.ai/server",
|
||||
},
|
||||
methodToTest: "chatCompletionNonStream",
|
||||
params: [
|
||||
{
|
||||
model: "gpt-4o",
|
||||
messages: [
|
||||
{ role: "user", content: "What is 2+2?" },
|
||||
{ role: "assistant", content: "4" },
|
||||
{ role: "user", content: "And 3+3?" },
|
||||
],
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.asksage.ai/server/query",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
accept: "application/json",
|
||||
"x-access-tokens": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
message: [
|
||||
{ user: "me", message: "What is 2+2?" },
|
||||
{ user: "gpt", message: "4" },
|
||||
{ user: "me", message: "And 3+3?" },
|
||||
],
|
||||
model: "gpt-4o",
|
||||
temperature: 0,
|
||||
mode: "chat",
|
||||
limit_references: 0,
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
text: "6",
|
||||
status: 200,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("chatCompletionNonStream with tools should convert correctly", async () => {
|
||||
await runAdapterTest({
|
||||
config: {
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.asksage.ai/server",
|
||||
},
|
||||
methodToTest: "chatCompletionNonStream",
|
||||
params: [
|
||||
{
|
||||
model: "gpt-4o",
|
||||
messages: [{ role: "user", content: "What's the weather in NYC?" }],
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
description: "Get current weather for a location",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string", description: "City name" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
tool_choice: "auto",
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.asksage.ai/server/query",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
accept: "application/json",
|
||||
"x-access-tokens": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
message: "What's the weather in NYC?",
|
||||
model: "gpt-4o",
|
||||
temperature: 0,
|
||||
mode: "chat",
|
||||
limit_references: 0,
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
description: "Get current weather for a location",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string", description: "City name" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
tool_choice: "auto",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_123",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
arguments: '{"location":"NYC"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
status: 200,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("chatCompletionStream should send a valid request", async () => {
|
||||
await runAdapterTest({
|
||||
config: {
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.asksage.ai/server",
|
||||
},
|
||||
methodToTest: "chatCompletionStream",
|
||||
params: [
|
||||
{
|
||||
model: "gpt-4o",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.asksage.ai/server/query",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
accept: "application/json",
|
||||
"x-access-tokens": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
message: "hello",
|
||||
model: "gpt-4o",
|
||||
temperature: 0,
|
||||
mode: "chat",
|
||||
limit_references: 0,
|
||||
},
|
||||
},
|
||||
// AskSage returns JSON, not SSE stream - the adapter converts it to chunks
|
||||
mockResponse: {
|
||||
text: "Hello! How can I help you today?",
|
||||
status: 200,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("embed should throw not supported error", async () => {
|
||||
const { constructLlmApi } = await import("../index.js");
|
||||
const api = constructLlmApi({
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
});
|
||||
|
||||
await expect(
|
||||
api!.embed({
|
||||
model: "text-embedding-ada-002",
|
||||
input: ["Hello", "World"],
|
||||
}),
|
||||
).rejects.toThrow("AskSage does not support embeddings");
|
||||
});
|
||||
|
||||
test("rerank should throw not supported error", async () => {
|
||||
const { constructLlmApi } = await import("../index.js");
|
||||
const api = constructLlmApi({
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
});
|
||||
|
||||
await expect(
|
||||
api!.rerank({
|
||||
model: "rerank-model",
|
||||
query: "test query",
|
||||
documents: ["doc1", "doc2"],
|
||||
}),
|
||||
).rejects.toThrow("AskSage does not support reranking");
|
||||
});
|
||||
|
||||
test("completionNonStream should throw not supported error", async () => {
|
||||
const { constructLlmApi } = await import("../index.js");
|
||||
const api = constructLlmApi({
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
api!.completionNonStream(
|
||||
{
|
||||
model: "gpt-4o",
|
||||
prompt: "Hello",
|
||||
},
|
||||
new AbortController().signal,
|
||||
),
|
||||
).toThrow("AskSage does not support legacy completions API");
|
||||
});
|
||||
|
||||
test("list should return empty array", async () => {
|
||||
const { constructLlmApi } = await import("../index.js");
|
||||
const api = constructLlmApi({
|
||||
provider: "askSage",
|
||||
apiKey: "test-api-key",
|
||||
});
|
||||
|
||||
const models = await api!.list();
|
||||
expect(models).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
@ -123,6 +123,17 @@ export const CometAPIConfigSchema = OpenAIConfigSchema.extend({
|
|||
});
|
||||
export type CometAPIConfig = z.infer<typeof CometAPIConfigSchema>;
|
||||
|
||||
export const AskSageConfigSchema = BasePlusConfig.extend({
|
||||
provider: z.literal("askSage"),
|
||||
env: z
|
||||
.object({
|
||||
email: z.string().optional(),
|
||||
userApiUrl: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
export type AskSageConfig = z.infer<typeof AskSageConfigSchema>;
|
||||
|
||||
export const AzureConfigSchema = OpenAIConfigSchema.extend({
|
||||
provider: z.literal("azure"),
|
||||
env: z
|
||||
|
|
@ -205,5 +216,6 @@ export const LLMConfigSchema = z.discriminatedUnion("provider", [
|
|||
LlamastackConfigSchema,
|
||||
ContinueProxyConfigSchema,
|
||||
CometAPIConfigSchema,
|
||||
AskSageConfigSchema,
|
||||
]);
|
||||
export type LLMConfig = z.infer<typeof LLMConfigSchema>;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue