import axios, { AxiosRequestConfig } from "axios"; import { Agent, AgentStatus, AgentType, Api, OpenAiPluginId, transcribeAudioToTextTranslateToEnglishTruthyValues, } from "./types"; export async function getAgentUrl( agents: Agent[], agentType: AgentType, profile?: string, healthCheck = true, ): Promise { let filtered = agents.filter( (a) => a.type === agentType && a.status === AgentStatus.ACTIVE, ); if (profile) { filtered = agents.filter( (a) => a.tags.profile && (a.tags.profile.includes("*") || a.tags.profile.includes(profile)), ); } if (healthCheck) { const coroutines: Promise[] = []; for (const agent of filtered) { const p: Promise = (async () => { const url = new URL("health", agent.url); const config: AxiosRequestConfig = { url: url.toString(), method: "get", headers: {}, }; await axios(config); return agent.url; })(); coroutines.push(p); } try { return await Promise.any(coroutines); } catch { throw new Error("No available agents"); } } else { const randomIndex = Math.floor(Math.random() * filtered.length); return filtered[randomIndex].url; } } export const sanitizeV2RequestBody = ( apiBody: Record, ): Record => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const traverseJSON = (obj: any) => { for (const key in obj) { if (key === "step" && obj.step[OpenAiPluginId]) { const value = obj.step[OpenAiPluginId].transcribeAudioToTextTranslateToEnglish; obj.step[OpenAiPluginId].transcribeAudioToTextTranslateToEnglish = transcribeAudioToTextTranslateToEnglishTruthyValues.includes(value); } else if (typeof obj[key] === "object") { sanitizeV2RequestBody(obj[key]); } } }; traverseJSON(apiBody); return apiBody; }; export const getSanitizedApi = (api: Api): any => { const sanitizedBlocks = (api.blocks ?? [])?.map( (block: Record) => sanitizeV2RequestBody(block), ); return { ...api, blocks: sanitizedBlocks, }; };