-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
166 lines (145 loc) · 4.96 KB
/
Copy pathserver.ts
File metadata and controls
166 lines (145 loc) · 4.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import {
Latitude,
capture,
registerLatitudeInstrumentations,
} from "@latitude-data/telemetry";
import Anthropic, * as AnthropicSDK from "@anthropic-ai/sdk";
import {
ConsoleSpanExporter,
SimpleSpanProcessor,
type ReadableSpan,
type SpanProcessor,
} from "@opentelemetry/sdk-trace-node";
import { zodToJsonSchema } from "zod-to-json-schema";
import {
allTools,
createGitHubClient,
executeTool,
} from "@agentum/tools";
import { SYSTEM_PROMPT, type Message } from "@agentum/prompt";
import { createApp, mountSpa, startServer } from "@agentum/server";
const latitude = new Latitude({
apiKey: process.env.LATITUDE_API_KEY!,
projectSlug: process.env.LATITUDE_PROJECT_SLUG!,
});
await registerLatitudeInstrumentations({
instrumentations: ["anthropic"],
modules: { anthropic: AnthropicSDK },
tracerProvider: latitude.provider,
});
await latitude.ready;
// Diagnostic: attach extra span processors to dump what the Anthropic
// instrumentation actually emits over the wire. Uses the same OTel v2
// internal-list trick the Latitude SDK uses in init.ts:40-63 because
// `addSpanProcessor` was removed from the public API in OTel v2.
if (process.env.DEBUG_SPANS === "1") {
const fullExporter = new SimpleSpanProcessor(new ConsoleSpanExporter());
const messageDumper: SpanProcessor = {
onStart: () => {},
onEnd(span: ReadableSpan) {
const attrs = span.attributes;
const interesting = [
"gen_ai.input.messages",
"gen_ai.output.messages",
"gen_ai.system_instructions",
"gen_ai.prompt.0.content",
"gen_ai.completion.0.content",
];
const found = interesting
.filter((k) => attrs[k] !== undefined)
.map((k) => [k, attrs[k]] as const);
if (found.length === 0) return;
console.log("\n[gen_ai] span", span.name, "scope:", span.instrumentationScope?.name);
for (const [k, v] of found) {
console.log(` ${k} =`, typeof v === "string" ? v : JSON.stringify(v));
}
},
forceFlush: () => Promise.resolve(),
shutdown: () => Promise.resolve(),
};
const processors = (latitude.provider as any)?._activeSpanProcessor
?._spanProcessors;
if (Array.isArray(processors)) {
processors.push(fullExporter, messageDumper);
console.log(
"[debug] Console + gen_ai span processors attached to Latitude provider",
);
} else {
console.warn(
"[debug] Could not locate _activeSpanProcessor._spanProcessors on latitude.provider — diagnostic processors not attached",
);
}
}
const github = createGitHubClient();
const anthropicTools = allTools.map((t) => ({
name: t.name,
description: t.description,
input_schema: zodToJsonSchema(t.input, { target: "openApi3" }) as Record<
string,
unknown
>,
}));
const MAX_STEPS = 10;
const MODEL = process.env.ANTHROPIC_MODEL || "claude-sonnet-4-6";
const MAX_TOKENS = Number(process.env.ANTHROPIC_MAX_TOKENS) || 1024;
type ToolCallTrace = { name: string; input: string };
async function runAgent(
userMessages: Message[],
): Promise<{ message: string; toolCalls: ToolCallTrace[] }> {
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const messages: any[] = userMessages.map((m) => ({
role: m.role,
content: m.content,
}));
const toolCalls: ToolCallTrace[] = [];
for (let step = 0; step < MAX_STEPS; step++) {
const response = await client.messages.create({
model: MODEL,
max_tokens: MAX_TOKENS,
system: SYSTEM_PROMPT,
messages,
tools: anthropicTools as any,
});
const toolUseBlocks = response.content.filter(
(b: any) => b.type === "tool_use",
);
if (response.stop_reason === "tool_use" && toolUseBlocks.length > 0) {
messages.push({ role: "assistant", content: response.content });
const toolResults: any[] = [];
for (const block of toolUseBlocks as any[]) {
toolCalls.push({ name: block.name, input: JSON.stringify(block.input) });
const result = await executeTool(block.name, block.input, github);
toolResults.push({
type: "tool_result",
tool_use_id: block.id,
content: JSON.stringify(result),
});
}
messages.push({ role: "user", content: toolResults });
continue;
}
const textBlock = response.content.find((b: any) => b.type === "text") as
| { type: "text"; text: string }
| undefined;
return { message: textBlock?.text ?? "", toolCalls };
}
return { message: "", toolCalls };
}
const app = createApp("Agentum — Anthropic");
app.post("/api/chat", async (c) => {
const body = await c.req.json<{ messages: Message[] }>();
const result = await capture(
"anthropic-chat",
async () => runAgent(body.messages),
{ metadata: { model: MODEL } },
);
return c.json({
message: result.message,
toolCalls: result.toolCalls.length ? result.toolCalls : undefined,
});
});
mountSpa(app);
startServer(app, {
port: Number(process.env.ANTHROPIC_PORT) || 4007,
name: "Anthropic harness",
});