@agentskit/adapters 0.9.1 → 0.11.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/dist/index.js CHANGED
@@ -779,13 +779,47 @@ function vercelAI(config) {
779
779
  var mistral = createOpenAICompatibleAdapter("https://api.mistral.ai/v1");
780
780
 
781
781
  // src/cohere.ts
782
- var cohere = createOpenAICompatibleAdapter("https://api.cohere.com/compatibility/v1");
782
+ var COHERE_BASE_URL = "https://api.cohere.com/compatibility/v1";
783
+ var DEFAULT_MODEL = "command-r-plus";
784
+ var baseFactory = createOpenAICompatibleAdapter(COHERE_BASE_URL);
785
+ function cohere(config) {
786
+ const factory = baseFactory({
787
+ model: DEFAULT_MODEL,
788
+ ...config
789
+ });
790
+ return {
791
+ ...factory,
792
+ capabilities: {
793
+ streaming: true,
794
+ tools: true,
795
+ usage: true
796
+ }
797
+ };
798
+ }
799
+ var cohereAdapter = cohere;
783
800
 
784
801
  // src/together.ts
785
802
  var together = createOpenAICompatibleAdapter("https://api.together.xyz/v1");
786
803
 
787
804
  // src/groq.ts
788
- var groq = createOpenAICompatibleAdapter("https://api.groq.com/openai/v1");
805
+ var GROQ_BASE_URL = "https://api.groq.com/openai/v1";
806
+ var DEFAULT_MODEL2 = "llama-3.3-70b-versatile";
807
+ var baseFactory2 = createOpenAICompatibleAdapter(GROQ_BASE_URL);
808
+ function groq(config) {
809
+ const factory = baseFactory2({
810
+ model: DEFAULT_MODEL2,
811
+ ...config
812
+ });
813
+ return {
814
+ ...factory,
815
+ capabilities: {
816
+ streaming: true,
817
+ tools: true,
818
+ usage: true
819
+ }
820
+ };
821
+ }
822
+ var groqAdapter = groq;
789
823
 
790
824
  // src/fireworks.ts
791
825
  var fireworks = createOpenAICompatibleAdapter("https://api.fireworks.ai/inference/v1");
@@ -805,6 +839,502 @@ var vllm = createOpenAICompatibleAdapter("http://localhost:8000/v1");
805
839
  // src/llamacpp.ts
806
840
  var llamacpp = createOpenAICompatibleAdapter("http://localhost:8080/v1");
807
841
 
842
+ // src/cerebras.ts
843
+ var CEREBRAS_BASE_URL = "https://api.cerebras.ai/v1";
844
+ var DEFAULT_MODEL3 = "llama-3.3-70b";
845
+ var baseFactory3 = createOpenAICompatibleAdapter(CEREBRAS_BASE_URL);
846
+ function cerebras(config) {
847
+ const factory = baseFactory3({
848
+ model: DEFAULT_MODEL3,
849
+ ...config
850
+ });
851
+ return {
852
+ ...factory,
853
+ capabilities: {
854
+ streaming: true,
855
+ tools: true,
856
+ usage: true
857
+ }
858
+ };
859
+ }
860
+ var cerebrasAdapter = cerebras;
861
+
862
+ // src/azure-openai.ts
863
+ var DEFAULT_API_VERSION = "2024-10-21";
864
+ function azureOpenAI(config) {
865
+ const { apiKey, endpoint, deployment, apiVersion = DEFAULT_API_VERSION, retry } = config;
866
+ const includeUsage = config.includeUsage ?? true;
867
+ const url = `${endpoint.replace(/\/$/, "")}/openai/deployments/${encodeURIComponent(deployment)}/chat/completions?api-version=${encodeURIComponent(apiVersion)}`;
868
+ return {
869
+ capabilities: {
870
+ streaming: true,
871
+ tools: true,
872
+ usage: true
873
+ },
874
+ createSource: (request) => {
875
+ const body = {
876
+ messages: toProviderMessages(request.messages),
877
+ tools: request.context?.tools?.map((tool) => ({
878
+ type: "function",
879
+ function: {
880
+ name: tool.name,
881
+ description: tool.description,
882
+ parameters: tool.schema
883
+ }
884
+ })),
885
+ temperature: request.context?.temperature,
886
+ max_tokens: request.context?.maxTokens,
887
+ stream: true
888
+ };
889
+ if (includeUsage) body.stream_options = { include_usage: true };
890
+ return createStreamSource(
891
+ (signal) => fetch(url, {
892
+ method: "POST",
893
+ headers: {
894
+ "Content-Type": "application/json",
895
+ "api-key": apiKey
896
+ },
897
+ body: JSON.stringify(body),
898
+ signal
899
+ }),
900
+ parseOpenAIStream,
901
+ "Azure OpenAI API",
902
+ retry
903
+ );
904
+ }
905
+ };
906
+ }
907
+ var azureOpenAIAdapter = azureOpenAI;
908
+
909
+ // src/replicate.ts
910
+ var DEFAULT_BASE_URL = "https://api.replicate.com";
911
+ function defaultPrompt(request) {
912
+ return request.messages.map((m) => {
913
+ if (m.role === "system") return `[SYSTEM] ${m.content}`;
914
+ if (m.role === "assistant") return `[ASSISTANT] ${m.content}`;
915
+ return `[USER] ${m.content}`;
916
+ }).join("\n\n") + "\n\n[ASSISTANT] ";
917
+ }
918
+ async function* parseReplicateStream(stream) {
919
+ const reader = stream.getReader();
920
+ const decoder = new TextDecoder();
921
+ let buffer = "";
922
+ let currentEvent = "";
923
+ try {
924
+ while (true) {
925
+ const { done, value } = await reader.read();
926
+ if (done) break;
927
+ buffer += decoder.decode(value, { stream: true });
928
+ const lines = buffer.split("\n");
929
+ buffer = lines.pop() ?? "";
930
+ for (const line of lines) {
931
+ if (line.startsWith("event: ")) {
932
+ currentEvent = line.slice(7).trim();
933
+ continue;
934
+ }
935
+ if (!line.startsWith("data: ")) continue;
936
+ const data = line.slice(6);
937
+ if (currentEvent === "output" && data) {
938
+ yield { type: "text", content: data };
939
+ } else if (currentEvent === "done") {
940
+ yield { type: "done" };
941
+ return;
942
+ } else if (currentEvent === "error") {
943
+ yield { type: "error", content: data || "replicate stream error" };
944
+ return;
945
+ }
946
+ }
947
+ }
948
+ } finally {
949
+ reader.releaseLock();
950
+ }
951
+ yield { type: "done" };
952
+ }
953
+ function replicate(config) {
954
+ const { apiKey, model, version, baseUrl = DEFAULT_BASE_URL, toInput = (r) => ({ prompt: defaultPrompt(r) }) } = config;
955
+ const predictionUrl = version ? `${baseUrl}/v1/predictions` : `${baseUrl}/v1/models/${model}/predictions`;
956
+ return {
957
+ capabilities: {
958
+ streaming: true,
959
+ tools: false
960
+ },
961
+ createSource: (request) => {
962
+ const controller = new AbortController();
963
+ let aborted = false;
964
+ return {
965
+ stream: async function* () {
966
+ if (aborted) return;
967
+ try {
968
+ const body = {
969
+ input: toInput(request),
970
+ stream: true
971
+ };
972
+ if (version) body.version = version;
973
+ const response = await fetch(predictionUrl, {
974
+ method: "POST",
975
+ headers: {
976
+ "Content-Type": "application/json",
977
+ "Authorization": `Bearer ${apiKey}`
978
+ },
979
+ body: JSON.stringify(body),
980
+ signal: controller.signal
981
+ });
982
+ if (!response.ok) {
983
+ yield { type: "error", content: `Replicate API error: ${response.status}` };
984
+ return;
985
+ }
986
+ const prediction = await response.json();
987
+ if (prediction.error) {
988
+ yield { type: "error", content: prediction.error };
989
+ return;
990
+ }
991
+ const streamUrl = prediction.urls?.stream;
992
+ if (!streamUrl) {
993
+ yield { type: "error", content: "Replicate prediction has no stream URL" };
994
+ return;
995
+ }
996
+ const streamResponse = await fetch(streamUrl, {
997
+ method: "GET",
998
+ headers: { Accept: "text/event-stream" },
999
+ signal: controller.signal
1000
+ });
1001
+ if (!streamResponse.ok || !streamResponse.body) {
1002
+ yield { type: "error", content: `Replicate stream error: ${streamResponse.status}` };
1003
+ return;
1004
+ }
1005
+ for await (const chunk of parseReplicateStream(streamResponse.body)) {
1006
+ if (aborted) return;
1007
+ yield chunk;
1008
+ }
1009
+ } catch (err) {
1010
+ if (err instanceof DOMException && err.name === "AbortError") return;
1011
+ yield { type: "error", content: err instanceof Error ? err.message : String(err) };
1012
+ }
1013
+ },
1014
+ abort: () => {
1015
+ aborted = true;
1016
+ controller.abort();
1017
+ }
1018
+ };
1019
+ }
1020
+ };
1021
+ }
1022
+ var replicateAdapter = replicate;
1023
+
1024
+ // src/bail.ts
1025
+ var BAIL_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";
1026
+ var DEFAULT_MODEL4 = "qwen-max";
1027
+ var baseFactory4 = createOpenAICompatibleAdapter(BAIL_BASE_URL);
1028
+ function bail(config) {
1029
+ const factory = baseFactory4({
1030
+ model: DEFAULT_MODEL4,
1031
+ ...config
1032
+ });
1033
+ return {
1034
+ ...factory,
1035
+ capabilities: {
1036
+ streaming: true,
1037
+ tools: true,
1038
+ multiModal: true,
1039
+ usage: true
1040
+ }
1041
+ };
1042
+ }
1043
+ var bailAdapter = bail;
1044
+ var qwen = bail;
1045
+
1046
+ // src/vertex.ts
1047
+ function vertex(config) {
1048
+ const { project, region, model, accessToken, publisher = "google", retry } = config;
1049
+ const url = `https://${region}-aiplatform.googleapis.com/v1/projects/${project}/locations/${region}/publishers/${publisher}/models/${model}:streamGenerateContent?alt=sse`;
1050
+ return {
1051
+ capabilities: {
1052
+ streaming: true,
1053
+ tools: true,
1054
+ multiModal: true,
1055
+ usage: true,
1056
+ reasoning: model.includes("pro")
1057
+ },
1058
+ createSource: (request) => {
1059
+ const body = {
1060
+ contents: request.messages.filter((message) => message.role !== "system").map((message) => ({
1061
+ role: message.role === "assistant" ? "model" : "user",
1062
+ parts: [{ text: message.content }]
1063
+ })),
1064
+ systemInstruction: request.messages.find((message) => message.role === "system") ? {
1065
+ role: "system",
1066
+ parts: [{ text: request.messages.find((message) => message.role === "system").content }]
1067
+ } : void 0,
1068
+ tools: request.context?.tools && request.context.tools.length > 0 ? [{
1069
+ functionDeclarations: request.context.tools.map((tool) => ({
1070
+ name: tool.name,
1071
+ description: tool.description,
1072
+ parameters: tool.schema
1073
+ }))
1074
+ }] : void 0
1075
+ };
1076
+ return createStreamSource(
1077
+ async (signal) => {
1078
+ const token = typeof accessToken === "string" ? accessToken : await accessToken();
1079
+ return fetch(url, {
1080
+ method: "POST",
1081
+ headers: {
1082
+ "Content-Type": "application/json",
1083
+ "Authorization": `Bearer ${token}`
1084
+ },
1085
+ body: JSON.stringify(body),
1086
+ signal
1087
+ });
1088
+ },
1089
+ parseGeminiStream,
1090
+ "Vertex AI",
1091
+ retry
1092
+ );
1093
+ }
1094
+ };
1095
+ }
1096
+ var vertexAdapter = vertex;
1097
+
1098
+ // src/bedrock.ts
1099
+ var cachedSdk = null;
1100
+ async function loadSdk() {
1101
+ if (!cachedSdk) {
1102
+ cachedSdk = (async () => {
1103
+ try {
1104
+ const moduleId = "@aws-sdk/client-bedrock-runtime";
1105
+ return await import(
1106
+ /* @vite-ignore */
1107
+ moduleId
1108
+ );
1109
+ } catch {
1110
+ throw new Error(
1111
+ "Install @aws-sdk/client-bedrock-runtime to use the bedrock adapter: npm install @aws-sdk/client-bedrock-runtime"
1112
+ );
1113
+ }
1114
+ })();
1115
+ }
1116
+ return cachedSdk;
1117
+ }
1118
+ function isAnthropicModel(model) {
1119
+ return model.startsWith("anthropic.");
1120
+ }
1121
+ function buildAnthropicBody(request, maxTokens) {
1122
+ const messages = request.messages.filter((m) => m.role !== "system").map((m) => ({ role: m.role, content: m.content }));
1123
+ const system = request.messages.find((m) => m.role === "system")?.content;
1124
+ const tools = request.context?.tools?.map((tool) => ({
1125
+ name: tool.name,
1126
+ description: tool.description,
1127
+ input_schema: tool.schema
1128
+ }));
1129
+ const body = {
1130
+ anthropic_version: "bedrock-2023-05-31",
1131
+ max_tokens: request.context?.maxTokens ?? maxTokens,
1132
+ messages
1133
+ };
1134
+ if (system) body.system = system;
1135
+ if (tools && tools.length > 0) body.tools = tools;
1136
+ return JSON.stringify(body);
1137
+ }
1138
+ async function* parseAnthropicBedrockEvents(events) {
1139
+ const decoder = new TextDecoder();
1140
+ const pendingToolCalls = /* @__PURE__ */ new Map();
1141
+ for await (const item of events) {
1142
+ const bytes = item.chunk?.bytes;
1143
+ if (!bytes) continue;
1144
+ let event;
1145
+ try {
1146
+ event = JSON.parse(decoder.decode(bytes));
1147
+ } catch {
1148
+ continue;
1149
+ }
1150
+ const type = event.type;
1151
+ if (type === "content_block_delta") {
1152
+ const delta = event.delta;
1153
+ if (delta?.type === "text_delta" && delta.text) {
1154
+ yield { type: "text", content: delta.text };
1155
+ } else if (delta?.type === "input_json_delta") {
1156
+ const index = event.index ?? 0;
1157
+ const existing = pendingToolCalls.get(index);
1158
+ if (existing) existing.args += delta.partial_json ?? "";
1159
+ }
1160
+ } else if (type === "content_block_start") {
1161
+ const index = event.index ?? 0;
1162
+ const block = event.content_block;
1163
+ if (block?.type === "tool_use" && block.id && block.name) {
1164
+ pendingToolCalls.set(index, { id: block.id, name: block.name, args: "" });
1165
+ }
1166
+ } else if (type === "content_block_stop") {
1167
+ const index = event.index ?? 0;
1168
+ const tc = pendingToolCalls.get(index);
1169
+ if (tc) {
1170
+ yield { type: "tool_call", toolCall: { id: tc.id, name: tc.name, args: tc.args || "{}" } };
1171
+ pendingToolCalls.delete(index);
1172
+ }
1173
+ } else if (type === "message_delta") {
1174
+ const usage = event.usage;
1175
+ if (usage) {
1176
+ const promptTokens = usage.input_tokens ?? 0;
1177
+ const completionTokens = usage.output_tokens ?? 0;
1178
+ yield {
1179
+ type: "usage",
1180
+ usage: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens }
1181
+ };
1182
+ }
1183
+ } else if (type === "message_start") {
1184
+ const usage = event.message?.usage;
1185
+ if (usage) {
1186
+ yield {
1187
+ type: "usage",
1188
+ usage: {
1189
+ promptTokens: usage.input_tokens ?? 0,
1190
+ completionTokens: 0,
1191
+ totalTokens: usage.input_tokens ?? 0
1192
+ }
1193
+ };
1194
+ }
1195
+ } else if (type === "message_stop") {
1196
+ for (const [, tc] of pendingToolCalls) {
1197
+ yield { type: "tool_call", toolCall: { id: tc.id, name: tc.name, args: tc.args || "{}" } };
1198
+ }
1199
+ pendingToolCalls.clear();
1200
+ yield { type: "done" };
1201
+ return;
1202
+ }
1203
+ }
1204
+ for (const [, tc] of pendingToolCalls) {
1205
+ yield { type: "tool_call", toolCall: { id: tc.id, name: tc.name, args: tc.args || "{}" } };
1206
+ }
1207
+ pendingToolCalls.clear();
1208
+ yield { type: "done" };
1209
+ }
1210
+ function bedrock(config) {
1211
+ const { model, region, maxTokens = 4096 } = config;
1212
+ if (!isAnthropicModel(model)) {
1213
+ throw new Error(
1214
+ `bedrock: model "${model}" is not supported in v1. Only anthropic.* models are wired up; Titan + others are tracked as a follow-up.`
1215
+ );
1216
+ }
1217
+ let clientPromise = null;
1218
+ const getClient = async () => {
1219
+ if (config.client) return config.client;
1220
+ if (!clientPromise) {
1221
+ clientPromise = (async () => {
1222
+ const sdk = await loadSdk();
1223
+ return new sdk.BedrockRuntimeClient({ region });
1224
+ })();
1225
+ }
1226
+ return clientPromise;
1227
+ };
1228
+ return {
1229
+ capabilities: {
1230
+ streaming: true,
1231
+ tools: true,
1232
+ reasoning: model.includes("sonnet") || model.includes("opus"),
1233
+ multiModal: true,
1234
+ usage: true
1235
+ },
1236
+ createSource: (request) => {
1237
+ const controller = new AbortController();
1238
+ let aborted = false;
1239
+ return {
1240
+ stream: async function* () {
1241
+ if (aborted) return;
1242
+ try {
1243
+ const client = await getClient();
1244
+ const sdk = config.client ? null : await loadSdk();
1245
+ const input = {
1246
+ modelId: model,
1247
+ contentType: "application/json",
1248
+ accept: "application/json",
1249
+ body: buildAnthropicBody(request, maxTokens)
1250
+ };
1251
+ const command = sdk ? new sdk.InvokeModelWithResponseStreamCommand(input) : { input };
1252
+ const response = await client.send(command);
1253
+ if (!response.body) {
1254
+ yield { type: "error", content: "Bedrock: empty response body" };
1255
+ return;
1256
+ }
1257
+ for await (const chunk of parseAnthropicBedrockEvents(response.body)) {
1258
+ if (aborted) return;
1259
+ yield chunk;
1260
+ }
1261
+ } catch (err) {
1262
+ yield { type: "error", content: err instanceof Error ? err.message : String(err) };
1263
+ }
1264
+ },
1265
+ abort: () => {
1266
+ aborted = true;
1267
+ controller.abort();
1268
+ }
1269
+ };
1270
+ }
1271
+ };
1272
+ }
1273
+ var bedrockAdapter = bedrock;
1274
+
1275
+ // src/webllm.ts
1276
+ var cachedSdk2 = null;
1277
+ async function loadSdk2() {
1278
+ if (!cachedSdk2) {
1279
+ cachedSdk2 = (async () => {
1280
+ try {
1281
+ const moduleId = "@mlc-ai/web-llm";
1282
+ return await import(
1283
+ /* @vite-ignore */
1284
+ moduleId
1285
+ );
1286
+ } catch {
1287
+ throw new Error("Install @mlc-ai/web-llm to use the webllm adapter: npm install @mlc-ai/web-llm");
1288
+ }
1289
+ })();
1290
+ }
1291
+ return cachedSdk2;
1292
+ }
1293
+ function webllm(config) {
1294
+ let enginePromise = null;
1295
+ const getEngine = () => {
1296
+ if (config.engine) return Promise.resolve(config.engine);
1297
+ if (!enginePromise) {
1298
+ enginePromise = (async () => {
1299
+ const sdk = await loadSdk2();
1300
+ return sdk.CreateMLCEngine(config.model, { initProgressCallback: config.onProgress });
1301
+ })();
1302
+ }
1303
+ return enginePromise;
1304
+ };
1305
+ return {
1306
+ capabilities: {
1307
+ streaming: true,
1308
+ tools: false
1309
+ },
1310
+ createSource: (request) => {
1311
+ let aborted = false;
1312
+ return {
1313
+ stream: async function* () {
1314
+ if (aborted) return;
1315
+ try {
1316
+ const engine = await getEngine();
1317
+ const messages = request.messages.map((m) => ({ role: m.role, content: m.content }));
1318
+ const completion = await engine.chat.completions.create({ messages, stream: true });
1319
+ for await (const chunk of completion) {
1320
+ if (aborted) return;
1321
+ const delta = chunk.choices[0]?.delta?.content;
1322
+ if (delta) yield { type: "text", content: delta };
1323
+ }
1324
+ yield { type: "done" };
1325
+ } catch (err) {
1326
+ yield { type: "error", content: err instanceof Error ? err.message : String(err) };
1327
+ }
1328
+ },
1329
+ abort: () => {
1330
+ aborted = true;
1331
+ }
1332
+ };
1333
+ }
1334
+ };
1335
+ }
1336
+ var webllmAdapter = webllm;
1337
+
808
1338
  // src/router.ts
809
1339
  function requireCapabilities(request) {
810
1340
  const needs = {};
@@ -1329,6 +1859,6 @@ var grokEmbedder = createOpenAICompatibleEmbedder("Grok", "https://api.x.ai");
1329
1859
  // src/embedders/kimi.ts
1330
1860
  var kimiEmbedder = createOpenAICompatibleEmbedder("Kimi", "https://api.moonshot.ai");
1331
1861
 
1332
- export { anthropic, chunkText, cohere, createAdapter, createEnsembleAdapter, createFallbackAdapter, createOpenAICompatibleEmbedder, createRouter, deepseek, deepseekEmbedder, fetchWithRetry, fireworks, gemini, geminiEmbedder, generic, grok, grokEmbedder, groq, huggingface, inMemorySink, kimi, kimiEmbedder, langchain, langgraph, llamacpp, lmstudio, mistral, mockAdapter, ollama, ollamaEmbedder, openai, openaiEmbedder, openrouter, recordingAdapter, replayAdapter, simulateStream, together, vercelAI, vllm };
1862
+ export { anthropic, azureOpenAI, azureOpenAIAdapter, bail, bailAdapter, bedrock, bedrockAdapter, cerebras, cerebrasAdapter, chunkText, cohere, cohereAdapter, createAdapter, createEnsembleAdapter, createFallbackAdapter, createOpenAICompatibleEmbedder, createRouter, deepseek, deepseekEmbedder, fetchWithRetry, fireworks, gemini, geminiEmbedder, generic, grok, grokEmbedder, groq, groqAdapter, huggingface, inMemorySink, kimi, kimiEmbedder, langchain, langgraph, llamacpp, lmstudio, mistral, mockAdapter, ollama, ollamaEmbedder, openai, openaiEmbedder, openrouter, qwen, recordingAdapter, replayAdapter, replicate, replicateAdapter, simulateStream, together, vercelAI, vertex, vertexAdapter, vllm, webllm, webllmAdapter };
1333
1863
  //# sourceMappingURL=index.js.map
1334
1864
  //# sourceMappingURL=index.js.map