coaiajs 0.1.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/CLAUDE.md +56 -0
- package/KINSHIP.md +63 -0
- package/README.md +148 -0
- package/articles/academic/creative-orientation-vs-problem-solving.md +177 -0
- package/articles/academic/jsonl-knowledge-graphs-agent-memory.md +142 -0
- package/articles/academic/langfuse-observability-llm-pipelines.md +144 -0
- package/articles/academic/medicine-wheel-software-architecture.md +163 -0
- package/articles/academic/mmot-autonomous-agents.md +156 -0
- package/articles/academic/model-context-protocol-interagent.md +161 -0
- package/articles/academic/pde-prompt-decomposition.md +186 -0
- package/articles/academic/structural-tension-in-ai-agents.md +134 -0
- package/articles/reviews/mcp-protocol-design-review.md +170 -0
- package/articles/reviews/observability-ai-systems-review.md +176 -0
- package/articles/reviews/prompt-engineering-decomposition-review.md +184 -0
- package/articles/surveys/agent-orchestration-survey.md +186 -0
- package/articles/surveys/knowledge-graph-storage-survey.md +204 -0
- package/articles/surveys/structural-tension-methodology-survey.md +154 -0
- package/articles/technical/aws-sdk-v3-polly.md +270 -0
- package/articles/technical/commander-cli-framework.md +262 -0
- package/articles/technical/dotenv-config-patterns.md +360 -0
- package/articles/technical/ioredis-vs-redis.md +142 -0
- package/articles/technical/langfuse-js-sdk-vs-rest.md +191 -0
- package/articles/technical/mcp-sdk-typescript.md +291 -0
- package/articles/technical/octokit-github-api.md +293 -0
- package/articles/technical/openai-sdk-modern.md +231 -0
- package/articles/technical/yaml-parsing-node.md +266 -0
- package/articles/technical/zod-runtime-validation.md +212 -0
- package/dist/mcp/config.d.ts +14 -0
- package/dist/mcp/config.js +185 -0
- package/dist/mcp/server.d.ts +3 -0
- package/dist/mcp/server.js +324 -0
- package/dist/mcp/tools/coaiapy-tools.d.ts +8 -0
- package/dist/mcp/tools/coaiapy-tools.js +326 -0
- package/dist/mcp/tools/index.d.ts +3 -0
- package/dist/mcp/tools/index.js +3 -0
- package/dist/src/audio.d.ts +12 -0
- package/dist/src/audio.js +57 -0
- package/dist/src/cli-helpers.d.ts +9 -0
- package/dist/src/cli-helpers.js +78 -0
- package/dist/src/cli.d.ts +3 -0
- package/dist/src/cli.js +1086 -0
- package/dist/src/config.d.ts +15 -0
- package/dist/src/config.js +145 -0
- package/dist/src/environment.d.ts +44 -0
- package/dist/src/environment.js +146 -0
- package/dist/src/github.d.ts +47 -0
- package/dist/src/github.js +79 -0
- package/dist/src/langfuse/client.d.ts +30 -0
- package/dist/src/langfuse/client.js +75 -0
- package/dist/src/langfuse/comments.d.ts +16 -0
- package/dist/src/langfuse/comments.js +36 -0
- package/dist/src/langfuse/datasets.d.ts +19 -0
- package/dist/src/langfuse/datasets.js +140 -0
- package/dist/src/langfuse/index.d.ts +13 -0
- package/dist/src/langfuse/index.js +10 -0
- package/dist/src/langfuse/media.d.ts +11 -0
- package/dist/src/langfuse/media.js +167 -0
- package/dist/src/langfuse/observations.d.ts +18 -0
- package/dist/src/langfuse/observations.js +113 -0
- package/dist/src/langfuse/prompts.d.ts +14 -0
- package/dist/src/langfuse/prompts.js +127 -0
- package/dist/src/langfuse/scores.d.ts +54 -0
- package/dist/src/langfuse/scores.js +366 -0
- package/dist/src/langfuse/traces.d.ts +29 -0
- package/dist/src/langfuse/traces.js +225 -0
- package/dist/src/llm.d.ts +23 -0
- package/dist/src/llm.js +76 -0
- package/dist/src/narrative/graph-manager.d.ts +106 -0
- package/dist/src/narrative/graph-manager.js +915 -0
- package/dist/src/narrative/index.d.ts +9 -0
- package/dist/src/narrative/index.js +7 -0
- package/dist/src/narrative/markdown-export.d.ts +21 -0
- package/dist/src/narrative/markdown-export.js +383 -0
- package/dist/src/narrative/tool-definitions.d.ts +21 -0
- package/dist/src/narrative/tool-definitions.js +588 -0
- package/dist/src/narrative/tool-handlers.d.ts +11 -0
- package/dist/src/narrative/tool-handlers.js +462 -0
- package/dist/src/narrative/types.d.ts +2 -0
- package/dist/src/narrative/types.js +2 -0
- package/dist/src/narrative/validation.d.ts +29 -0
- package/dist/src/narrative/validation.js +144 -0
- package/dist/src/pde/index.d.ts +8 -0
- package/dist/src/pde/index.js +8 -0
- package/dist/src/pde/mcp-handlers.d.ts +7 -0
- package/dist/src/pde/mcp-handlers.js +300 -0
- package/dist/src/pde/mcp-tools.d.ts +15 -0
- package/dist/src/pde/mcp-tools.js +191 -0
- package/dist/src/pde/session-manager.d.ts +32 -0
- package/dist/src/pde/session-manager.js +205 -0
- package/dist/src/pde/stc-mapper.d.ts +26 -0
- package/dist/src/pde/stc-mapper.js +234 -0
- package/dist/src/pipeline/index.d.ts +2 -0
- package/dist/src/pipeline/index.js +3 -0
- package/dist/src/pipeline/template-engine.d.ts +20 -0
- package/dist/src/pipeline/template-engine.js +361 -0
- package/dist/src/planning/index.d.ts +7 -0
- package/dist/src/planning/index.js +7 -0
- package/dist/src/planning/mcp-handlers.d.ts +7 -0
- package/dist/src/planning/mcp-handlers.js +310 -0
- package/dist/src/planning/mcp-tools.d.ts +15 -0
- package/dist/src/planning/mcp-tools.js +145 -0
- package/dist/src/planning/plan-parser.d.ts +35 -0
- package/dist/src/planning/plan-parser.js +506 -0
- package/dist/src/redis.d.ts +21 -0
- package/dist/src/redis.js +78 -0
- package/dist/src/types.d.ts +244 -0
- package/dist/src/types.js +8 -0
- package/mcp/config.ts +196 -0
- package/mcp/server.ts +402 -0
- package/mcp/tools/coaiapy-tools.ts +364 -0
- package/mcp/tools/index.ts +4 -0
- package/package.json +52 -0
- package/rispecs/00-coaiajs-platform.spec.md +102 -0
- package/rispecs/01-core-config.spec.md +89 -0
- package/rispecs/02-redis-module.spec.md +62 -0
- package/rispecs/03-langfuse-module.spec.md +101 -0
- package/rispecs/04-narrative-engine.spec.md +185 -0
- package/rispecs/05-pde-engine.spec.md +112 -0
- package/rispecs/06-planning-engine.spec.md +128 -0
- package/rispecs/07-pipeline-templates.spec.md +97 -0
- package/rispecs/08-cli-interface.spec.md +134 -0
- package/rispecs/09-mcp-server.spec.md +140 -0
- package/rispecs/10-audio-module.spec.md +63 -0
- package/rispecs/KINSHIP.md +56 -0
- package/rispecs/README.md +100 -0
- package/src/audio.ts +76 -0
- package/src/cli-helpers.ts +86 -0
- package/src/cli.ts +1223 -0
- package/src/config.ts +172 -0
- package/src/environment.ts +171 -0
- package/src/github.ts +143 -0
- package/src/langfuse/client.ts +105 -0
- package/src/langfuse/comments.ts +52 -0
- package/src/langfuse/datasets.ts +178 -0
- package/src/langfuse/index.ts +33 -0
- package/src/langfuse/media.ts +193 -0
- package/src/langfuse/observations.ts +131 -0
- package/src/langfuse/prompts.ts +157 -0
- package/src/langfuse/scores.ts +456 -0
- package/src/langfuse/traces.ts +276 -0
- package/src/llm.ts +106 -0
- package/src/narrative/graph-manager.ts +1358 -0
- package/src/narrative/index.ts +32 -0
- package/src/narrative/markdown-export.ts +535 -0
- package/src/narrative/tool-definitions.ts +635 -0
- package/src/narrative/tool-handlers.ts +528 -0
- package/src/narrative/types.ts +9 -0
- package/src/narrative/validation.ts +179 -0
- package/src/pde/index.ts +8 -0
- package/src/pde/mcp-handlers.ts +359 -0
- package/src/pde/mcp-tools.ts +201 -0
- package/src/pde/session-manager.ts +248 -0
- package/src/pde/stc-mapper.ts +298 -0
- package/src/pipeline/index.ts +7 -0
- package/src/pipeline/template-engine.ts +398 -0
- package/src/planning/index.ts +13 -0
- package/src/planning/mcp-handlers.ts +369 -0
- package/src/planning/mcp-tools.ts +155 -0
- package/src/planning/plan-parser.ts +587 -0
- package/src/redis.ts +97 -0
- package/src/types.ts +280 -0
- package/tsconfig.json +26 -0
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// coaiajs/src/langfuse/traces.ts — Trace operations
|
|
2
|
+
// Port of cofuse.py trace functions
|
|
3
|
+
|
|
4
|
+
import { v4 as uuidv4 } from 'uuid';
|
|
5
|
+
import { getClient, nowISO } from './client.js';
|
|
6
|
+
import type { IngestionEvent } from './client.js';
|
|
7
|
+
|
|
8
|
+
export interface TraceFilters {
|
|
9
|
+
sessionId?: string;
|
|
10
|
+
userId?: string;
|
|
11
|
+
name?: string;
|
|
12
|
+
tags?: string[];
|
|
13
|
+
fromTimestamp?: string;
|
|
14
|
+
toTimestamp?: string;
|
|
15
|
+
orderBy?: string;
|
|
16
|
+
version?: string;
|
|
17
|
+
release?: string;
|
|
18
|
+
environment?: string[];
|
|
19
|
+
page?: number;
|
|
20
|
+
limit?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function addTrace(params: {
|
|
24
|
+
traceId?: string;
|
|
25
|
+
userId?: string;
|
|
26
|
+
sessionId?: string;
|
|
27
|
+
name?: string;
|
|
28
|
+
inputData?: unknown;
|
|
29
|
+
outputData?: unknown;
|
|
30
|
+
metadata?: unknown;
|
|
31
|
+
}): Promise<string> {
|
|
32
|
+
const client = getClient();
|
|
33
|
+
const now = nowISO();
|
|
34
|
+
const traceId = params.traceId ?? uuidv4();
|
|
35
|
+
|
|
36
|
+
const body: Record<string, unknown> = {
|
|
37
|
+
id: traceId,
|
|
38
|
+
timestamp: now,
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
if (params.sessionId) body.sessionId = params.sessionId;
|
|
42
|
+
if (params.name) body.name = params.name;
|
|
43
|
+
if (params.inputData) body.input = params.inputData;
|
|
44
|
+
if (params.outputData) body.output = params.outputData;
|
|
45
|
+
if (params.userId) body.userId = params.userId;
|
|
46
|
+
if (params.metadata) body.metadata = params.metadata;
|
|
47
|
+
|
|
48
|
+
const event: IngestionEvent = {
|
|
49
|
+
id: `${traceId}-event`,
|
|
50
|
+
timestamp: now,
|
|
51
|
+
type: 'trace-create',
|
|
52
|
+
body,
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
await client.ingest([event]);
|
|
56
|
+
|
|
57
|
+
return JSON.stringify({
|
|
58
|
+
success: true,
|
|
59
|
+
traceId,
|
|
60
|
+
message: `Trace ${traceId} created`,
|
|
61
|
+
}, null, 2);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function patchTraceOutput(traceId: string, outputData: unknown): Promise<string> {
|
|
65
|
+
const client = getClient();
|
|
66
|
+
const now = nowISO();
|
|
67
|
+
|
|
68
|
+
const body: Record<string, unknown> = {
|
|
69
|
+
id: traceId,
|
|
70
|
+
timestamp: now,
|
|
71
|
+
output: outputData,
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const eventId = `${traceId}-patch-${uuidv4().slice(0, 8)}`;
|
|
75
|
+
const event: IngestionEvent = {
|
|
76
|
+
id: eventId,
|
|
77
|
+
timestamp: now,
|
|
78
|
+
type: 'trace-create',
|
|
79
|
+
body,
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
await client.ingest([event]);
|
|
83
|
+
|
|
84
|
+
return JSON.stringify({
|
|
85
|
+
success: true,
|
|
86
|
+
traceId,
|
|
87
|
+
message: `Trace output patched for ${traceId}`,
|
|
88
|
+
}, null, 2);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function listTraces(filters: TraceFilters): Promise<string> {
|
|
92
|
+
const client = getClient();
|
|
93
|
+
const params = new URLSearchParams();
|
|
94
|
+
|
|
95
|
+
if (filters.sessionId) params.set('sessionId', filters.sessionId);
|
|
96
|
+
if (filters.userId) params.set('userId', filters.userId);
|
|
97
|
+
if (filters.name) params.set('name', filters.name);
|
|
98
|
+
if (filters.fromTimestamp) params.set('fromTimestamp', filters.fromTimestamp);
|
|
99
|
+
if (filters.toTimestamp) params.set('toTimestamp', filters.toTimestamp);
|
|
100
|
+
if (filters.orderBy) params.set('orderBy', filters.orderBy);
|
|
101
|
+
if (filters.version) params.set('version', filters.version);
|
|
102
|
+
if (filters.release) params.set('release', filters.release);
|
|
103
|
+
if (filters.tags) {
|
|
104
|
+
for (const tag of filters.tags) params.append('tags', tag);
|
|
105
|
+
}
|
|
106
|
+
if (filters.environment) {
|
|
107
|
+
for (const env of filters.environment) params.append('environment', env);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const page = filters.page ?? 1;
|
|
111
|
+
const limit = filters.limit ?? 50;
|
|
112
|
+
params.set('page', String(page));
|
|
113
|
+
params.set('limit', String(limit));
|
|
114
|
+
|
|
115
|
+
const qs = params.toString();
|
|
116
|
+
const path = `/api/public/traces${qs ? `?${qs}` : ''}`;
|
|
117
|
+
const result = await client.request<unknown>('GET', path);
|
|
118
|
+
return JSON.stringify(result, null, 2);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function getTrace(traceId: string): Promise<string> {
|
|
122
|
+
const client = getClient();
|
|
123
|
+
|
|
124
|
+
const trace = await client.request<Record<string, unknown>>('GET', `/api/public/traces/${traceId}`);
|
|
125
|
+
|
|
126
|
+
// Fetch observations for this trace
|
|
127
|
+
try {
|
|
128
|
+
const obsResult = await client.request<Record<string, unknown>>(
|
|
129
|
+
'GET',
|
|
130
|
+
`/api/public/observations?traceId=${traceId}`,
|
|
131
|
+
);
|
|
132
|
+
if (obsResult && typeof obsResult === 'object' && 'data' in obsResult) {
|
|
133
|
+
trace.observations = obsResult.data;
|
|
134
|
+
} else {
|
|
135
|
+
trace.observations = obsResult;
|
|
136
|
+
}
|
|
137
|
+
} catch {
|
|
138
|
+
trace.observations = [];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return JSON.stringify(trace, null, 2);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ─── Formatters ─────────────────────────────────────────────────────
|
|
145
|
+
|
|
146
|
+
export function formatTracesTable(json: unknown): string {
|
|
147
|
+
try {
|
|
148
|
+
const data = typeof json === 'string' ? JSON.parse(json) : json;
|
|
149
|
+
const traces: Record<string, unknown>[] = Array.isArray(data)
|
|
150
|
+
? data
|
|
151
|
+
: (data as Record<string, unknown>).data as Record<string, unknown>[] ?? [];
|
|
152
|
+
|
|
153
|
+
if (!traces.length) return 'No traces found.';
|
|
154
|
+
|
|
155
|
+
const headers = ['ID', 'Name', 'Session', 'User', 'Time'];
|
|
156
|
+
const rows = traces.map((t) => [
|
|
157
|
+
trunc(String(t.id ?? 'N/A'), 20),
|
|
158
|
+
trunc(String(t.name ?? 'Unnamed'), 20),
|
|
159
|
+
trunc(String(t.sessionId ?? 'N/A'), 15),
|
|
160
|
+
trunc(String(t.userId ?? 'N/A'), 12),
|
|
161
|
+
trunc(String(t.timestamp ?? 'N/A').slice(0, 19), 19),
|
|
162
|
+
]);
|
|
163
|
+
|
|
164
|
+
return formatTable(headers, rows) + `\nTotal traces: ${traces.length}`;
|
|
165
|
+
} catch (e) {
|
|
166
|
+
return `Error formatting traces: ${e}`;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const TYPE_GLYPHS: Record<string, string> = {
|
|
171
|
+
SPAN: '🔗',
|
|
172
|
+
GENERATION: '🤖',
|
|
173
|
+
EVENT: '⚡',
|
|
174
|
+
SCORE: '📊',
|
|
175
|
+
TRACE: '🛤️',
|
|
176
|
+
DEFAULT: '📦',
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
export function formatTraceTree(json: unknown): string {
|
|
180
|
+
try {
|
|
181
|
+
const trace = (typeof json === 'string' ? JSON.parse(json) : json) as Record<string, unknown>;
|
|
182
|
+
if ('error' in trace) return `Error: ${trace.error}`;
|
|
183
|
+
|
|
184
|
+
const BRANCH = '├── ';
|
|
185
|
+
const LAST = '└── ';
|
|
186
|
+
const VERT = '│ ';
|
|
187
|
+
const SPACE = ' ';
|
|
188
|
+
|
|
189
|
+
const lines: string[] = [];
|
|
190
|
+
const name = String(trace.name ?? 'Unnamed');
|
|
191
|
+
const id = String(trace.id ?? 'N/A');
|
|
192
|
+
const userId = String(trace.userId ?? 'N/A');
|
|
193
|
+
const sessionId = String(trace.sessionId ?? 'N/A');
|
|
194
|
+
const ts = String(trace.timestamp ?? 'N/A').slice(0, 19);
|
|
195
|
+
|
|
196
|
+
lines.push(`🔗 Trace: ${name}`);
|
|
197
|
+
lines.push(`${BRANCH}🆔 ID: ${id}`);
|
|
198
|
+
lines.push(`${BRANCH}👤 User: ${userId}`);
|
|
199
|
+
lines.push(`${BRANCH}🔗 Session: ${sessionId}`);
|
|
200
|
+
lines.push(`${BRANCH}⏰ Time: ${ts}`);
|
|
201
|
+
|
|
202
|
+
const metadata = trace.metadata as Record<string, unknown> | undefined;
|
|
203
|
+
if (metadata && typeof metadata === 'object' && Object.keys(metadata).length) {
|
|
204
|
+
lines.push(`${BRANCH}📋 Metadata:`);
|
|
205
|
+
const entries = Object.entries(metadata);
|
|
206
|
+
entries.forEach(([k, v], i) => {
|
|
207
|
+
const pre = i === entries.length - 1 ? LAST : BRANCH;
|
|
208
|
+
lines.push(`${VERT}${pre}${k}: ${v}`);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const observations = (trace.observations ?? []) as Record<string, unknown>[];
|
|
213
|
+
if (!observations.length) {
|
|
214
|
+
lines.push(`${LAST}📝 No observations`);
|
|
215
|
+
return lines.join('\n');
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
lines.push(`${LAST}📝 Observations (${observations.length}):`);
|
|
219
|
+
|
|
220
|
+
const roots = observations.filter((o) => !o.parentObservationId);
|
|
221
|
+
|
|
222
|
+
function addTree(list: Record<string, unknown>[], prefix: string) {
|
|
223
|
+
list.forEach((obs, i) => {
|
|
224
|
+
const isLast = i === list.length - 1;
|
|
225
|
+
const obsName = String(obs.name ?? `Obs ${String(obs.id ?? '').slice(0, 8)}`);
|
|
226
|
+
const obsType = String(obs.type ?? 'UNKNOWN').toUpperCase();
|
|
227
|
+
const obsTime = String(obs.startTime ?? 'N/A').slice(0, 19);
|
|
228
|
+
const glyph = TYPE_GLYPHS[obsType] ?? TYPE_GLYPHS.DEFAULT;
|
|
229
|
+
|
|
230
|
+
const sym = isLast ? LAST : BRANCH;
|
|
231
|
+
const np = prefix + (isLast ? SPACE : VERT);
|
|
232
|
+
|
|
233
|
+
lines.push(`${prefix}${sym}${glyph} [${obsType}] ${obsName} (${obs.id})`);
|
|
234
|
+
lines.push(`${np}${BRANCH}⏰ ${obsTime}`);
|
|
235
|
+
|
|
236
|
+
if (obs.input) {
|
|
237
|
+
const txt = trunc(String(obs.input).replace(/\n/g, ' '), 90);
|
|
238
|
+
lines.push(`${np}${BRANCH}📥 Input: ${txt}`);
|
|
239
|
+
}
|
|
240
|
+
if (obs.output) {
|
|
241
|
+
const txt = trunc(String(obs.output).replace(/\n/g, ' '), 90);
|
|
242
|
+
lines.push(`${np}${LAST}📤 Output: ${txt}`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const children = observations.filter((c) => c.parentObservationId === obs.id);
|
|
246
|
+
if (children.length) {
|
|
247
|
+
lines.push(`${np}${LAST}🌿 Children (${children.length}):`);
|
|
248
|
+
addTree(children, np + SPACE);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
addTree(roots, SPACE);
|
|
254
|
+
return lines.join('\n');
|
|
255
|
+
} catch (e) {
|
|
256
|
+
return `Error formatting trace tree: ${e}`;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ─── Helpers ────────────────────────────────────────────────────────
|
|
261
|
+
|
|
262
|
+
function trunc(s: string, len: number): string {
|
|
263
|
+
return s.length > len ? s.slice(0, len - 3) + '...' : s;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function formatTable(headers: string[], rows: string[][]): string {
|
|
267
|
+
const widths = headers.map((h, i) =>
|
|
268
|
+
Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),
|
|
269
|
+
);
|
|
270
|
+
const sep = '+' + widths.map((w) => '-'.repeat(w + 2)).join('+') + '+';
|
|
271
|
+
const hdr = '| ' + headers.map((h, i) => h.padEnd(widths[i])).join(' | ') + ' |';
|
|
272
|
+
const body = rows.map(
|
|
273
|
+
(r) => '| ' + r.map((c, i) => (c ?? '').padEnd(widths[i])).join(' | ') + ' |',
|
|
274
|
+
);
|
|
275
|
+
return [sep, hdr, sep, ...body, sep].join('\n');
|
|
276
|
+
}
|
package/src/llm.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// coaiajs/src/llm.ts — LLM module
|
|
2
|
+
// Parity with coaiapy's OpenAI functions
|
|
3
|
+
|
|
4
|
+
import OpenAI from 'openai';
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { getConfig } from './config.js';
|
|
7
|
+
|
|
8
|
+
let _client: OpenAI | null = null;
|
|
9
|
+
|
|
10
|
+
function getClient(): OpenAI {
|
|
11
|
+
if (!_client) {
|
|
12
|
+
const cfg = getConfig();
|
|
13
|
+
_client = new OpenAI({
|
|
14
|
+
apiKey: cfg.openai?.apiKey ?? process.env['OPENAI_API_KEY'],
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return _client;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Reset client (testing). */
|
|
21
|
+
export function resetClient(): void {
|
|
22
|
+
_client = null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Send a chat completion request.
|
|
27
|
+
* Minimal wrapper matching coaiapy's `llm()` function.
|
|
28
|
+
*/
|
|
29
|
+
export async function llm(
|
|
30
|
+
user: string,
|
|
31
|
+
system?: string,
|
|
32
|
+
temperature?: number,
|
|
33
|
+
): Promise<string> {
|
|
34
|
+
const client = getClient();
|
|
35
|
+
const cfg = getConfig();
|
|
36
|
+
const model = cfg.openai?.model ?? 'gpt-4o';
|
|
37
|
+
|
|
38
|
+
const messages: OpenAI.ChatCompletionMessageParam[] = [];
|
|
39
|
+
if (system) {
|
|
40
|
+
messages.push({ role: 'system', content: system });
|
|
41
|
+
}
|
|
42
|
+
messages.push({ role: 'user', content: user });
|
|
43
|
+
|
|
44
|
+
const response = await client.chat.completions.create({
|
|
45
|
+
model,
|
|
46
|
+
messages,
|
|
47
|
+
temperature: temperature ?? 0.7,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
return response.choices[0]?.message?.content ?? '';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Transcribe audio using Whisper API.
|
|
55
|
+
* Parity with coaiapy's transcription functions.
|
|
56
|
+
*/
|
|
57
|
+
export async function transcribeAudio(filePath: string): Promise<string> {
|
|
58
|
+
const client = getClient();
|
|
59
|
+
|
|
60
|
+
const file = new File(
|
|
61
|
+
[readFileSync(filePath)],
|
|
62
|
+
filePath.split('/').pop() ?? 'audio.wav',
|
|
63
|
+
{ type: 'audio/wav' },
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
const response = await client.audio.transcriptions.create({
|
|
67
|
+
model: 'whisper-1',
|
|
68
|
+
file,
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
return response.text;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Generate an image using DALL-E.
|
|
76
|
+
* Returns the URL of the generated image.
|
|
77
|
+
*/
|
|
78
|
+
export async function generateImage(
|
|
79
|
+
prompt: string,
|
|
80
|
+
size?: string,
|
|
81
|
+
): Promise<string> {
|
|
82
|
+
const client = getClient();
|
|
83
|
+
|
|
84
|
+
const validSize = (size ?? '1024x1024') as '256x256' | '512x512' | '1024x1024' | '1792x1024' | '1024x1792';
|
|
85
|
+
|
|
86
|
+
const response = await client.images.generate({
|
|
87
|
+
model: 'dall-e-3',
|
|
88
|
+
prompt,
|
|
89
|
+
n: 1,
|
|
90
|
+
size: validSize,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
return response.data?.[0]?.url ?? '';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Abstract process: config-driven LLM call with a named process.
|
|
98
|
+
* Looks up system prompt by processName in config or uses a default.
|
|
99
|
+
*/
|
|
100
|
+
export async function abstractProcess(
|
|
101
|
+
processName: string,
|
|
102
|
+
input: string,
|
|
103
|
+
): Promise<string> {
|
|
104
|
+
const systemPrompt = `You are executing the "${processName}" process. Follow the process instructions precisely and produce the expected output format.`;
|
|
105
|
+
return llm(input, systemPrompt);
|
|
106
|
+
}
|