openloops 0.1.31 → 0.1.33
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/clients/llm-client.d.ts +5 -0
- package/dist/clients/llm-client.js +73 -15
- package/dist/clients/llm-client.mjs +73 -15
- package/dist/clients/llm-error.d.ts +9 -0
- package/dist/clients/llm-error.js +69 -0
- package/dist/clients/llm-error.mjs +45 -0
- package/dist/clients/llm-types.d.ts +61 -0
- package/dist/clients/llm-types.js +16 -0
- package/dist/clients/llm-types.mjs +0 -0
- package/dist/clients/pi-ai-adapter.d.ts +7 -0
- package/dist/clients/pi-ai-adapter.js +137 -0
- package/dist/clients/pi-ai-adapter.mjs +113 -0
- package/dist/{agent → harness}/agent-loop.d.ts +11 -1
- package/dist/{agent → harness}/agent-state.js +1 -1
- package/dist/{agent → harness}/agent-state.mjs +1 -1
- package/dist/{agent → harness}/agent.d.ts +34 -3
- package/dist/harness/agent.js +546 -0
- package/dist/harness/agent.mjs +530 -0
- package/dist/{agent → harness}/index.js +5 -5
- package/dist/harness/native-tools.d.ts +23 -0
- package/dist/harness/native-tools.js +251 -0
- package/dist/harness/native-tools.mjs +227 -0
- package/dist/harness/tool-catalog.d.ts +16 -0
- package/dist/harness/tool-catalog.js +85 -0
- package/dist/harness/tool-catalog.mjs +59 -0
- package/dist/harness/tool-pipeline.d.ts +42 -0
- package/dist/harness/tool-pipeline.js +200 -0
- package/dist/harness/tool-pipeline.mjs +177 -0
- package/dist/harness/utils/describe-shape.d.ts +2 -0
- package/dist/harness/utils/describe-shape.js +56 -0
- package/dist/harness/utils/describe-shape.mjs +32 -0
- package/dist/harness/utils/grounding.d.ts +6 -0
- package/dist/harness/utils/grounding.js +79 -0
- package/dist/harness/utils/grounding.mjs +53 -0
- package/dist/harness/workspace.d.ts +44 -0
- package/dist/harness/workspace.js +95 -0
- package/dist/harness/workspace.mjs +78 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/loops/agi/index.d.ts +1 -0
- package/dist/loops/agi/index.js +22 -0
- package/dist/loops/agi/index.mjs +1 -0
- package/dist/loops/agi/loop.d.ts +24 -0
- package/dist/loops/agi/loop.js +220 -0
- package/dist/loops/agi/loop.mjs +197 -0
- package/dist/loops/agi/skills/reasoning-engine.d.ts +14 -0
- package/dist/loops/agi/skills/reasoning-engine.js +94 -0
- package/dist/loops/agi/skills/reasoning-engine.mjs +71 -0
- package/dist/loops/index.d.ts +1 -0
- package/dist/loops/index.js +3 -1
- package/dist/loops/index.mjs +1 -0
- package/dist/loops/plan-execute/plan-execute-loop.d.ts +2 -1
- package/dist/loops/plan-execute/plan-execute-loop.js +90 -35
- package/dist/loops/plan-execute/plan-execute-loop.mjs +80 -25
- package/dist/loops/shared/skills/action-planner.js +7 -4
- package/dist/loops/shared/skills/action-planner.mjs +7 -4
- package/dist/loops/shared/skills/final-responder.js +4 -3
- package/dist/loops/shared/skills/final-responder.mjs +4 -3
- package/dist/loops/shared/skills/state-observer.js +6 -2
- package/dist/loops/shared/skills/state-observer.mjs +6 -2
- package/dist/services/chats/entities/chat-message.entity.d.ts +4 -1
- package/dist/services/chats/entities/chat-message.entity.js +7 -3
- package/dist/services/chats/entities/chat-message.entity.mjs +7 -3
- package/dist/services/chats/entities/chat.entity.d.ts +10 -11
- package/dist/services/chats/entities/chat.entity.js +17 -21
- package/dist/services/chats/entities/chat.entity.mjs +17 -21
- package/dist/services/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.d.ts +2 -0
- package/dist/services/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.js +4 -4
- package/dist/services/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.mjs +2 -2
- package/dist/services/tasks/entities/agent-action.entity.d.ts +111 -0
- package/dist/services/tasks/entities/agent-action.entity.js +271 -0
- package/dist/services/tasks/entities/agent-action.entity.mjs +247 -0
- package/dist/services/tasks/entities/agent-task.entity.d.ts +176 -0
- package/dist/services/tasks/entities/agent-task.entity.js +695 -0
- package/dist/services/tasks/entities/agent-task.entity.mjs +662 -0
- package/dist/services/tasks/entities/index.d.ts +2 -0
- package/dist/services/tasks/entities/index.js +24 -0
- package/dist/services/tasks/entities/index.mjs +2 -0
- package/dist/services/tasks/index.d.ts +3 -0
- package/dist/services/tasks/index.js +26 -0
- package/dist/services/tasks/index.mjs +3 -0
- package/dist/services/tasks/lambdas/create-agent-action/create-agent-action.use-case.d.ts +14 -0
- package/dist/services/tasks/lambdas/create-agent-action/create-agent-action.use-case.js +60 -0
- package/dist/services/tasks/lambdas/create-agent-action/create-agent-action.use-case.mjs +31 -0
- package/dist/services/tasks/lambdas/create-agent-action/index.d.ts +1 -0
- package/dist/services/tasks/lambdas/create-agent-action/index.js +22 -0
- package/dist/services/tasks/lambdas/create-agent-action/index.mjs +1 -0
- package/dist/services/tasks/lambdas/create-agent-task/create-agent-task.use-case.d.ts +14 -0
- package/dist/services/tasks/lambdas/create-agent-task/create-agent-task.use-case.js +60 -0
- package/dist/services/tasks/lambdas/create-agent-task/create-agent-task.use-case.mjs +31 -0
- package/dist/services/tasks/lambdas/create-agent-task/index.d.ts +1 -0
- package/dist/services/tasks/lambdas/create-agent-task/index.js +22 -0
- package/dist/services/tasks/lambdas/create-agent-task/index.mjs +1 -0
- package/dist/services/tasks/lambdas/get-agent-task-by-id/get-agent-task-by-id.use-case.d.ts +14 -0
- package/dist/services/tasks/lambdas/get-agent-task-by-id/get-agent-task-by-id.use-case.js +55 -0
- package/dist/services/tasks/lambdas/get-agent-task-by-id/get-agent-task-by-id.use-case.mjs +26 -0
- package/dist/services/tasks/lambdas/get-agent-task-by-id/index.d.ts +1 -0
- package/dist/services/tasks/lambdas/get-agent-task-by-id/index.js +22 -0
- package/dist/services/tasks/lambdas/get-agent-task-by-id/index.mjs +1 -0
- package/dist/services/tasks/lambdas/index.d.ts +7 -0
- package/dist/services/tasks/lambdas/index.js +46 -0
- package/dist/services/tasks/lambdas/index.mjs +17 -0
- package/dist/services/tasks/lambdas/list-agent-actions-by-task/index.d.ts +1 -0
- package/dist/services/tasks/lambdas/list-agent-actions-by-task/index.js +22 -0
- package/dist/services/tasks/lambdas/list-agent-actions-by-task/index.mjs +1 -0
- package/dist/services/tasks/lambdas/list-agent-actions-by-task/list-agent-actions-by-task.use-case.d.ts +16 -0
- package/dist/services/tasks/lambdas/list-agent-actions-by-task/list-agent-actions-by-task.use-case.js +62 -0
- package/dist/services/tasks/lambdas/list-agent-actions-by-task/list-agent-actions-by-task.use-case.mjs +33 -0
- package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/index.d.ts +1 -0
- package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/index.js +22 -0
- package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/index.mjs +1 -0
- package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/list-agent-tasks-by-chat.use-case.d.ts +16 -0
- package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/list-agent-tasks-by-chat.use-case.js +62 -0
- package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/list-agent-tasks-by-chat.use-case.mjs +33 -0
- package/dist/services/tasks/lambdas/update-agent-action/index.d.ts +1 -0
- package/dist/services/tasks/lambdas/update-agent-action/index.js +22 -0
- package/dist/services/tasks/lambdas/update-agent-action/index.mjs +1 -0
- package/dist/services/tasks/lambdas/update-agent-action/update-agent-action.use-case.d.ts +15 -0
- package/dist/services/tasks/lambdas/update-agent-action/update-agent-action.use-case.js +67 -0
- package/dist/services/tasks/lambdas/update-agent-action/update-agent-action.use-case.mjs +38 -0
- package/dist/services/tasks/lambdas/update-agent-task/index.d.ts +1 -0
- package/dist/services/tasks/lambdas/update-agent-task/index.js +22 -0
- package/dist/services/tasks/lambdas/update-agent-task/index.mjs +1 -0
- package/dist/services/tasks/lambdas/update-agent-task/update-agent-task.use-case.d.ts +15 -0
- package/dist/services/tasks/lambdas/update-agent-task/update-agent-task.use-case.js +67 -0
- package/dist/services/tasks/lambdas/update-agent-task/update-agent-task.use-case.mjs +38 -0
- package/dist/services/tasks/module.d.ts +15 -0
- package/dist/services/tasks/module.js +76 -0
- package/dist/services/tasks/module.mjs +47 -0
- package/dist/services/tasks/repositories/agent-action.repository.d.ts +8 -0
- package/dist/services/tasks/repositories/agent-action.repository.js +62 -0
- package/dist/services/tasks/repositories/agent-action.repository.mjs +33 -0
- package/dist/services/tasks/repositories/agent-task.repository.d.ts +9 -0
- package/dist/services/tasks/repositories/agent-task.repository.js +65 -0
- package/dist/services/tasks/repositories/agent-task.repository.mjs +36 -0
- package/dist/services/tasks/repositories/index.d.ts +2 -0
- package/dist/services/tasks/repositories/index.js +24 -0
- package/dist/services/tasks/repositories/index.mjs +2 -0
- package/dist/services/traces/entities/agent-trace-entry.entity.d.ts +30 -0
- package/dist/services/traces/entities/agent-trace-entry.entity.js +85 -0
- package/dist/services/traces/entities/agent-trace-entry.entity.mjs +62 -0
- package/dist/services/traces/entities/index.d.ts +1 -0
- package/dist/services/traces/entities/index.js +22 -0
- package/dist/services/traces/entities/index.mjs +1 -0
- package/dist/services/traces/index.d.ts +3 -0
- package/dist/services/traces/index.js +26 -0
- package/dist/services/traces/index.mjs +3 -0
- package/dist/services/traces/lambdas/create-agent-traces/create-agent-traces.use-case.d.ts +16 -0
- package/dist/services/traces/lambdas/create-agent-traces/create-agent-traces.use-case.js +62 -0
- package/dist/services/traces/lambdas/create-agent-traces/create-agent-traces.use-case.mjs +33 -0
- package/dist/services/traces/lambdas/create-agent-traces/index.d.ts +1 -0
- package/dist/services/traces/lambdas/create-agent-traces/index.js +22 -0
- package/dist/services/traces/lambdas/create-agent-traces/index.mjs +1 -0
- package/dist/services/traces/lambdas/index.d.ts +2 -0
- package/dist/services/traces/lambdas/index.js +31 -0
- package/dist/services/traces/lambdas/index.mjs +7 -0
- package/dist/services/traces/lambdas/list-agent-traces-by-chat/index.d.ts +1 -0
- package/dist/services/traces/lambdas/list-agent-traces-by-chat/index.js +22 -0
- package/dist/services/traces/lambdas/list-agent-traces-by-chat/index.mjs +1 -0
- package/dist/services/traces/lambdas/list-agent-traces-by-chat/list-agent-traces-by-chat.use-case.d.ts +18 -0
- package/dist/services/traces/lambdas/list-agent-traces-by-chat/list-agent-traces-by-chat.use-case.js +67 -0
- package/dist/services/traces/lambdas/list-agent-traces-by-chat/list-agent-traces-by-chat.use-case.mjs +38 -0
- package/dist/services/traces/module.d.ts +5 -0
- package/dist/services/traces/module.js +41 -0
- package/dist/services/traces/module.mjs +17 -0
- package/dist/services/traces/repositories/agent-trace.repository.d.ts +7 -0
- package/dist/services/traces/repositories/agent-trace.repository.js +55 -0
- package/dist/services/traces/repositories/agent-trace.repository.mjs +26 -0
- package/dist/services/traces/repositories/index.d.ts +1 -0
- package/dist/services/traces/repositories/index.js +22 -0
- package/dist/services/traces/repositories/index.mjs +1 -0
- package/dist/services/workspaces/entities/index.d.ts +1 -0
- package/dist/services/workspaces/entities/index.js +22 -0
- package/dist/services/workspaces/entities/index.mjs +1 -0
- package/dist/services/workspaces/entities/workspace-item.entity.d.ts +33 -0
- package/dist/services/workspaces/entities/workspace-item.entity.js +95 -0
- package/dist/services/workspaces/entities/workspace-item.entity.mjs +72 -0
- package/dist/services/workspaces/index.d.ts +3 -0
- package/dist/services/workspaces/index.js +26 -0
- package/dist/services/workspaces/index.mjs +3 -0
- package/dist/services/workspaces/lambdas/delete-workspace-item/delete-workspace-item.use-case.d.ts +17 -0
- package/dist/services/workspaces/lambdas/delete-workspace-item/delete-workspace-item.use-case.js +68 -0
- package/dist/services/workspaces/lambdas/delete-workspace-item/delete-workspace-item.use-case.mjs +39 -0
- package/dist/services/workspaces/lambdas/delete-workspace-item/index.d.ts +1 -0
- package/dist/services/workspaces/lambdas/delete-workspace-item/index.js +22 -0
- package/dist/services/workspaces/lambdas/delete-workspace-item/index.mjs +1 -0
- package/dist/services/workspaces/lambdas/get-workspace-item/get-workspace-item.use-case.d.ts +17 -0
- package/dist/services/workspaces/lambdas/get-workspace-item/get-workspace-item.use-case.js +67 -0
- package/dist/services/workspaces/lambdas/get-workspace-item/get-workspace-item.use-case.mjs +38 -0
- package/dist/services/workspaces/lambdas/get-workspace-item/index.d.ts +1 -0
- package/dist/services/workspaces/lambdas/get-workspace-item/index.js +22 -0
- package/dist/services/workspaces/lambdas/get-workspace-item/index.mjs +1 -0
- package/dist/services/workspaces/lambdas/index.d.ts +5 -0
- package/dist/services/workspaces/lambdas/index.js +40 -0
- package/dist/services/workspaces/lambdas/index.mjs +13 -0
- package/dist/services/workspaces/lambdas/list-workspace-items/index.d.ts +1 -0
- package/dist/services/workspaces/lambdas/list-workspace-items/index.js +22 -0
- package/dist/services/workspaces/lambdas/list-workspace-items/index.mjs +1 -0
- package/dist/services/workspaces/lambdas/list-workspace-items/list-workspace-items.use-case.d.ts +18 -0
- package/dist/services/workspaces/lambdas/list-workspace-items/list-workspace-items.use-case.js +69 -0
- package/dist/services/workspaces/lambdas/list-workspace-items/list-workspace-items.use-case.mjs +40 -0
- package/dist/services/workspaces/lambdas/save-workspace-item/index.d.ts +1 -0
- package/dist/services/workspaces/lambdas/save-workspace-item/index.js +22 -0
- package/dist/services/workspaces/lambdas/save-workspace-item/index.mjs +1 -0
- package/dist/services/workspaces/lambdas/save-workspace-item/save-workspace-item.use-case.d.ts +14 -0
- package/dist/services/workspaces/lambdas/save-workspace-item/save-workspace-item.use-case.js +76 -0
- package/dist/services/workspaces/lambdas/save-workspace-item/save-workspace-item.use-case.mjs +47 -0
- package/dist/services/workspaces/lambdas/search-workspace-items/index.d.ts +1 -0
- package/dist/services/workspaces/lambdas/search-workspace-items/index.js +22 -0
- package/dist/services/workspaces/lambdas/search-workspace-items/index.mjs +1 -0
- package/dist/services/workspaces/lambdas/search-workspace-items/search-workspace-items.use-case.d.ts +19 -0
- package/dist/services/workspaces/lambdas/search-workspace-items/search-workspace-items.use-case.js +73 -0
- package/dist/services/workspaces/lambdas/search-workspace-items/search-workspace-items.use-case.mjs +44 -0
- package/dist/services/workspaces/module.d.ts +11 -0
- package/dist/services/workspaces/module.js +62 -0
- package/dist/services/workspaces/module.mjs +35 -0
- package/dist/services/workspaces/repositories/index.d.ts +1 -0
- package/dist/services/workspaces/repositories/index.js +22 -0
- package/dist/services/workspaces/repositories/index.mjs +1 -0
- package/dist/services/workspaces/repositories/workspace-item.repository.d.ts +18 -0
- package/dist/services/workspaces/repositories/workspace-item.repository.js +74 -0
- package/dist/services/workspaces/repositories/workspace-item.repository.mjs +45 -0
- package/dist/skills/runtime-context.d.ts +8 -0
- package/dist/skills/runtime-context.js +65 -0
- package/dist/skills/runtime-context.mjs +42 -0
- package/dist/skills/skill.d.ts +7 -0
- package/dist/skills/skill.js +26 -60
- package/dist/skills/skill.mjs +26 -60
- package/dist/tools/tool.d.ts +6 -0
- package/dist/tools/tool.js +56 -0
- package/dist/tools/tool.mjs +56 -0
- package/package.json +3 -3
- package/dist/agent/agent.js +0 -327
- package/dist/agent/agent.mjs +0 -303
- package/dist/services/chats/entities/agent-action.entity.d.ts +0 -58
- package/dist/services/chats/entities/agent-action.entity.js +0 -151
- package/dist/services/chats/entities/agent-action.entity.mjs +0 -128
- package/dist/services/chats/entities/agent-task.entity.d.ts +0 -59
- package/dist/services/chats/entities/agent-task.entity.js +0 -231
- package/dist/services/chats/entities/agent-task.entity.mjs +0 -207
- package/dist/services/chats/entities/chat-context.entity.d.ts +0 -39
- package/dist/services/chats/entities/chat-context.entity.js +0 -70
- package/dist/services/chats/entities/chat-context.entity.mjs +0 -47
- /package/dist/{agent → harness}/agent-loop.js +0 -0
- /package/dist/{agent → harness}/agent-loop.mjs +0 -0
- /package/dist/{agent → harness}/agent-state.d.ts +0 -0
- /package/dist/{agent → harness}/index.d.ts +0 -0
- /package/dist/{agent → harness}/index.mjs +0 -0
- /package/dist/{agent → harness}/utils/rank-tools-by-keywords.d.ts +0 -0
- /package/dist/{agent → harness}/utils/rank-tools-by-keywords.js +0 -0
- /package/dist/{agent → harness}/utils/rank-tools-by-keywords.mjs +0 -0
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import type { KnownProvider, Message, AssistantMessage } from '@earendil-works/pi-ai';
|
|
2
2
|
import { CurrentUser } from '../common/base/index.js';
|
|
3
|
+
import { LLMChatParams, LLMResponse } from './llm-types';
|
|
3
4
|
export declare class LLMClient {
|
|
4
5
|
private readonly logger;
|
|
5
6
|
private readonly langfuse?;
|
|
6
7
|
private readonly langfuseEnabled;
|
|
7
8
|
constructor();
|
|
9
|
+
chat(params: LLMChatParams): Promise<LLMResponse>;
|
|
8
10
|
complete(params: LLMCompletionParams): Promise<AssistantMessage>;
|
|
11
|
+
private waitingOnRateLimit;
|
|
12
|
+
private traced;
|
|
9
13
|
private postResponse;
|
|
10
14
|
private formatContentForLog;
|
|
15
|
+
private formatTextForLog;
|
|
11
16
|
private formatMessagesForLog;
|
|
12
17
|
}
|
|
13
18
|
export interface LLMCompletionParams {
|
|
@@ -36,6 +36,13 @@ var import_secret_manager = require("../common/utils/secret-manager.js");
|
|
|
36
36
|
var import_logger = require("../common/logger/index.js");
|
|
37
37
|
var import_helpers = require("../common/helpers/index.js");
|
|
38
38
|
var import_llmcalls = require("../services/llmcalls/index.js");
|
|
39
|
+
var import_pi_ai_adapter = require("./pi-ai-adapter");
|
|
40
|
+
var import_llm_error = require("./llm-error");
|
|
41
|
+
const DEFAULT_PROVIDER = "openai";
|
|
42
|
+
const DEFAULT_MODEL = "gpt-4o-mini";
|
|
43
|
+
const DEFAULT_TEMPERATURE = 0.7;
|
|
44
|
+
const MAX_RETRIES = 4;
|
|
45
|
+
const MAX_RATE_LIMIT_WAITS = 2;
|
|
39
46
|
class LLMClient {
|
|
40
47
|
logger = new import_logger.Logger();
|
|
41
48
|
langfuse;
|
|
@@ -53,6 +60,38 @@ class LLMClient {
|
|
|
53
60
|
this.logger.debug("[LLM Service] Langfuse disabled: configuration variables missing");
|
|
54
61
|
}
|
|
55
62
|
}
|
|
63
|
+
async chat(params) {
|
|
64
|
+
const {
|
|
65
|
+
origin,
|
|
66
|
+
sessionId,
|
|
67
|
+
answerId,
|
|
68
|
+
currentUser,
|
|
69
|
+
messages,
|
|
70
|
+
tools,
|
|
71
|
+
toolChoice,
|
|
72
|
+
provider = DEFAULT_PROVIDER,
|
|
73
|
+
modelName = DEFAULT_MODEL,
|
|
74
|
+
temperature = DEFAULT_TEMPERATURE
|
|
75
|
+
} = params;
|
|
76
|
+
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
77
|
+
const models = builtinModels();
|
|
78
|
+
const model = models.getModel(provider, modelName);
|
|
79
|
+
if (!model) throw new Error("[LLM Client] model not found");
|
|
80
|
+
const context = (0, import_pi_ai_adapter.toPiContext)({ messages, tools }, model);
|
|
81
|
+
const options = { temperature, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
|
|
82
|
+
const raw = await this.traced(
|
|
83
|
+
{ origin, sessionId, answerId, currentUser, modelName, provider, temperature },
|
|
84
|
+
context,
|
|
85
|
+
() => this.waitingOnRateLimit(() => toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options))
|
|
86
|
+
);
|
|
87
|
+
if (raw.stopReason === "error" || raw.stopReason === "aborted") {
|
|
88
|
+
throw import_llm_error.LLMError.fromProvider(raw.errorMessage ?? `request ${raw.stopReason}`);
|
|
89
|
+
}
|
|
90
|
+
return (0, import_pi_ai_adapter.fromPiMessage)(raw);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* @deprecated Use chat(). Kept so callers that still depend on the provider message shape keep working.
|
|
94
|
+
*/
|
|
56
95
|
async complete(params) {
|
|
57
96
|
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
58
97
|
const models = builtinModels();
|
|
@@ -63,9 +102,9 @@ class LLMClient {
|
|
|
63
102
|
currentUser,
|
|
64
103
|
systemPrompt,
|
|
65
104
|
messages,
|
|
66
|
-
provider =
|
|
67
|
-
modelName =
|
|
68
|
-
temperature =
|
|
105
|
+
provider = DEFAULT_PROVIDER,
|
|
106
|
+
modelName = DEFAULT_MODEL,
|
|
107
|
+
temperature = DEFAULT_TEMPERATURE
|
|
69
108
|
} = params ?? {};
|
|
70
109
|
const model = models.getModel(provider, modelName);
|
|
71
110
|
if (!model) throw new Error("[LLM Client] model not found");
|
|
@@ -73,11 +112,31 @@ class LLMClient {
|
|
|
73
112
|
systemPrompt,
|
|
74
113
|
messages
|
|
75
114
|
};
|
|
115
|
+
return this.traced(
|
|
116
|
+
{ origin, sessionId, answerId, currentUser, modelName, provider, temperature },
|
|
117
|
+
context,
|
|
118
|
+
() => this.waitingOnRateLimit(() => models.complete(model, context, { temperature, maxRetries: MAX_RETRIES }))
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
async waitingOnRateLimit(run) {
|
|
122
|
+
let response = await run();
|
|
123
|
+
for (let waits = 0; waits < MAX_RATE_LIMIT_WAITS && response.stopReason === "error"; waits++) {
|
|
124
|
+
const delay = import_llm_error.LLMError.fromProvider(response.errorMessage ?? "").code === "LLM_RATE_LIMITED" ? (0, import_llm_error.retryDelayMs)(response.errorMessage) : void 0;
|
|
125
|
+
if (!delay) break;
|
|
126
|
+
this.logger.warn({ waitMs: delay }, "[LLM Service] Rate limited, waiting before retrying");
|
|
127
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
128
|
+
response = await run();
|
|
129
|
+
}
|
|
130
|
+
return response;
|
|
131
|
+
}
|
|
132
|
+
async traced(call, context, run) {
|
|
133
|
+
const { origin, sessionId, answerId, currentUser, modelName, provider, temperature } = call;
|
|
76
134
|
this.logger.debug({
|
|
77
135
|
origin,
|
|
78
136
|
context: {
|
|
79
137
|
...context,
|
|
80
|
-
|
|
138
|
+
...context.systemPrompt ? { systemPrompt: this.formatTextForLog(context.systemPrompt) } : {},
|
|
139
|
+
messages: this.formatMessagesForLog(context.messages)
|
|
81
140
|
}
|
|
82
141
|
}, "[LLM Service] context");
|
|
83
142
|
const trace = this.langfuseEnabled ? this.langfuse.trace({
|
|
@@ -97,9 +156,7 @@ class LLMClient {
|
|
|
97
156
|
input: context
|
|
98
157
|
});
|
|
99
158
|
try {
|
|
100
|
-
const response = await
|
|
101
|
-
temperature
|
|
102
|
-
});
|
|
159
|
+
const response = await run();
|
|
103
160
|
generation?.end({
|
|
104
161
|
output: response,
|
|
105
162
|
usage: response.usage ? {
|
|
@@ -142,19 +199,20 @@ class LLMClient {
|
|
|
142
199
|
}
|
|
143
200
|
formatContentForLog(records) {
|
|
144
201
|
return records?.map((record) => {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const isJson = Object.keys(extracted).length > 0;
|
|
148
|
-
return {
|
|
149
|
-
...record,
|
|
150
|
-
text: isJson ? extracted : text
|
|
151
|
-
};
|
|
202
|
+
if (record?.type !== "text") return record;
|
|
203
|
+
return { ...record, text: this.formatTextForLog(record?.text) };
|
|
152
204
|
});
|
|
153
205
|
}
|
|
206
|
+
formatTextForLog(text) {
|
|
207
|
+
if (typeof text !== "string") return text;
|
|
208
|
+
const extracted = (0, import_helpers.extractJSON)(text);
|
|
209
|
+
const isJson = extracted && Object.keys(extracted).length > 0;
|
|
210
|
+
return isJson ? extracted : text;
|
|
211
|
+
}
|
|
154
212
|
formatMessagesForLog(messages) {
|
|
155
213
|
return messages.map((message) => ({
|
|
156
214
|
...message,
|
|
157
|
-
content: this.formatContentForLog(message
|
|
215
|
+
content: Array.isArray(message?.content) ? this.formatContentForLog(message.content) : this.formatTextForLog(message?.content)
|
|
158
216
|
}));
|
|
159
217
|
}
|
|
160
218
|
}
|
|
@@ -4,6 +4,13 @@ import { secretManager } from "../common/utils/secret-manager.js";
|
|
|
4
4
|
import { Logger } from "../common/logger/index.js";
|
|
5
5
|
import { extractJSON } from "../common/helpers/index.js";
|
|
6
6
|
import { createLLMCall } from "../services/llmcalls/index.js";
|
|
7
|
+
import { toPiContext, fromPiMessage } from "./pi-ai-adapter";
|
|
8
|
+
import { LLMError, retryDelayMs } from "./llm-error";
|
|
9
|
+
const DEFAULT_PROVIDER = "openai";
|
|
10
|
+
const DEFAULT_MODEL = "gpt-4o-mini";
|
|
11
|
+
const DEFAULT_TEMPERATURE = 0.7;
|
|
12
|
+
const MAX_RETRIES = 4;
|
|
13
|
+
const MAX_RATE_LIMIT_WAITS = 2;
|
|
7
14
|
class LLMClient {
|
|
8
15
|
logger = new Logger();
|
|
9
16
|
langfuse;
|
|
@@ -21,6 +28,38 @@ class LLMClient {
|
|
|
21
28
|
this.logger.debug("[LLM Service] Langfuse disabled: configuration variables missing");
|
|
22
29
|
}
|
|
23
30
|
}
|
|
31
|
+
async chat(params) {
|
|
32
|
+
const {
|
|
33
|
+
origin,
|
|
34
|
+
sessionId,
|
|
35
|
+
answerId,
|
|
36
|
+
currentUser,
|
|
37
|
+
messages,
|
|
38
|
+
tools,
|
|
39
|
+
toolChoice,
|
|
40
|
+
provider = DEFAULT_PROVIDER,
|
|
41
|
+
modelName = DEFAULT_MODEL,
|
|
42
|
+
temperature = DEFAULT_TEMPERATURE
|
|
43
|
+
} = params;
|
|
44
|
+
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
45
|
+
const models = builtinModels();
|
|
46
|
+
const model = models.getModel(provider, modelName);
|
|
47
|
+
if (!model) throw new Error("[LLM Client] model not found");
|
|
48
|
+
const context = toPiContext({ messages, tools }, model);
|
|
49
|
+
const options = { temperature, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
|
|
50
|
+
const raw = await this.traced(
|
|
51
|
+
{ origin, sessionId, answerId, currentUser, modelName, provider, temperature },
|
|
52
|
+
context,
|
|
53
|
+
() => this.waitingOnRateLimit(() => toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options))
|
|
54
|
+
);
|
|
55
|
+
if (raw.stopReason === "error" || raw.stopReason === "aborted") {
|
|
56
|
+
throw LLMError.fromProvider(raw.errorMessage ?? `request ${raw.stopReason}`);
|
|
57
|
+
}
|
|
58
|
+
return fromPiMessage(raw);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* @deprecated Use chat(). Kept so callers that still depend on the provider message shape keep working.
|
|
62
|
+
*/
|
|
24
63
|
async complete(params) {
|
|
25
64
|
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
26
65
|
const models = builtinModels();
|
|
@@ -31,9 +70,9 @@ class LLMClient {
|
|
|
31
70
|
currentUser,
|
|
32
71
|
systemPrompt,
|
|
33
72
|
messages,
|
|
34
|
-
provider =
|
|
35
|
-
modelName =
|
|
36
|
-
temperature =
|
|
73
|
+
provider = DEFAULT_PROVIDER,
|
|
74
|
+
modelName = DEFAULT_MODEL,
|
|
75
|
+
temperature = DEFAULT_TEMPERATURE
|
|
37
76
|
} = params ?? {};
|
|
38
77
|
const model = models.getModel(provider, modelName);
|
|
39
78
|
if (!model) throw new Error("[LLM Client] model not found");
|
|
@@ -41,11 +80,31 @@ class LLMClient {
|
|
|
41
80
|
systemPrompt,
|
|
42
81
|
messages
|
|
43
82
|
};
|
|
83
|
+
return this.traced(
|
|
84
|
+
{ origin, sessionId, answerId, currentUser, modelName, provider, temperature },
|
|
85
|
+
context,
|
|
86
|
+
() => this.waitingOnRateLimit(() => models.complete(model, context, { temperature, maxRetries: MAX_RETRIES }))
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
async waitingOnRateLimit(run) {
|
|
90
|
+
let response = await run();
|
|
91
|
+
for (let waits = 0; waits < MAX_RATE_LIMIT_WAITS && response.stopReason === "error"; waits++) {
|
|
92
|
+
const delay = LLMError.fromProvider(response.errorMessage ?? "").code === "LLM_RATE_LIMITED" ? retryDelayMs(response.errorMessage) : void 0;
|
|
93
|
+
if (!delay) break;
|
|
94
|
+
this.logger.warn({ waitMs: delay }, "[LLM Service] Rate limited, waiting before retrying");
|
|
95
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
96
|
+
response = await run();
|
|
97
|
+
}
|
|
98
|
+
return response;
|
|
99
|
+
}
|
|
100
|
+
async traced(call, context, run) {
|
|
101
|
+
const { origin, sessionId, answerId, currentUser, modelName, provider, temperature } = call;
|
|
44
102
|
this.logger.debug({
|
|
45
103
|
origin,
|
|
46
104
|
context: {
|
|
47
105
|
...context,
|
|
48
|
-
|
|
106
|
+
...context.systemPrompt ? { systemPrompt: this.formatTextForLog(context.systemPrompt) } : {},
|
|
107
|
+
messages: this.formatMessagesForLog(context.messages)
|
|
49
108
|
}
|
|
50
109
|
}, "[LLM Service] context");
|
|
51
110
|
const trace = this.langfuseEnabled ? this.langfuse.trace({
|
|
@@ -65,9 +124,7 @@ class LLMClient {
|
|
|
65
124
|
input: context
|
|
66
125
|
});
|
|
67
126
|
try {
|
|
68
|
-
const response = await
|
|
69
|
-
temperature
|
|
70
|
-
});
|
|
127
|
+
const response = await run();
|
|
71
128
|
generation?.end({
|
|
72
129
|
output: response,
|
|
73
130
|
usage: response.usage ? {
|
|
@@ -110,19 +167,20 @@ class LLMClient {
|
|
|
110
167
|
}
|
|
111
168
|
formatContentForLog(records) {
|
|
112
169
|
return records?.map((record) => {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const isJson = Object.keys(extracted).length > 0;
|
|
116
|
-
return {
|
|
117
|
-
...record,
|
|
118
|
-
text: isJson ? extracted : text
|
|
119
|
-
};
|
|
170
|
+
if (record?.type !== "text") return record;
|
|
171
|
+
return { ...record, text: this.formatTextForLog(record?.text) };
|
|
120
172
|
});
|
|
121
173
|
}
|
|
174
|
+
formatTextForLog(text) {
|
|
175
|
+
if (typeof text !== "string") return text;
|
|
176
|
+
const extracted = extractJSON(text);
|
|
177
|
+
const isJson = extracted && Object.keys(extracted).length > 0;
|
|
178
|
+
return isJson ? extracted : text;
|
|
179
|
+
}
|
|
122
180
|
formatMessagesForLog(messages) {
|
|
123
181
|
return messages.map((message) => ({
|
|
124
182
|
...message,
|
|
125
|
-
content: this.formatContentForLog(message
|
|
183
|
+
content: Array.isArray(message?.content) ? this.formatContentForLog(message.content) : this.formatTextForLog(message?.content)
|
|
126
184
|
}));
|
|
127
185
|
}
|
|
128
186
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type LLMErrorCode = 'LLM_RATE_LIMITED' | 'LLM_QUOTA_EXCEEDED' | 'LLM_UNAVAILABLE' | 'LLM_FAILED';
|
|
2
|
+
export declare class LLMError extends Error {
|
|
3
|
+
readonly code: LLMErrorCode;
|
|
4
|
+
readonly isRetryable: boolean;
|
|
5
|
+
readonly userMessage: string;
|
|
6
|
+
constructor(code: LLMErrorCode, detail: string);
|
|
7
|
+
static fromProvider(detail: string): LLMError;
|
|
8
|
+
}
|
|
9
|
+
export declare function retryDelayMs(detail?: string): number | undefined;
|
|
@@ -0,0 +1,69 @@
|
|
|
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
|
+
var llm_error_exports = {};
|
|
20
|
+
__export(llm_error_exports, {
|
|
21
|
+
LLMError: () => LLMError,
|
|
22
|
+
retryDelayMs: () => retryDelayMs
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(llm_error_exports);
|
|
25
|
+
const USER_MESSAGES = {
|
|
26
|
+
LLM_RATE_LIMITED: "The model is receiving too many requests right now. Please try again in a few seconds.",
|
|
27
|
+
LLM_QUOTA_EXCEEDED: "The usage quota of the model provider has been exhausted. Please check the plan and billing of the provider.",
|
|
28
|
+
LLM_UNAVAILABLE: "The model provider is temporarily unavailable. Please try again in a moment.",
|
|
29
|
+
LLM_FAILED: "The model request failed. Please try again."
|
|
30
|
+
};
|
|
31
|
+
const RETRYABLE = {
|
|
32
|
+
LLM_RATE_LIMITED: true,
|
|
33
|
+
LLM_QUOTA_EXCEEDED: false,
|
|
34
|
+
LLM_UNAVAILABLE: true,
|
|
35
|
+
LLM_FAILED: true
|
|
36
|
+
};
|
|
37
|
+
const MAX_WAIT_MS = 6e4;
|
|
38
|
+
class LLMError extends Error {
|
|
39
|
+
code;
|
|
40
|
+
isRetryable;
|
|
41
|
+
userMessage;
|
|
42
|
+
constructor(code, detail) {
|
|
43
|
+
super(`[LLM Client] ${detail}`);
|
|
44
|
+
this.code = code;
|
|
45
|
+
this.isRetryable = RETRYABLE[code];
|
|
46
|
+
this.userMessage = USER_MESSAGES[code];
|
|
47
|
+
}
|
|
48
|
+
static fromProvider(detail) {
|
|
49
|
+
return new LLMError(classify(detail), detail);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function classify(detail) {
|
|
53
|
+
if (/PerDay|per day|billing|insufficient_quota|exceeded your current quota[\s\S]*(daily|day)/i.test(detail) && !/per.?min/i.test(detail)) return "LLM_QUOTA_EXCEEDED";
|
|
54
|
+
if (/\b429\b|rate.?limit|RESOURCE_EXHAUSTED|too many requests/i.test(detail)) return "LLM_RATE_LIMITED";
|
|
55
|
+
if (/\b50[0-9]\b|unavailable|overloaded|timeout|timed out|econn|network/i.test(detail)) return "LLM_UNAVAILABLE";
|
|
56
|
+
return "LLM_FAILED";
|
|
57
|
+
}
|
|
58
|
+
function retryDelayMs(detail) {
|
|
59
|
+
if (!detail) return void 0;
|
|
60
|
+
const match = detail.match(/"retryDelay\\*"\s*:\s*\\*"(\d+(?:\.\d+)?)s/) ?? detail.match(/retry in (\d+(?:\.\d+)?)s/i);
|
|
61
|
+
if (!match) return void 0;
|
|
62
|
+
const ms = Math.ceil(Number(match[1]) * 1e3) + 1e3;
|
|
63
|
+
return ms <= MAX_WAIT_MS ? ms : void 0;
|
|
64
|
+
}
|
|
65
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
66
|
+
0 && (module.exports = {
|
|
67
|
+
LLMError,
|
|
68
|
+
retryDelayMs
|
|
69
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import "../chunk-CF3WOMB3.mjs";
|
|
2
|
+
const USER_MESSAGES = {
|
|
3
|
+
LLM_RATE_LIMITED: "The model is receiving too many requests right now. Please try again in a few seconds.",
|
|
4
|
+
LLM_QUOTA_EXCEEDED: "The usage quota of the model provider has been exhausted. Please check the plan and billing of the provider.",
|
|
5
|
+
LLM_UNAVAILABLE: "The model provider is temporarily unavailable. Please try again in a moment.",
|
|
6
|
+
LLM_FAILED: "The model request failed. Please try again."
|
|
7
|
+
};
|
|
8
|
+
const RETRYABLE = {
|
|
9
|
+
LLM_RATE_LIMITED: true,
|
|
10
|
+
LLM_QUOTA_EXCEEDED: false,
|
|
11
|
+
LLM_UNAVAILABLE: true,
|
|
12
|
+
LLM_FAILED: true
|
|
13
|
+
};
|
|
14
|
+
const MAX_WAIT_MS = 6e4;
|
|
15
|
+
class LLMError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
isRetryable;
|
|
18
|
+
userMessage;
|
|
19
|
+
constructor(code, detail) {
|
|
20
|
+
super(`[LLM Client] ${detail}`);
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.isRetryable = RETRYABLE[code];
|
|
23
|
+
this.userMessage = USER_MESSAGES[code];
|
|
24
|
+
}
|
|
25
|
+
static fromProvider(detail) {
|
|
26
|
+
return new LLMError(classify(detail), detail);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function classify(detail) {
|
|
30
|
+
if (/PerDay|per day|billing|insufficient_quota|exceeded your current quota[\s\S]*(daily|day)/i.test(detail) && !/per.?min/i.test(detail)) return "LLM_QUOTA_EXCEEDED";
|
|
31
|
+
if (/\b429\b|rate.?limit|RESOURCE_EXHAUSTED|too many requests/i.test(detail)) return "LLM_RATE_LIMITED";
|
|
32
|
+
if (/\b50[0-9]\b|unavailable|overloaded|timeout|timed out|econn|network/i.test(detail)) return "LLM_UNAVAILABLE";
|
|
33
|
+
return "LLM_FAILED";
|
|
34
|
+
}
|
|
35
|
+
function retryDelayMs(detail) {
|
|
36
|
+
if (!detail) return void 0;
|
|
37
|
+
const match = detail.match(/"retryDelay\\*"\s*:\s*\\*"(\d+(?:\.\d+)?)s/) ?? detail.match(/retry in (\d+(?:\.\d+)?)s/i);
|
|
38
|
+
if (!match) return void 0;
|
|
39
|
+
const ms = Math.ceil(Number(match[1]) * 1e3) + 1e3;
|
|
40
|
+
return ms <= MAX_WAIT_MS ? ms : void 0;
|
|
41
|
+
}
|
|
42
|
+
export {
|
|
43
|
+
LLMError,
|
|
44
|
+
retryDelayMs
|
|
45
|
+
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { CurrentUser } from '../common/base/index.js';
|
|
2
|
+
export interface LLMToolCall {
|
|
3
|
+
id: string;
|
|
4
|
+
name: string;
|
|
5
|
+
arguments: Record<string, any>;
|
|
6
|
+
}
|
|
7
|
+
export interface LLMToolDefinition {
|
|
8
|
+
name: string;
|
|
9
|
+
description: string;
|
|
10
|
+
parameters: Record<string, any>;
|
|
11
|
+
}
|
|
12
|
+
export type LLMMessage = {
|
|
13
|
+
role: 'system';
|
|
14
|
+
content: string;
|
|
15
|
+
} | {
|
|
16
|
+
role: 'user';
|
|
17
|
+
content: string;
|
|
18
|
+
} | {
|
|
19
|
+
role: 'assistant';
|
|
20
|
+
content: string;
|
|
21
|
+
toolCalls?: LLMToolCall[];
|
|
22
|
+
native?: unknown;
|
|
23
|
+
} | {
|
|
24
|
+
role: 'tool';
|
|
25
|
+
toolCallId: string;
|
|
26
|
+
toolName: string;
|
|
27
|
+
content: string;
|
|
28
|
+
isError?: boolean;
|
|
29
|
+
};
|
|
30
|
+
export type LLMStopReason = 'stop' | 'length' | 'tool_use' | 'error' | 'aborted';
|
|
31
|
+
export interface LLMUsage {
|
|
32
|
+
input: number;
|
|
33
|
+
output: number;
|
|
34
|
+
cacheRead: number;
|
|
35
|
+
cacheWrite: number;
|
|
36
|
+
totalTokens: number;
|
|
37
|
+
costInUsd: number;
|
|
38
|
+
}
|
|
39
|
+
export interface LLMResponse {
|
|
40
|
+
text: string;
|
|
41
|
+
toolCalls: LLMToolCall[];
|
|
42
|
+
stopReason: LLMStopReason;
|
|
43
|
+
usage: LLMUsage;
|
|
44
|
+
responseId?: string;
|
|
45
|
+
model?: string;
|
|
46
|
+
errorMessage?: string;
|
|
47
|
+
native?: unknown;
|
|
48
|
+
}
|
|
49
|
+
export type LLMToolChoice = 'auto' | 'none';
|
|
50
|
+
export interface LLMChatParams {
|
|
51
|
+
origin: string;
|
|
52
|
+
sessionId: string;
|
|
53
|
+
answerId: string;
|
|
54
|
+
currentUser?: CurrentUser;
|
|
55
|
+
messages: LLMMessage[];
|
|
56
|
+
tools?: LLMToolDefinition[];
|
|
57
|
+
toolChoice?: LLMToolChoice;
|
|
58
|
+
provider?: string;
|
|
59
|
+
modelName?: string;
|
|
60
|
+
temperature?: number;
|
|
61
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
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 __copyProps = (to, from, except, desc) => {
|
|
7
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
|
+
for (let key of __getOwnPropNames(from))
|
|
9
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
10
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
11
|
+
}
|
|
12
|
+
return to;
|
|
13
|
+
};
|
|
14
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
15
|
+
var llm_types_exports = {};
|
|
16
|
+
module.exports = __toCommonJS(llm_types_exports);
|
|
File without changes
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Api, AssistantMessage, Context, Model } from '@earendil-works/pi-ai';
|
|
2
|
+
import type { LLMMessage, LLMResponse, LLMToolDefinition } from './llm-types';
|
|
3
|
+
export declare function toPiContext(input: {
|
|
4
|
+
messages: LLMMessage[];
|
|
5
|
+
tools?: LLMToolDefinition[];
|
|
6
|
+
}, model: Model<Api>): Context;
|
|
7
|
+
export declare function fromPiMessage(message: AssistantMessage): LLMResponse;
|
|
@@ -0,0 +1,137 @@
|
|
|
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
|
+
var pi_ai_adapter_exports = {};
|
|
20
|
+
__export(pi_ai_adapter_exports, {
|
|
21
|
+
fromPiMessage: () => fromPiMessage,
|
|
22
|
+
toPiContext: () => toPiContext
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(pi_ai_adapter_exports);
|
|
25
|
+
const ZERO_USAGE = {
|
|
26
|
+
input: 0,
|
|
27
|
+
output: 0,
|
|
28
|
+
cacheRead: 0,
|
|
29
|
+
cacheWrite: 0,
|
|
30
|
+
totalTokens: 0,
|
|
31
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
32
|
+
};
|
|
33
|
+
function isPiAssistant(value) {
|
|
34
|
+
return Boolean(value) && value.role === "assistant" && Array.isArray(value.content);
|
|
35
|
+
}
|
|
36
|
+
function toPiTool(tool) {
|
|
37
|
+
return { name: tool.name, description: tool.description, parameters: tool.parameters };
|
|
38
|
+
}
|
|
39
|
+
function toPiContext(input, model) {
|
|
40
|
+
const leading = [];
|
|
41
|
+
const messages = [];
|
|
42
|
+
let seenConversation = false;
|
|
43
|
+
for (const message of input.messages) {
|
|
44
|
+
const timestamp = Date.now();
|
|
45
|
+
switch (message.role) {
|
|
46
|
+
case "system":
|
|
47
|
+
if (!seenConversation) leading.push(message.content);
|
|
48
|
+
else messages.push({ role: "system", content: message.content, timestamp });
|
|
49
|
+
break;
|
|
50
|
+
case "user":
|
|
51
|
+
seenConversation = true;
|
|
52
|
+
messages.push({ role: "user", content: message.content, timestamp });
|
|
53
|
+
break;
|
|
54
|
+
case "assistant": {
|
|
55
|
+
seenConversation = true;
|
|
56
|
+
if (isPiAssistant(message.native)) {
|
|
57
|
+
messages.push(message.native);
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
const content = [];
|
|
61
|
+
if (message.content) content.push({ type: "text", text: message.content });
|
|
62
|
+
for (const call of message.toolCalls ?? []) content.push({ type: "toolCall", id: call.id, name: call.name, arguments: call.arguments });
|
|
63
|
+
messages.push({
|
|
64
|
+
role: "assistant",
|
|
65
|
+
content,
|
|
66
|
+
api: model.api,
|
|
67
|
+
provider: model.provider,
|
|
68
|
+
model: model.id,
|
|
69
|
+
usage: ZERO_USAGE,
|
|
70
|
+
stopReason: message.toolCalls?.length ? "toolUse" : "stop",
|
|
71
|
+
timestamp
|
|
72
|
+
});
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
case "tool":
|
|
76
|
+
seenConversation = true;
|
|
77
|
+
messages.push({
|
|
78
|
+
role: "toolResult",
|
|
79
|
+
toolCallId: message.toolCallId,
|
|
80
|
+
toolName: message.toolName,
|
|
81
|
+
content: [{ type: "text", text: message.content }],
|
|
82
|
+
isError: Boolean(message.isError),
|
|
83
|
+
timestamp
|
|
84
|
+
});
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
...leading.length ? { systemPrompt: leading.join("\n\n") } : {},
|
|
90
|
+
messages,
|
|
91
|
+
...input.tools?.length ? { tools: input.tools.map(toPiTool) } : {}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function mapStopReason(reason) {
|
|
95
|
+
switch (reason) {
|
|
96
|
+
case "toolUse":
|
|
97
|
+
return "tool_use";
|
|
98
|
+
case "length":
|
|
99
|
+
return "length";
|
|
100
|
+
case "error":
|
|
101
|
+
return "error";
|
|
102
|
+
case "aborted":
|
|
103
|
+
return "aborted";
|
|
104
|
+
default:
|
|
105
|
+
return "stop";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function fromPiMessage(message) {
|
|
109
|
+
const text = message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
|
|
110
|
+
const toolCalls = message.content.filter((block) => block.type === "toolCall").map((block) => {
|
|
111
|
+
const call = block;
|
|
112
|
+
return { id: call.id, name: call.name, arguments: call.arguments ?? {} };
|
|
113
|
+
});
|
|
114
|
+
const usage = message.usage;
|
|
115
|
+
return {
|
|
116
|
+
text,
|
|
117
|
+
toolCalls,
|
|
118
|
+
stopReason: mapStopReason(message.stopReason),
|
|
119
|
+
usage: {
|
|
120
|
+
input: usage?.input ?? 0,
|
|
121
|
+
output: usage?.output ?? 0,
|
|
122
|
+
cacheRead: usage?.cacheRead ?? 0,
|
|
123
|
+
cacheWrite: usage?.cacheWrite ?? 0,
|
|
124
|
+
totalTokens: usage?.totalTokens ?? 0,
|
|
125
|
+
costInUsd: usage?.cost?.total ?? 0
|
|
126
|
+
},
|
|
127
|
+
responseId: message.responseId,
|
|
128
|
+
model: message.model,
|
|
129
|
+
errorMessage: message.errorMessage,
|
|
130
|
+
native: message
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
134
|
+
0 && (module.exports = {
|
|
135
|
+
fromPiMessage,
|
|
136
|
+
toPiContext
|
|
137
|
+
});
|