|
| 1 | +import { listTools } from "@bitte-ai/data"; |
| 2 | +import { NextResponse } from "next/server"; |
| 3 | +import { kv } from "@vercel/kv"; |
| 4 | +import { BittePrimitiveNames } from "@/lib/constants"; |
| 5 | +import { FunctionDefinition } from "openai/resources/shared.mjs"; |
| 6 | + |
| 7 | +const getPingsByTool = async (toolName: string): Promise<number | null> => { |
| 8 | + return await kv.get<number>(`smart-action:v1.0:tool:${toolName}:pings`); |
| 9 | +}; |
| 10 | + |
| 11 | +export async function GET( |
| 12 | + _request: Request, |
| 13 | + { params }: { params: Promise<{ agentId: string }> } |
| 14 | +) { |
| 15 | + try { |
| 16 | + const agentId = (await params).agentId; |
| 17 | + |
| 18 | + // Get all tools and filter by agentId |
| 19 | + const allTools = await listTools(); |
| 20 | + const tools = allTools.filter((tool) => tool.agentId === agentId); |
| 21 | + |
| 22 | + if (tools.length === 0) { |
| 23 | + return NextResponse.json([]); |
| 24 | + } |
| 25 | + |
| 26 | + // Add isPrimitive flag to each tool |
| 27 | + const toolsWithPrimitiveFlags = tools.map((tool) => ({ |
| 28 | + ...tool, |
| 29 | + isPrimitive: BittePrimitiveNames.includes(tool.id), |
| 30 | + })); |
| 31 | + |
| 32 | + // Add pings data to each tool |
| 33 | + const toolsWithPings = await Promise.all( |
| 34 | + toolsWithPrimitiveFlags.map(async (tool) => { |
| 35 | + const pings = await getPingsByTool( |
| 36 | + (tool.function as unknown as FunctionDefinition).name |
| 37 | + ); |
| 38 | + return { |
| 39 | + ...tool, |
| 40 | + pings: pings || 0, |
| 41 | + }; |
| 42 | + }) |
| 43 | + ); |
| 44 | + |
| 45 | + // Sort by pings (most pinged first) |
| 46 | + const sortedTools = toolsWithPings.sort((a, b) => b.pings - a.pings); |
| 47 | + |
| 48 | + return NextResponse.json(sortedTools); |
| 49 | + } catch (error) { |
| 50 | + console.error("Error fetching agent tools:", error); |
| 51 | + return NextResponse.json( |
| 52 | + { error: "Failed to fetch agent tools" }, |
| 53 | + { status: 500 } |
| 54 | + ); |
| 55 | + } |
| 56 | +} |
0 commit comments