@speeq/llm-openai-compatible 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/dist/index.cjs +165 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +47 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.js +144 -0
- package/dist/index.js.map +1 -0
- package/package.json +57 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 speeq contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,41 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @speeq/llm-openai-compatible
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An `LLMProvider` for [speeq](../../../README.md) that talks to any OpenAI-compatible
|
|
4
|
+
`/chat/completions` endpoint with streaming and tool calling. It uses plain `fetch`, with no SDK.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pnpm add @speeq/llm-openai-compatible@next
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Configure a server endpoint
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { createOpenAICompatibleProvider } from "@speeq/llm-openai-compatible";
|
|
14
|
+
|
|
15
|
+
export const llm = createOpenAICompatibleProvider({
|
|
16
|
+
baseURL: process.env.GROQ_BASE_URL!,
|
|
17
|
+
apiKey: process.env.GROQ_API_KEY,
|
|
18
|
+
model: process.env.GROQ_MODEL!,
|
|
19
|
+
});
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Options
|
|
23
|
+
|
|
24
|
+
| Option | Default | Meaning |
|
|
25
|
+
| ------------------ | ------------------- | ----------------------------------------------------------------------------------- |
|
|
26
|
+
| `baseURL`, `model` | required | Endpoint and model id |
|
|
27
|
+
| `apiKey` | none | Sent as a bearer token |
|
|
28
|
+
| `headers` | none | Extra headers |
|
|
29
|
+
| `temperature` | provider default | Sampling temperature |
|
|
30
|
+
| `maxOutputTokens` | `1024` | Sent as `max_completion_tokens` |
|
|
31
|
+
| `includeUsage` | `true` | Request token usage in the stream; set `false` if a server rejects `stream_options` |
|
|
32
|
+
| `kind` | `openai-compatible` | Name reported in anonymous telemetry |
|
|
33
|
+
| `fetch` | global `fetch` | For tests and proxies |
|
|
34
|
+
|
|
35
|
+
## Errors
|
|
36
|
+
|
|
37
|
+
HTTP 429, or a body that mentions rate limits or quota, becomes `RATE_LIMITED` with a retry hint
|
|
38
|
+
taken from `Retry-After`. 401/403 becomes `NOT_CONFIGURED`. Everything else becomes
|
|
39
|
+
`PROVIDER_ERROR`. The provider's raw message is kept only in `error.details` for your server logs.
|
|
40
|
+
|
|
41
|
+
[Related guide or reference](../../../docs/guides/llm-providers.md)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
createOpenAICompatibleProvider: () => createOpenAICompatibleProvider,
|
|
24
|
+
parseArguments: () => parseArguments,
|
|
25
|
+
toOpenAIMessages: () => toOpenAIMessages
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(src_exports);
|
|
28
|
+
var import_core = require("@speeq/core");
|
|
29
|
+
function toOpenAIMessages(messages) {
|
|
30
|
+
return messages.map((m) => {
|
|
31
|
+
switch (m.role) {
|
|
32
|
+
case "assistant":
|
|
33
|
+
if (!m.toolCalls?.length) return { role: "assistant", content: m.content };
|
|
34
|
+
return {
|
|
35
|
+
role: "assistant",
|
|
36
|
+
content: m.content || null,
|
|
37
|
+
tool_calls: m.toolCalls.map((c) => ({
|
|
38
|
+
id: c.id,
|
|
39
|
+
type: "function",
|
|
40
|
+
function: { name: c.name, arguments: JSON.stringify(c.arguments ?? {}) }
|
|
41
|
+
}))
|
|
42
|
+
};
|
|
43
|
+
case "tool":
|
|
44
|
+
return { role: "tool", tool_call_id: m.toolCallId, content: m.content };
|
|
45
|
+
default:
|
|
46
|
+
return { role: m.role, content: m.content };
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function mapFinish(reason) {
|
|
51
|
+
switch (reason) {
|
|
52
|
+
case "stop":
|
|
53
|
+
return "stop";
|
|
54
|
+
case "tool_calls":
|
|
55
|
+
case "function_call":
|
|
56
|
+
return "tool_calls";
|
|
57
|
+
case "length":
|
|
58
|
+
return "length";
|
|
59
|
+
case "content_filter":
|
|
60
|
+
return "content_filter";
|
|
61
|
+
default:
|
|
62
|
+
return "other";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function toUsage(raw) {
|
|
66
|
+
if (!raw) return void 0;
|
|
67
|
+
const u = {};
|
|
68
|
+
if (raw.prompt_tokens !== void 0) u.inputTokens = raw.prompt_tokens;
|
|
69
|
+
if (raw.completion_tokens !== void 0) u.outputTokens = raw.completion_tokens;
|
|
70
|
+
if (raw.total_tokens !== void 0) u.totalTokens = raw.total_tokens;
|
|
71
|
+
return u;
|
|
72
|
+
}
|
|
73
|
+
function parseArguments(raw) {
|
|
74
|
+
if (!raw.trim()) return {};
|
|
75
|
+
const parsed = (0, import_core.safeJsonParse)(raw);
|
|
76
|
+
return parsed.ok ? parsed.value : { __invalidJson: raw };
|
|
77
|
+
}
|
|
78
|
+
function createOpenAICompatibleProvider(options) {
|
|
79
|
+
const kind = options.kind ?? "openai-compatible";
|
|
80
|
+
const url = `${options.baseURL.replace(/\/+$/, "")}/chat/completions`;
|
|
81
|
+
const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
82
|
+
return {
|
|
83
|
+
kind,
|
|
84
|
+
model: options.model,
|
|
85
|
+
async *stream(request) {
|
|
86
|
+
const body = {
|
|
87
|
+
model: options.model,
|
|
88
|
+
messages: toOpenAIMessages(request.messages),
|
|
89
|
+
stream: true,
|
|
90
|
+
max_completion_tokens: request.maxOutputTokens ?? options.maxOutputTokens ?? 1024
|
|
91
|
+
};
|
|
92
|
+
const temperature = request.temperature ?? options.temperature;
|
|
93
|
+
if (temperature !== void 0) body.temperature = temperature;
|
|
94
|
+
if (options.includeUsage !== false) body.stream_options = { include_usage: true };
|
|
95
|
+
if (request.tools.length > 0) {
|
|
96
|
+
body.tools = request.tools.map((t) => ({
|
|
97
|
+
type: "function",
|
|
98
|
+
function: { name: t.name, description: t.description, parameters: t.parameters }
|
|
99
|
+
}));
|
|
100
|
+
body.tool_choice = "auto";
|
|
101
|
+
}
|
|
102
|
+
const headers = {
|
|
103
|
+
"content-type": "application/json",
|
|
104
|
+
...options.headers
|
|
105
|
+
};
|
|
106
|
+
if (options.apiKey) headers.authorization = `Bearer ${options.apiKey}`;
|
|
107
|
+
const init = { method: "POST", headers, body: JSON.stringify(body) };
|
|
108
|
+
if (request.signal) init.signal = request.signal;
|
|
109
|
+
const res = await (0, import_core.providerFetch)(kind, fetchImpl, url, init);
|
|
110
|
+
if (!res.ok || !res.body) {
|
|
111
|
+
throw (0, import_core.mapProviderHttpError)(
|
|
112
|
+
kind,
|
|
113
|
+
res.status,
|
|
114
|
+
await res.text().catch(() => ""),
|
|
115
|
+
res.headers.get("retry-after")
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
const pending = /* @__PURE__ */ new Map();
|
|
119
|
+
let finish = null;
|
|
120
|
+
let usage;
|
|
121
|
+
for await (const data of (0, import_core.readSseData)(res.body, request.signal)) {
|
|
122
|
+
const parsed = (0, import_core.safeJsonParse)(data);
|
|
123
|
+
if (!parsed.ok) continue;
|
|
124
|
+
const chunk = parsed.value;
|
|
125
|
+
if (chunk.error) throw (0, import_core.mapProviderHttpError)(kind, 500, JSON.stringify(chunk.error));
|
|
126
|
+
usage = toUsage(chunk.usage ?? chunk.x_groq?.usage) ?? usage;
|
|
127
|
+
for (const choice of chunk.choices ?? []) {
|
|
128
|
+
const content = choice.delta?.content;
|
|
129
|
+
if (content) yield { type: "text-delta", text: content };
|
|
130
|
+
for (const d of choice.delta?.tool_calls ?? []) {
|
|
131
|
+
const index = d.index ?? pending.size;
|
|
132
|
+
const entry = pending.get(index) ?? { id: "", name: "", args: "" };
|
|
133
|
+
if (d.id) entry.id = d.id;
|
|
134
|
+
if (d.function?.name) entry.name += d.function.name;
|
|
135
|
+
if (d.function?.arguments) entry.args += d.function.arguments;
|
|
136
|
+
pending.set(index, entry);
|
|
137
|
+
}
|
|
138
|
+
if (choice.finish_reason) finish = mapFinish(choice.finish_reason);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const calls = [...pending.entries()].sort(([a], [b]) => a - b).map(([, v]) => v);
|
|
142
|
+
for (const [i, c] of calls.entries()) {
|
|
143
|
+
if (!c.name)
|
|
144
|
+
throw new import_core.SpeeqError("PROVIDER_ERROR", {
|
|
145
|
+
message: "The model sent an incomplete tool call."
|
|
146
|
+
});
|
|
147
|
+
const call = {
|
|
148
|
+
id: c.id || `call_${i}`,
|
|
149
|
+
name: c.name,
|
|
150
|
+
arguments: parseArguments(c.args)
|
|
151
|
+
};
|
|
152
|
+
yield { type: "tool-call", call };
|
|
153
|
+
}
|
|
154
|
+
const reason = calls.length > 0 ? "tool_calls" : finish ?? "stop";
|
|
155
|
+
yield usage ? { type: "finish", reason, usage } : { type: "finish", reason };
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
160
|
+
0 && (module.exports = {
|
|
161
|
+
createOpenAICompatibleProvider,
|
|
162
|
+
parseArguments,
|
|
163
|
+
toOpenAIMessages
|
|
164
|
+
});
|
|
165
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@speeq/llm-openai-compatible`: an {@link LLMProvider} for any OpenAI-compatible\n * `/chat/completions` endpoint (Groq, OpenRouter, Ollama, OpenAI, …), using plain `fetch`.\n * @packageDocumentation\n */\nimport {\n type LLMFinishReason,\n type LLMMessage,\n type LLMProvider,\n type LLMRequest,\n type LLMStreamChunk,\n type LLMToolCall,\n mapProviderHttpError,\n providerFetch,\n readSseData,\n SpeeqError,\n safeJsonParse,\n type Usage,\n} from \"@speeq/core\";\n\n/** Options for {@link createOpenAICompatibleProvider}. */\nexport interface OpenAICompatibleOptions {\n /** API base URL, e.g. `https://api.groq.com/openai/v1`. */\n baseURL: string;\n /** Sent as `Authorization: Bearer …`. Optional for local servers such as Ollama. */\n apiKey?: string;\n /** Model id. Read it from an env var: free-tier model ids change often. */\n model: string;\n /** Extra headers (e.g. OpenRouter's `HTTP-Referer`). */\n headers?: Record<string, string>;\n /** Default sampling temperature. */\n temperature?: number;\n /** Maximum output tokens per call (`max_completion_tokens`). Default 1024. */\n maxOutputTokens?: number;\n /** Ask for token usage in the stream (`stream_options.include_usage`). Default `true`. */\n includeUsage?: boolean;\n /** Telemetry kind. Default `openai-compatible`. */\n kind?: string;\n /** Custom fetch (tests, proxies). */\n fetch?: typeof fetch;\n}\n\ninterface ToolCallDelta {\n index?: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n}\n\ninterface ChunkBody {\n choices?: Array<{\n delta?: { content?: string | null; tool_calls?: ToolCallDelta[] };\n finish_reason?: string | null;\n }>;\n usage?: RawUsage | null;\n x_groq?: { usage?: RawUsage };\n error?: { message?: string; code?: string | number; type?: string };\n}\n\ninterface RawUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n}\n\n/** Converts normalized messages to the OpenAI wire format. */\nexport function toOpenAIMessages(messages: LLMMessage[]): unknown[] {\n return messages.map((m) => {\n switch (m.role) {\n case \"assistant\":\n if (!m.toolCalls?.length) return { role: \"assistant\", content: m.content };\n return {\n role: \"assistant\",\n content: m.content || null,\n tool_calls: m.toolCalls.map((c) => ({\n id: c.id,\n type: \"function\",\n function: { name: c.name, arguments: JSON.stringify(c.arguments ?? {}) },\n })),\n };\n case \"tool\":\n return { role: \"tool\", tool_call_id: m.toolCallId, content: m.content };\n default:\n return { role: m.role, content: m.content };\n }\n });\n}\n\nfunction mapFinish(reason: string | null | undefined): LLMFinishReason {\n switch (reason) {\n case \"stop\":\n return \"stop\";\n case \"tool_calls\":\n case \"function_call\":\n return \"tool_calls\";\n case \"length\":\n return \"length\";\n case \"content_filter\":\n return \"content_filter\";\n default:\n return \"other\";\n }\n}\n\nfunction toUsage(raw: RawUsage | null | undefined): Usage | undefined {\n if (!raw) return undefined;\n const u: Usage = {};\n if (raw.prompt_tokens !== undefined) u.inputTokens = raw.prompt_tokens;\n if (raw.completion_tokens !== undefined) u.outputTokens = raw.completion_tokens;\n if (raw.total_tokens !== undefined) u.totalTokens = raw.total_tokens;\n return u;\n}\n\n/** Parses streamed tool-call arguments. Empty means `{}`; invalid JSON is kept for the model to see. */\nexport function parseArguments(raw: string): unknown {\n if (!raw.trim()) return {};\n const parsed = safeJsonParse(raw);\n return parsed.ok ? parsed.value : { __invalidJson: raw };\n}\n\n/**\n * Creates a provider for an OpenAI-compatible endpoint.\n *\n * @example\n * createOpenAICompatibleProvider({\n * baseURL: \"https://api.groq.com/openai/v1\",\n * apiKey: process.env.GROQ_API_KEY,\n * model: process.env.GROQ_MODEL ?? \"llama-3.3-70b-versatile\",\n * });\n */\nexport function createOpenAICompatibleProvider(options: OpenAICompatibleOptions): LLMProvider {\n const kind = options.kind ?? \"openai-compatible\";\n const url = `${options.baseURL.replace(/\\/+$/, \"\")}/chat/completions`;\n const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n\n return {\n kind,\n model: options.model,\n async *stream(request: LLMRequest): AsyncIterable<LLMStreamChunk> {\n const body: Record<string, unknown> = {\n model: options.model,\n messages: toOpenAIMessages(request.messages),\n stream: true,\n max_completion_tokens: request.maxOutputTokens ?? options.maxOutputTokens ?? 1024,\n };\n const temperature = request.temperature ?? options.temperature;\n if (temperature !== undefined) body.temperature = temperature;\n if (options.includeUsage !== false) body.stream_options = { include_usage: true };\n if (request.tools.length > 0) {\n body.tools = request.tools.map((t) => ({\n type: \"function\",\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n body.tool_choice = \"auto\";\n }\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...options.headers,\n };\n if (options.apiKey) headers.authorization = `Bearer ${options.apiKey}`;\n\n const init: RequestInit = { method: \"POST\", headers, body: JSON.stringify(body) };\n if (request.signal) init.signal = request.signal;\n const res = await providerFetch(kind, fetchImpl, url, init);\n if (!res.ok || !res.body) {\n throw mapProviderHttpError(\n kind,\n res.status,\n await res.text().catch(() => \"\"),\n res.headers.get(\"retry-after\"),\n );\n }\n\n const pending = new Map<number, { id: string; name: string; args: string }>();\n let finish: LLMFinishReason | null = null;\n let usage: Usage | undefined;\n for await (const data of readSseData(res.body, request.signal)) {\n const parsed = safeJsonParse<ChunkBody>(data);\n if (!parsed.ok) continue;\n const chunk = parsed.value;\n if (chunk.error) throw mapProviderHttpError(kind, 500, JSON.stringify(chunk.error));\n usage = toUsage(chunk.usage ?? chunk.x_groq?.usage) ?? usage;\n for (const choice of chunk.choices ?? []) {\n const content = choice.delta?.content;\n if (content) yield { type: \"text-delta\", text: content };\n for (const d of choice.delta?.tool_calls ?? []) {\n const index = d.index ?? pending.size;\n const entry = pending.get(index) ?? { id: \"\", name: \"\", args: \"\" };\n if (d.id) entry.id = d.id;\n if (d.function?.name) entry.name += d.function.name;\n if (d.function?.arguments) entry.args += d.function.arguments;\n pending.set(index, entry);\n }\n if (choice.finish_reason) finish = mapFinish(choice.finish_reason);\n }\n }\n\n const calls = [...pending.entries()].sort(([a], [b]) => a - b).map(([, v]) => v);\n for (const [i, c] of calls.entries()) {\n if (!c.name)\n throw new SpeeqError(\"PROVIDER_ERROR\", {\n message: \"The model sent an incomplete tool call.\",\n });\n const call: LLMToolCall = {\n id: c.id || `call_${i}`,\n name: c.name,\n arguments: parseArguments(c.args),\n };\n yield { type: \"tool-call\", call };\n }\n const reason = calls.length > 0 ? \"tool_calls\" : (finish ?? \"stop\");\n yield usage ? { type: \"finish\", reason, usage } : { type: \"finish\", reason };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,kBAaO;AA+CA,SAAS,iBAAiB,UAAmC;AAClE,SAAO,SAAS,IAAI,CAAC,MAAM;AACzB,YAAQ,EAAE,MAAM;AAAA,MACd,KAAK;AACH,YAAI,CAAC,EAAE,WAAW,OAAQ,QAAO,EAAE,MAAM,aAAa,SAAS,EAAE,QAAQ;AACzE,eAAO;AAAA,UACL,MAAM;AAAA,UACN,SAAS,EAAE,WAAW;AAAA,UACtB,YAAY,EAAE,UAAU,IAAI,CAAC,OAAO;AAAA,YAClC,IAAI,EAAE;AAAA,YACN,MAAM;AAAA,YACN,UAAU,EAAE,MAAM,EAAE,MAAM,WAAW,KAAK,UAAU,EAAE,aAAa,CAAC,CAAC,EAAE;AAAA,UACzE,EAAE;AAAA,QACJ;AAAA,MACF,KAAK;AACH,eAAO,EAAE,MAAM,QAAQ,cAAc,EAAE,YAAY,SAAS,EAAE,QAAQ;AAAA,MACxE;AACE,eAAO,EAAE,MAAM,EAAE,MAAM,SAAS,EAAE,QAAQ;AAAA,IAC9C;AAAA,EACF,CAAC;AACH;AAEA,SAAS,UAAU,QAAoD;AACrE,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAEA,SAA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KAAM,OAAM,QAAQ,EAAE,SAAS;AAC/C,gBAAI,EAAE,UAAU,UAAW,OAAM,QAAQ,EAAE,SAAS;AACpD,oBAAQ,IAAI,OAAO,KAAK;AAAA,UAC1B;AACA,cAAI,OAAO,cAAe,UAAS,UAAU,OAAO,aAAa;AAAA,QACnE;AAAA,MACF;AAEA,YAAM,QAAQ,CAAC,GAAG,QAAQ,QAAQ,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC;AAC/E,iBAAW,CAAC,GAAG,CAAC,KAAK,MAAM,QAAQ,GAAG;AACpC,YAAI,CAAC,EAAE;AACL,gBAAM,IAAI,uBAAW,kBAAkB;AAAA,YACrC,SAAS;AAAA,UACX,CAAC;AACH,cAAM,OAAoB;AAAA,UACxB,IAAI,EAAE,MAAM,QAAQ,CAAC;AAAA,UACrB,MAAM,EAAE;AAAA,UACR,WAAW,eAAe,EAAE,IAAI;AAAA,QAClC;AACA,cAAM,EAAE,MAAM,aAAa,KAAK;AAAA,MAClC;AACA,YAAM,SAAS,MAAM,SAAS,IAAI,eAAgB,UAAU;AAC5D,YAAM,QAAQ,EAAE,MAAM,UAAU,QAAQ,MAAM,IAAI,EAAE,MAAM,UAAU,OAAO;AAAA,IAC7E;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { LLMProvider, LLMMessage } from '@speeq/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `@speeq/llm-openai-compatible`: an {@link LLMProvider} for any OpenAI-compatible
|
|
5
|
+
* `/chat/completions` endpoint (Groq, OpenRouter, Ollama, OpenAI, …), using plain `fetch`.
|
|
6
|
+
* @packageDocumentation
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Options for {@link createOpenAICompatibleProvider}. */
|
|
10
|
+
interface OpenAICompatibleOptions {
|
|
11
|
+
/** API base URL, e.g. `https://api.groq.com/openai/v1`. */
|
|
12
|
+
baseURL: string;
|
|
13
|
+
/** Sent as `Authorization: Bearer …`. Optional for local servers such as Ollama. */
|
|
14
|
+
apiKey?: string;
|
|
15
|
+
/** Model id. Read it from an env var: free-tier model ids change often. */
|
|
16
|
+
model: string;
|
|
17
|
+
/** Extra headers (e.g. OpenRouter's `HTTP-Referer`). */
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
/** Default sampling temperature. */
|
|
20
|
+
temperature?: number;
|
|
21
|
+
/** Maximum output tokens per call (`max_completion_tokens`). Default 1024. */
|
|
22
|
+
maxOutputTokens?: number;
|
|
23
|
+
/** Ask for token usage in the stream (`stream_options.include_usage`). Default `true`. */
|
|
24
|
+
includeUsage?: boolean;
|
|
25
|
+
/** Telemetry kind. Default `openai-compatible`. */
|
|
26
|
+
kind?: string;
|
|
27
|
+
/** Custom fetch (tests, proxies). */
|
|
28
|
+
fetch?: typeof fetch;
|
|
29
|
+
}
|
|
30
|
+
/** Converts normalized messages to the OpenAI wire format. */
|
|
31
|
+
declare function toOpenAIMessages(messages: LLMMessage[]): unknown[];
|
|
32
|
+
/** Parses streamed tool-call arguments. Empty means `{}`; invalid JSON is kept for the model to see. */
|
|
33
|
+
declare function parseArguments(raw: string): unknown;
|
|
34
|
+
/**
|
|
35
|
+
* Creates a provider for an OpenAI-compatible endpoint.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* createOpenAICompatibleProvider({
|
|
39
|
+
* baseURL: "https://api.groq.com/openai/v1",
|
|
40
|
+
* apiKey: process.env.GROQ_API_KEY,
|
|
41
|
+
* model: process.env.GROQ_MODEL ?? "llama-3.3-70b-versatile",
|
|
42
|
+
* });
|
|
43
|
+
*/
|
|
44
|
+
declare function createOpenAICompatibleProvider(options: OpenAICompatibleOptions): LLMProvider;
|
|
45
|
+
|
|
46
|
+
export { createOpenAICompatibleProvider, parseArguments, toOpenAIMessages };
|
|
47
|
+
export type { OpenAICompatibleOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { LLMProvider, LLMMessage } from '@speeq/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `@speeq/llm-openai-compatible`: an {@link LLMProvider} for any OpenAI-compatible
|
|
5
|
+
* `/chat/completions` endpoint (Groq, OpenRouter, Ollama, OpenAI, …), using plain `fetch`.
|
|
6
|
+
* @packageDocumentation
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Options for {@link createOpenAICompatibleProvider}. */
|
|
10
|
+
interface OpenAICompatibleOptions {
|
|
11
|
+
/** API base URL, e.g. `https://api.groq.com/openai/v1`. */
|
|
12
|
+
baseURL: string;
|
|
13
|
+
/** Sent as `Authorization: Bearer …`. Optional for local servers such as Ollama. */
|
|
14
|
+
apiKey?: string;
|
|
15
|
+
/** Model id. Read it from an env var: free-tier model ids change often. */
|
|
16
|
+
model: string;
|
|
17
|
+
/** Extra headers (e.g. OpenRouter's `HTTP-Referer`). */
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
/** Default sampling temperature. */
|
|
20
|
+
temperature?: number;
|
|
21
|
+
/** Maximum output tokens per call (`max_completion_tokens`). Default 1024. */
|
|
22
|
+
maxOutputTokens?: number;
|
|
23
|
+
/** Ask for token usage in the stream (`stream_options.include_usage`). Default `true`. */
|
|
24
|
+
includeUsage?: boolean;
|
|
25
|
+
/** Telemetry kind. Default `openai-compatible`. */
|
|
26
|
+
kind?: string;
|
|
27
|
+
/** Custom fetch (tests, proxies). */
|
|
28
|
+
fetch?: typeof fetch;
|
|
29
|
+
}
|
|
30
|
+
/** Converts normalized messages to the OpenAI wire format. */
|
|
31
|
+
declare function toOpenAIMessages(messages: LLMMessage[]): unknown[];
|
|
32
|
+
/** Parses streamed tool-call arguments. Empty means `{}`; invalid JSON is kept for the model to see. */
|
|
33
|
+
declare function parseArguments(raw: string): unknown;
|
|
34
|
+
/**
|
|
35
|
+
* Creates a provider for an OpenAI-compatible endpoint.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* createOpenAICompatibleProvider({
|
|
39
|
+
* baseURL: "https://api.groq.com/openai/v1",
|
|
40
|
+
* apiKey: process.env.GROQ_API_KEY,
|
|
41
|
+
* model: process.env.GROQ_MODEL ?? "llama-3.3-70b-versatile",
|
|
42
|
+
* });
|
|
43
|
+
*/
|
|
44
|
+
declare function createOpenAICompatibleProvider(options: OpenAICompatibleOptions): LLMProvider;
|
|
45
|
+
|
|
46
|
+
export { createOpenAICompatibleProvider, parseArguments, toOpenAIMessages };
|
|
47
|
+
export type { OpenAICompatibleOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
mapProviderHttpError,
|
|
4
|
+
providerFetch,
|
|
5
|
+
readSseData,
|
|
6
|
+
SpeeqError,
|
|
7
|
+
safeJsonParse
|
|
8
|
+
} from "@speeq/core";
|
|
9
|
+
function toOpenAIMessages(messages) {
|
|
10
|
+
return messages.map((m) => {
|
|
11
|
+
switch (m.role) {
|
|
12
|
+
case "assistant":
|
|
13
|
+
if (!m.toolCalls?.length) return { role: "assistant", content: m.content };
|
|
14
|
+
return {
|
|
15
|
+
role: "assistant",
|
|
16
|
+
content: m.content || null,
|
|
17
|
+
tool_calls: m.toolCalls.map((c) => ({
|
|
18
|
+
id: c.id,
|
|
19
|
+
type: "function",
|
|
20
|
+
function: { name: c.name, arguments: JSON.stringify(c.arguments ?? {}) }
|
|
21
|
+
}))
|
|
22
|
+
};
|
|
23
|
+
case "tool":
|
|
24
|
+
return { role: "tool", tool_call_id: m.toolCallId, content: m.content };
|
|
25
|
+
default:
|
|
26
|
+
return { role: m.role, content: m.content };
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function mapFinish(reason) {
|
|
31
|
+
switch (reason) {
|
|
32
|
+
case "stop":
|
|
33
|
+
return "stop";
|
|
34
|
+
case "tool_calls":
|
|
35
|
+
case "function_call":
|
|
36
|
+
return "tool_calls";
|
|
37
|
+
case "length":
|
|
38
|
+
return "length";
|
|
39
|
+
case "content_filter":
|
|
40
|
+
return "content_filter";
|
|
41
|
+
default:
|
|
42
|
+
return "other";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function toUsage(raw) {
|
|
46
|
+
if (!raw) return void 0;
|
|
47
|
+
const u = {};
|
|
48
|
+
if (raw.prompt_tokens !== void 0) u.inputTokens = raw.prompt_tokens;
|
|
49
|
+
if (raw.completion_tokens !== void 0) u.outputTokens = raw.completion_tokens;
|
|
50
|
+
if (raw.total_tokens !== void 0) u.totalTokens = raw.total_tokens;
|
|
51
|
+
return u;
|
|
52
|
+
}
|
|
53
|
+
function parseArguments(raw) {
|
|
54
|
+
if (!raw.trim()) return {};
|
|
55
|
+
const parsed = safeJsonParse(raw);
|
|
56
|
+
return parsed.ok ? parsed.value : { __invalidJson: raw };
|
|
57
|
+
}
|
|
58
|
+
function createOpenAICompatibleProvider(options) {
|
|
59
|
+
const kind = options.kind ?? "openai-compatible";
|
|
60
|
+
const url = `${options.baseURL.replace(/\/+$/, "")}/chat/completions`;
|
|
61
|
+
const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
62
|
+
return {
|
|
63
|
+
kind,
|
|
64
|
+
model: options.model,
|
|
65
|
+
async *stream(request) {
|
|
66
|
+
const body = {
|
|
67
|
+
model: options.model,
|
|
68
|
+
messages: toOpenAIMessages(request.messages),
|
|
69
|
+
stream: true,
|
|
70
|
+
max_completion_tokens: request.maxOutputTokens ?? options.maxOutputTokens ?? 1024
|
|
71
|
+
};
|
|
72
|
+
const temperature = request.temperature ?? options.temperature;
|
|
73
|
+
if (temperature !== void 0) body.temperature = temperature;
|
|
74
|
+
if (options.includeUsage !== false) body.stream_options = { include_usage: true };
|
|
75
|
+
if (request.tools.length > 0) {
|
|
76
|
+
body.tools = request.tools.map((t) => ({
|
|
77
|
+
type: "function",
|
|
78
|
+
function: { name: t.name, description: t.description, parameters: t.parameters }
|
|
79
|
+
}));
|
|
80
|
+
body.tool_choice = "auto";
|
|
81
|
+
}
|
|
82
|
+
const headers = {
|
|
83
|
+
"content-type": "application/json",
|
|
84
|
+
...options.headers
|
|
85
|
+
};
|
|
86
|
+
if (options.apiKey) headers.authorization = `Bearer ${options.apiKey}`;
|
|
87
|
+
const init = { method: "POST", headers, body: JSON.stringify(body) };
|
|
88
|
+
if (request.signal) init.signal = request.signal;
|
|
89
|
+
const res = await providerFetch(kind, fetchImpl, url, init);
|
|
90
|
+
if (!res.ok || !res.body) {
|
|
91
|
+
throw mapProviderHttpError(
|
|
92
|
+
kind,
|
|
93
|
+
res.status,
|
|
94
|
+
await res.text().catch(() => ""),
|
|
95
|
+
res.headers.get("retry-after")
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
const pending = /* @__PURE__ */ new Map();
|
|
99
|
+
let finish = null;
|
|
100
|
+
let usage;
|
|
101
|
+
for await (const data of readSseData(res.body, request.signal)) {
|
|
102
|
+
const parsed = safeJsonParse(data);
|
|
103
|
+
if (!parsed.ok) continue;
|
|
104
|
+
const chunk = parsed.value;
|
|
105
|
+
if (chunk.error) throw mapProviderHttpError(kind, 500, JSON.stringify(chunk.error));
|
|
106
|
+
usage = toUsage(chunk.usage ?? chunk.x_groq?.usage) ?? usage;
|
|
107
|
+
for (const choice of chunk.choices ?? []) {
|
|
108
|
+
const content = choice.delta?.content;
|
|
109
|
+
if (content) yield { type: "text-delta", text: content };
|
|
110
|
+
for (const d of choice.delta?.tool_calls ?? []) {
|
|
111
|
+
const index = d.index ?? pending.size;
|
|
112
|
+
const entry = pending.get(index) ?? { id: "", name: "", args: "" };
|
|
113
|
+
if (d.id) entry.id = d.id;
|
|
114
|
+
if (d.function?.name) entry.name += d.function.name;
|
|
115
|
+
if (d.function?.arguments) entry.args += d.function.arguments;
|
|
116
|
+
pending.set(index, entry);
|
|
117
|
+
}
|
|
118
|
+
if (choice.finish_reason) finish = mapFinish(choice.finish_reason);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const calls = [...pending.entries()].sort(([a], [b]) => a - b).map(([, v]) => v);
|
|
122
|
+
for (const [i, c] of calls.entries()) {
|
|
123
|
+
if (!c.name)
|
|
124
|
+
throw new SpeeqError("PROVIDER_ERROR", {
|
|
125
|
+
message: "The model sent an incomplete tool call."
|
|
126
|
+
});
|
|
127
|
+
const call = {
|
|
128
|
+
id: c.id || `call_${i}`,
|
|
129
|
+
name: c.name,
|
|
130
|
+
arguments: parseArguments(c.args)
|
|
131
|
+
};
|
|
132
|
+
yield { type: "tool-call", call };
|
|
133
|
+
}
|
|
134
|
+
const reason = calls.length > 0 ? "tool_calls" : finish ?? "stop";
|
|
135
|
+
yield usage ? { type: "finish", reason, usage } : { type: "finish", reason };
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
export {
|
|
140
|
+
createOpenAICompatibleProvider,
|
|
141
|
+
parseArguments,
|
|
142
|
+
toOpenAIMessages
|
|
143
|
+
};
|
|
144
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@speeq/llm-openai-compatible`: an {@link LLMProvider} for any OpenAI-compatible\n * `/chat/completions` endpoint (Groq, OpenRouter, Ollama, OpenAI, …), using plain `fetch`.\n * @packageDocumentation\n */\nimport {\n type LLMFinishReason,\n type LLMMessage,\n type LLMProvider,\n type LLMRequest,\n type LLMStreamChunk,\n type LLMToolCall,\n mapProviderHttpError,\n providerFetch,\n readSseData,\n SpeeqError,\n safeJsonParse,\n type Usage,\n} from \"@speeq/core\";\n\n/** Options for {@link createOpenAICompatibleProvider}. */\nexport interface OpenAICompatibleOptions {\n /** API base URL, e.g. `https://api.groq.com/openai/v1`. */\n baseURL: string;\n /** Sent as `Authorization: Bearer …`. Optional for local servers such as Ollama. */\n apiKey?: string;\n /** Model id. Read it from an env var: free-tier model ids change often. */\n model: string;\n /** Extra headers (e.g. OpenRouter's `HTTP-Referer`). */\n headers?: Record<string, string>;\n /** Default sampling temperature. */\n temperature?: number;\n /** Maximum output tokens per call (`max_completion_tokens`). Default 1024. */\n maxOutputTokens?: number;\n /** Ask for token usage in the stream (`stream_options.include_usage`). Default `true`. */\n includeUsage?: boolean;\n /** Telemetry kind. Default `openai-compatible`. */\n kind?: string;\n /** Custom fetch (tests, proxies). */\n fetch?: typeof fetch;\n}\n\ninterface ToolCallDelta {\n index?: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n}\n\ninterface ChunkBody {\n choices?: Array<{\n delta?: { content?: string | null; tool_calls?: ToolCallDelta[] };\n finish_reason?: string | null;\n }>;\n usage?: RawUsage | null;\n x_groq?: { usage?: RawUsage };\n error?: { message?: string; code?: string | number; type?: string };\n}\n\ninterface RawUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n}\n\n/** Converts normalized messages to the OpenAI wire format. */\nexport function toOpenAIMessages(messages: LLMMessage[]): unknown[] {\n return messages.map((m) => {\n switch (m.role) {\n case \"assistant\":\n if (!m.toolCalls?.length) return { role: \"assistant\", content: m.content };\n return {\n role: \"assistant\",\n content: m.content || null,\n tool_calls: m.toolCalls.map((c) => ({\n id: c.id,\n type: \"function\",\n function: { name: c.name, arguments: JSON.stringify(c.arguments ?? {}) },\n })),\n };\n case \"tool\":\n return { role: \"tool\", tool_call_id: m.toolCallId, content: m.content };\n default:\n return { role: m.role, content: m.content };\n }\n });\n}\n\nfunction mapFinish(reason: string | null | undefined): LLMFinishReason {\n switch (reason) {\n case \"stop\":\n return \"stop\";\n case \"tool_calls\":\n case \"function_call\":\n return \"tool_calls\";\n case \"length\":\n return \"length\";\n case \"content_filter\":\n return \"content_filter\";\n default:\n return \"other\";\n }\n}\n\nfunction toUsage(raw: RawUsage | null | undefined): Usage | undefined {\n if (!raw) return undefined;\n const u: Usage = {};\n if (raw.prompt_tokens !== undefined) u.inputTokens = raw.prompt_tokens;\n if (raw.completion_tokens !== undefined) u.outputTokens = raw.completion_tokens;\n if (raw.total_tokens !== undefined) u.totalTokens = raw.total_tokens;\n return u;\n}\n\n/** Parses streamed tool-call arguments. Empty means `{}`; invalid JSON is kept for the model to see. */\nexport function parseArguments(raw: string): unknown {\n if (!raw.trim()) return {};\n const parsed = safeJsonParse(raw);\n return parsed.ok ? parsed.value : { __invalidJson: raw };\n}\n\n/**\n * Creates a provider for an OpenAI-compatible endpoint.\n *\n * @example\n * createOpenAICompatibleProvider({\n * baseURL: \"https://api.groq.com/openai/v1\",\n * apiKey: process.env.GROQ_API_KEY,\n * model: process.env.GROQ_MODEL ?? \"llama-3.3-70b-versatile\",\n * });\n */\nexport function createOpenAICompatibleProvider(options: OpenAICompatibleOptions): LLMProvider {\n const kind = options.kind ?? \"openai-compatible\";\n const url = `${options.baseURL.replace(/\\/+$/, \"\")}/chat/completions`;\n const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n\n return {\n kind,\n model: options.model,\n async *stream(request: LLMRequest): AsyncIterable<LLMStreamChunk> {\n const body: Record<string, unknown> = {\n model: options.model,\n messages: toOpenAIMessages(request.messages),\n stream: true,\n max_completion_tokens: request.maxOutputTokens ?? options.maxOutputTokens ?? 1024,\n };\n const temperature = request.temperature ?? options.temperature;\n if (temperature !== undefined) body.temperature = temperature;\n if (options.includeUsage !== false) body.stream_options = { include_usage: true };\n if (request.tools.length > 0) {\n body.tools = request.tools.map((t) => ({\n type: \"function\",\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n body.tool_choice = \"auto\";\n }\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...options.headers,\n };\n if (options.apiKey) headers.authorization = `Bearer ${options.apiKey}`;\n\n const init: RequestInit = { method: \"POST\", headers, body: JSON.stringify(body) };\n if (request.signal) init.signal = request.signal;\n const res = await providerFetch(kind, fetchImpl, url, init);\n if (!res.ok || !res.body) {\n throw mapProviderHttpError(\n kind,\n res.status,\n await res.text().catch(() => \"\"),\n res.headers.get(\"retry-after\"),\n );\n }\n\n const pending = new Map<number, { id: string; name: string; args: string }>();\n let finish: LLMFinishReason | null = null;\n let usage: Usage | undefined;\n for await (const data of readSseData(res.body, request.signal)) {\n const parsed = safeJsonParse<ChunkBody>(data);\n if (!parsed.ok) continue;\n const chunk = parsed.value;\n if (chunk.error) throw mapProviderHttpError(kind, 500, JSON.stringify(chunk.error));\n usage = toUsage(chunk.usage ?? chunk.x_groq?.usage) ?? usage;\n for (const choice of chunk.choices ?? []) {\n const content = choice.delta?.content;\n if (content) yield { type: \"text-delta\", text: content };\n for (const d of choice.delta?.tool_calls ?? []) {\n const index = d.index ?? pending.size;\n const entry = pending.get(index) ?? { id: \"\", name: \"\", args: \"\" };\n if (d.id) entry.id = d.id;\n if (d.function?.name) entry.name += d.function.name;\n if (d.function?.arguments) entry.args += d.function.arguments;\n pending.set(index, entry);\n }\n if (choice.finish_reason) finish = mapFinish(choice.finish_reason);\n }\n }\n\n const calls = [...pending.entries()].sort(([a], [b]) => a - b).map(([, v]) => v);\n for (const [i, c] of calls.entries()) {\n if (!c.name)\n throw new SpeeqError(\"PROVIDER_ERROR\", {\n message: \"The model sent an incomplete tool call.\",\n });\n const call: LLMToolCall = {\n id: c.id || `call_${i}`,\n name: c.name,\n arguments: parseArguments(c.args),\n };\n yield { type: \"tool-call\", call };\n }\n const reason = calls.length > 0 ? \"tool_calls\" : (finish ?? \"stop\");\n yield usage ? { type: \"finish\", reason, usage } : { type: \"finish\", reason };\n },\n };\n}\n"],"mappings":";AAKA;AAAA,EAOE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AA+CA,SAAS,iBAAiB,UAAmC;AAClE,SAAO,SAAS,IAAI,CAAC,MAAM;AACzB,YAAQ,EAAE,MAAM;AAAA,MACd,KAAK;AACH,YAAI,CAAC,EAAE,WAAW,OAAQ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H,cAAM,OAAoB;AAAA,UACxB,IAAI,EAAE,MAAM,QAAQ,CAAC;AAAA,UACrB,MAAM,EAAE;AAAA,UACR,WAAW,eAAe,EAAE,IAAI;AAAA,QAClC;AACA,cAAM,EAAE,MAAM,aAAa,KAAK;AAAA,MAClC;AACA,YAAM,SAAS,MAAM,SAAS,IAAI,eAAgB,UAAU;AAC5D,YAAM,QAAQ,EAAE,MAAM,UAAU,QAAQ,MAAM,IAAI,EAAE,MAAM,UAAU,OAAO;AAAA,IAC7E;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@speeq/llm-openai-compatible",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "OpenAI-compatible chat completions LLMProvider for speeq (Groq, OpenRouter, Ollama, OpenAI) using plain fetch.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/Mudavath-Giri-Naik/speeq.git",
|
|
11
|
+
"directory": "packages/adapters/llm-openai-compatible"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/Mudavath-Giri-Naik/speeq#readme",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"speeq",
|
|
16
|
+
"voice",
|
|
17
|
+
"agent",
|
|
18
|
+
"conversational-ai",
|
|
19
|
+
"headless"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md"
|
|
27
|
+
],
|
|
28
|
+
"main": "./dist/index.cjs",
|
|
29
|
+
"module": "./dist/index.js",
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"@speeq/source": "./src/index.ts",
|
|
34
|
+
"import": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"default": "./dist/index.js"
|
|
37
|
+
},
|
|
38
|
+
"require": {
|
|
39
|
+
"types": "./dist/index.d.cts",
|
|
40
|
+
"default": "./dist/index.cjs"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"./package.json": "./package.json"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@speeq/core": "0.2.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@speeq/tsconfig": "0.0.0",
|
|
53
|
+
"zod": "4.6.7"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"build": "tsup",
|
|
57
|
+
"typecheck": "tsc --noEmit",
|
|
58
|
+
"test": "vitest run"
|
|
59
|
+
}
|
|
6
60
|
}
|