סקירת פונקציית TypeScript שכתב סוכן קידוד
נתקלתי ב stavrobot, סוכן AI שאמור להיות גרסה מאובטחת של אופןקלו. לא התקנתי אבל מאחר והפרויקט בקוד פתוח והמפתח הדגיש שהוא עבד עם סוכן קידוד כדי לבנות את זה היה לי מעניין להסתכל בקוד. אפשר למצוא את הפרויקט בקישור הזה:
https://github.com/skorokithakis/stavrobot
בפוסט היום נתבונן בפונקציה אחת מתוך הקוד ונאתר בה מספר Anti Patterns, כלומר תבניות קוד שליליות שאני מזהה שחוזרות בצורות שונות בקוד AI. תבניות אלה יעבדו נגדנו כשנרצה להמשיך ולפתח את הפרויקט.
נתחיל בהצגת קוד הפונקציה כמו שמצאתי אותה בפרויקט:
export function serializeMessagesForSummary(messages: AgentMessage[]): string {
const lines: string[] = [];
for (const message of messages) {
if (message.role === "user") {
let textContent: string;
if (typeof message.content === "string") {
textContent = message.content;
} else {
const content = Array.isArray(message.content) ? message.content : [];
textContent = content
.filter((block): block is TextContent => block.type === "text")
.map((block) => block.text)
.join("");
}
lines.push(`User: ${textContent}`);
} else if (message.role === "assistant") {
const content = Array.isArray(message.content) ? message.content : [];
const textContent = content
.filter((block): block is TextContent => block.type === "text")
.map((block) => block.text)
.join("");
if (textContent) {
lines.push(`Assistant: ${textContent}`);
}
for (const block of content) {
if (block.type === "toolCall") {
const toolCall = block as ToolCall;
const args = Object.entries(toolCall.arguments)
.map(([key, value]) => {
if (typeof value === "string") {
return `${key}=${JSON.stringify(value)}`;
}
if (typeof value === "object" && value !== null) {
return `${key}=${JSON.stringify(value)}`;
}
return `${key}=${String(value)}`;
})
.join(", ");
lines.push(`Assistant called ${toolCall.name}(${args})`);
}
}
} else if (message.role === "toolResult") {
const content = Array.isArray(message.content) ? message.content : [];
const textContent = content
.filter((block): block is TextContent => block.type === "text")
.map((block) => block.text)
.join("");
lines.push(`Tool result (${message.toolName}): ${textContent}`);
}
}
return lines.join("\n");
}
הפונקציה מקבלת מערך של הודעות וצריכה להפוך אותו למערך של שורות כלומר כל הודעה צריכה להפוך לשורת טקסט במערך התוצאה.