Herramienta con un secreto
Conecta el token de una API propia mediante un secreto. Enlaza el campo de autenticación de la herramienta al secreto para que su definición y las respuestas no incluyan el token.
Antes de empezar
- Una API key de Platica en
PLATIC_API_KEY. - Solo para la prueba real: un API tuyo, en
PLATIC_EXAMPLE_API_URL, y su token enPLATIC_EXAMPLE_API_TOKEN. - Node.js 20.3 o superior y
npm install platic-sdk.
Guarda el token y prepara la llamada
- Crea un secreto
bearercon el token. El API nunca devuelve su valor. - Crea una herramienta de API propia.
auth: { type: "bearer" }define el campoauth.token;secrets: { "auth.token": secret.id }lo enlaza al secreto. - Prueba la herramienta con
dryRun: true: se arma la petición y no se llama a nada fuera de Platica. - Con la prueba real activada: llama a tu API, habilita la herramienta y la conecta a un agente nuevo.
- Elimina todo lo que creó, aunque falle un paso.
El código
import { Platic } from "platic-sdk";
const apiKey = process.env.PLATIC_API_KEY;
if (!apiKey) {
console.error("Set PLATIC_API_KEY to a Platica API key (pl_key_…).");
process.exit(1);
}
const realTest = process.env.PLATIC_EXAMPLE_REAL_TEST === "1";
const apiUrl = process.env.PLATIC_EXAMPLE_API_URL ?? "https://api.example.com/orders";
const apiToken = process.env.PLATIC_EXAMPLE_API_TOKEN ?? "example-token-not-a-real-credential";
if (realTest && !process.env.PLATIC_EXAMPLE_API_URL) {
console.error("PLATIC_EXAMPLE_REAL_TEST=1 calls a real API: set PLATIC_EXAMPLE_API_URL (and PLATIC_EXAMPLE_API_TOKEN) to one you own.");
process.exit(1);
}
const platic = new Platic({ apiKey });
const cleanup: Array<[string, () => Promise<unknown>]> = [];
try {
// 1. La credencial, guardada una vez. El API nunca devuelve su valor.
const secret = await platic.secrets.create({ name: `Orders API token ${Date.now()}`, kind: "bearer", value: apiToken });
cleanup.unshift([`secret ${secret.id}`, () => platic.secrets.delete(secret.id)]);
// 2. La herramienta. `auth: { type: "bearer" }` expone el espacio `auth.token`, enlazado aquí al secreto por su id.
const api = await platic.tools.apis.create({
name: `order_status_${Date.now()}`,
description: "Looks up an order by its number and returns its status and delivery date.",
request: { method: "GET", url: apiUrl, params: [{ key: "number", value: "{{order}}" }], auth: { type: "bearer" } },
variables: [{ name: "order", type: "string", description: "The order number the customer gives", required: true, mode: "ai" }],
secrets: { "auth.token": secret.id },
});
cleanup.unshift([`tool ${api.id}`, () => platic.tools.apis.delete(api.id)]);
console.log(`tool ${api.name}: ${api.nextStep}`);
// 3. Arma la petición sin enviarla.
const dry = await platic.tools.apis.test(api.id, { dryRun: true, input: { order: "1001" } });
console.log(`dry run: ${dry.success ? "the request builds" : "the request does not build"}${dry.nextStep ? `; ${dry.nextStep}` : ""}`);
if (realTest) {
// 4. Una prueba real que pasa marca la definición como verificada, que es lo que necesita habilitarla.
const test = await platic.tools.apis.test(api.id, { input: { order: "1001" } });
console.log(`real test: ${test.success ? "passed" : "failed"} (HTTP ${test.httpStatus ?? "none"})`);
if (!test.success) throw new Error(test.nextStep ?? "the real test did not pass");
// 5. Publícala en el catálogo del workspace y dásela a un agente.
const { toolId } = await platic.tools.apis.enable(api.id);
const agent = await platic.agents.create({ name: "Orders", instructions: "Look up orders with your tool before answering." });
cleanup.unshift([`agent ${agent.id}`, () => platic.agents.delete(agent.id)]);
await platic.agents.tools.connect(agent.id, toolId);
cleanup.unshift([`tool ${toolId} on agent ${agent.id}`, () => platic.agents.tools.disconnect(agent.id, toolId)]);
console.log(`agent ${agent.id} can now call ${api.name}`);
}
} finally {
await cleanUp(cleanup);
}
// Ejecuta todos los pasos, aunque uno falle, y dice qué no se pudo eliminar.
async function cleanUp(steps: Array<[string, () => Promise<unknown>]>): Promise<void> {
for (const [label, step] of steps) {
try {
await step();
console.log(`removed ${label}`);
} catch (error) {
console.error(`could not remove ${label}: ${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
}
}
} Ejecútalo
Guarda el código en tool-with-a-secret.ts y ejecútalo con tsx.
Define tu API key y ejecuta el script:
export PLATIC_API_KEY=pl_key_...
npx tsx tool-with-a-secret.ts Para ejecutar la prueba real, habilitar la herramienta y conectarla a un agente, usa:
PLATIC_EXAMPLE_REAL_TEST=1 \
PLATIC_EXAMPLE_API_URL=https://api.your-company.com/orders \
PLATIC_EXAMPLE_API_TOKEN=... \
npx tsx tool-with-a-secret.ts Qué esperar
tool order_status_…: <next step from the API>
dry run: the request builds
removed tool …
removed secret … Con la prueba real activada también ves el resultado de la prueba real y el agente nuevo. El script elimina la herramienta, el secreto y el agente en orden inverso. Si una eliminación falla, dice cuál y termina con código 1.
Referencia del API que usa
- Crea un secreto
- Elimina un secreto
- Crea una API propia
- Prueba una API propia
- Publica una API propia
- Conecta una herramienta a un agente
Siguientes pasos
Todos los ejemplos del SDK: el siguiente es Función personalizada.