| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360 |
- import { describe, expect } from "bun:test"
- import { Effect, Schema } from "effect"
- import { HttpClientRequest } from "effect/unstable/http"
- import { LLM, LLMRequest, Message, ToolCallPart, ToolChoice, ToolDefinition } from "../../src"
- import { Auth, LLMClient } from "../../src/route"
- import { compileRequest } from "../../src/route/client"
- import * as OpenAICompatible from "../../src/providers/openai-compatible"
- import * as OpenAICompatibleChat from "../../src/protocols/openai-compatible-chat"
- import { it } from "../lib/effect"
- import { dynamicResponse, fixedResponse } from "../lib/http"
- import { sseEvents } from "../lib/sse"
- const Json = Schema.fromJsonString(Schema.Unknown)
- const decodeJson = Schema.decodeUnknownSync(Json)
- const model = OpenAICompatibleChat.route
- .with({
- provider: "deepseek",
- endpoint: { baseURL: "https://api.deepseek.test/v1/", query: { "api-version": "2026-01-01" } },
- auth: Auth.bearer("test-key"),
- })
- .model({ id: "deepseek-chat" })
- const request = LLM.request({
- id: "req_1",
- model,
- system: "You are concise.",
- prompt: "Say hello.",
- generation: { maxTokens: 20, temperature: 0 },
- })
- const deltaChunk = (delta: object, finishReason: string | null = null) => ({
- id: "chatcmpl_fixture",
- choices: [{ delta, finish_reason: finishReason }],
- usage: null,
- })
- const usageChunk = (usage: object) => ({
- id: "chatcmpl_fixture",
- choices: [],
- usage,
- })
- const providerFamilies = [
- ["baseten", OpenAICompatible.baseten, "https://inference.baseten.co/v1"],
- ["cerebras", OpenAICompatible.cerebras, "https://api.cerebras.ai/v1"],
- ["deepinfra", OpenAICompatible.deepinfra, "https://api.deepinfra.com/v1/openai"],
- ["deepseek", OpenAICompatible.deepseek, "https://api.deepseek.com/v1"],
- ["fireworks", OpenAICompatible.fireworks, "https://api.fireworks.ai/inference/v1"],
- ["togetherai", OpenAICompatible.togetherai, "https://api.together.xyz/v1"],
- ] as const
- describe("OpenAI-compatible Chat route", () => {
- it.effect("prepares generic Chat target", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLMRequest.update(request, {
- tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
- toolChoice: ToolChoice.make({ type: "required" }),
- }),
- )
- expect(prepared.route).toBe("openai-compatible-chat")
- expect(prepared.model).toMatchObject({
- id: "deepseek-chat",
- provider: "deepseek",
- route: { id: "openai-compatible-chat" },
- })
- expect(prepared.model.route.endpoint).toMatchObject({
- baseURL: "https://api.deepseek.test/v1/",
- query: { "api-version": "2026-01-01" },
- })
- expect(prepared.body).toEqual({
- model: "deepseek-chat",
- messages: [
- { role: "system", content: "You are concise." },
- { role: "user", content: "Say hello." },
- ],
- tools: [
- {
- type: "function",
- function: { name: "lookup", description: "Lookup data", parameters: { type: "object" } },
- },
- ],
- tool_choice: "required",
- stream: true,
- stream_options: { include_usage: true },
- max_tokens: 20,
- temperature: 0,
- })
- }),
- )
- it.effect("provides model helpers for compatible provider families", () =>
- Effect.gen(function* () {
- expect(
- providerFamilies.map(([provider, family]) => {
- const model = family.configure({ apiKey: "test-key" }).model(`${provider}-model`)
- return {
- id: String(model.id),
- provider: String(model.provider),
- route: model.route.id,
- baseURL: model.route.endpoint.baseURL,
- }
- }),
- ).toEqual(
- providerFamilies.map(([provider, _, baseURL]) => ({
- id: `${provider}-model`,
- provider,
- route: "openai-compatible-chat",
- baseURL,
- })),
- )
- const custom = OpenAICompatible.deepseek
- .configure({
- apiKey: "test-key",
- baseURL: "https://custom.deepseek.test/v1",
- })
- .model("deepseek-chat")
- expect(custom).toMatchObject({
- provider: "deepseek",
- route: { id: "openai-compatible-chat" },
- })
- expect(custom.route.endpoint.baseURL).toBe("https://custom.deepseek.test/v1")
- }),
- )
- it.effect("matches AI SDK compatible basic request body fixture", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(request)
- expect(prepared.body).toEqual({
- model: "deepseek-chat",
- messages: [
- { role: "system", content: "You are concise." },
- { role: "user", content: "Say hello." },
- ],
- stream: true,
- stream_options: { include_usage: true },
- max_tokens: 20,
- temperature: 0,
- })
- }),
- )
- it.effect("configures the max tokens request field", () =>
- Effect.gen(function* () {
- const compatible = OpenAICompatibleChat.route
- .with({ provider: "custom", endpoint: { baseURL: "https://api.custom.test/v1" } })
- .model({ id: "custom-model", compatibility: { maxTokensField: "max_completion_tokens" } })
- const prepared = yield* compileRequest(
- LLM.request({ model: compatible, prompt: "Say hello.", generation: { maxTokens: 20 } }),
- )
- expect(prepared.body).toMatchObject({ max_completion_tokens: 20 })
- expect(prepared.body).not.toHaveProperty("max_tokens")
- }),
- )
- it.effect("matches AI SDK compatible tool request body fixture", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- id: "req_tool_parity",
- model,
- tools: [
- {
- name: "lookup",
- description: "Lookup data",
- inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] },
- },
- ],
- toolChoice: "lookup",
- messages: [
- Message.user("What is the weather?"),
- Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
- Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
- ],
- }),
- )
- expect(prepared.body).toEqual({
- model: "deepseek-chat",
- messages: [
- { role: "user", content: "What is the weather?" },
- {
- role: "assistant",
- content: null,
- tool_calls: [
- {
- id: "call_1",
- type: "function",
- function: { name: "lookup", arguments: '{"query":"weather"}' },
- },
- ],
- },
- { role: "tool", tool_call_id: "call_1", content: '{"forecast":"sunny"}' },
- ],
- tools: [
- {
- type: "function",
- function: {
- name: "lookup",
- description: "Lookup data",
- parameters: { type: "object", properties: { query: { type: "string" } }, required: ["query"] },
- },
- },
- ],
- tool_choice: { type: "function", function: { name: "lookup" } },
- stream: true,
- stream_options: { include_usage: true },
- })
- }),
- )
- it.effect("posts to the configured compatible endpoint and parses text usage", () =>
- Effect.gen(function* () {
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- dynamicResponse((input) =>
- Effect.gen(function* () {
- const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
- expect(web.url).toBe("https://api.deepseek.test/v1/chat/completions?api-version=2026-01-01")
- expect(web.headers.get("authorization")).toBe("Bearer test-key")
- expect(decodeJson(input.text)).toMatchObject({
- model: "deepseek-chat",
- stream: true,
- messages: [
- { role: "system", content: "You are concise." },
- { role: "user", content: "Say hello." },
- ],
- })
- return input.respond(
- sseEvents(
- deltaChunk({ role: "assistant", content: "Hello" }),
- deltaChunk({ content: "!" }),
- deltaChunk({}, "stop"),
- usageChunk({ prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 }),
- ),
- { headers: { "content-type": "text/event-stream" } },
- )
- }),
- ),
- ),
- )
- expect(response.text).toBe("Hello!")
- expect(response.usage).toMatchObject({ inputTokens: 5, outputTokens: 2, totalTokens: 7 })
- expect(response.events.at(-1)).toMatchObject({
- type: "finish",
- reason: { normalized: "stop", raw: "stop" },
- })
- }),
- )
- it.effect("accepts nullable usage and preserves provider fields", () =>
- Effect.gen(function* () {
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- deltaChunk({ content: "Hello" }),
- deltaChunk({}, "stop"),
- usageChunk({
- prompt_tokens: null,
- completion_tokens: null,
- total_tokens: null,
- prompt_tokens_details: { cached_tokens: null, vendor_cache_tokens: 3 },
- completion_tokens_details: {
- reasoning_tokens: null,
- accepted_prediction_tokens: null,
- rejected_prediction_tokens: null,
- },
- cost: "0.001",
- }),
- ),
- ),
- ),
- )
- expect(response.usage).toMatchObject({
- inputTokens: undefined,
- outputTokens: undefined,
- totalTokens: undefined,
- providerMetadata: {
- openai: {
- prompt_tokens: null,
- completion_tokens: null,
- total_tokens: null,
- prompt_tokens_details: { cached_tokens: null, vendor_cache_tokens: 3 },
- cost: "0.001",
- },
- },
- })
- }),
- )
- it.effect("assembles indexless parallel tool calls across sparse chunks", () =>
- Effect.gen(function* () {
- const response = yield* LLMClient.generate(
- LLMRequest.update(request, {
- tools: [
- ToolDefinition.make({ name: "weather", description: "Get weather", inputSchema: { type: "object" } }),
- ],
- }),
- ).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- deltaChunk({
- tool_calls: [
- { id: "call_paris", function: { name: "weather", arguments: '{"city":"' } },
- { index: null, id: "call_london", function: { name: "weather", arguments: '{"city":"' } },
- ],
- }),
- deltaChunk({ tool_calls: [{ function: { arguments: 'London"}' } }] }),
- deltaChunk({ tool_calls: [{ id: "call_paris", function: { arguments: 'Paris"}' } }] }),
- deltaChunk({}, "tool_calls"),
- ),
- ),
- ),
- )
- expect(response.toolCalls).toMatchObject([
- { id: "call_paris", name: "weather", input: { city: "Paris" } },
- { id: "call_london", name: "weather", input: { city: "London" } },
- ])
- }),
- )
- it.effect("treats an empty finish reason as terminal", () =>
- Effect.gen(function* () {
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(fixedResponse(sseEvents(deltaChunk({ content: "Hello" }), deltaChunk({}, "")))),
- )
- expect(response.finishReason).toEqual({ normalized: "unknown", raw: "" })
- }),
- )
- it.effect("rejects content after a terminal chunk", () =>
- Effect.gen(function* () {
- const error = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- deltaChunk({ content: "Hello" }),
- deltaChunk({}, "stop"),
- deltaChunk({ tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: "{}" } }] }),
- ),
- ),
- ),
- Effect.flip,
- )
- expect(error.message).toContain("OpenAI Chat received content after the finish reason")
- }),
- )
- })
|