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