AIDeed Criar conta grátis

Início › Desenvolvedores › Exemplos de código

Exemplos de código

Copie, troque a chave pela sua (variável de ambiente AIDEED_API_KEY) e rode. Os exemplos usam o agente de testes agt_sandbox_cobranca.

Pedir uma tarefa e ler o resultado

JavaScript

const BASE = "https://aideed.com.br/api/developers/v1";
const KEY = process.env.AIDEED_API_KEY; // aid_test_… ou aid_live_…

async function aideed(path, init = {}) {
  const r = await fetch(BASE + path, {
    ...init,
    headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json", ...init.headers },
  });
  const body = await r.json();
  if (!r.ok) throw new Error(`${body.code}: ${body.title} (${body.request_id})`);
  return body;
}

let task = await aideed("/agents/agt_sandbox_cobranca/tasks", {
  method: "POST",
  headers: { "Idempotency-Key": "fatura-4821" },
  body: JSON.stringify({ input: "Envie o lembrete de vencimento da fatura 4821", external_ref: "4821" }),
});

// sem webhooks: consulte até terminar (com aprovação ligada, prefira os webhooks)
while (["pending_approval", "queued", "running"].includes(task.status)) {
  await new Promise((r) => setTimeout(r, 3000));
  task = await aideed(`/tasks/${task.id}`);
}
if (task.status === "completed") {
  const result = await aideed(`/tasks/${task.id}/result`);
  console.log(result.output.text);
} else {
  console.log(task.status, task.error);
}

Python

import os
import time

import httpx

client = httpx.Client(
    base_url="https://aideed.com.br/api/developers/v1",
    headers={"Authorization": f"Bearer {os.environ['AIDEED_API_KEY']}"},
    timeout=30,
)

r = client.post(
    "/agents/agt_sandbox_cobranca/tasks",
    json={"input": "Envie o lembrete de vencimento da fatura 4821", "external_ref": "4821"},
    headers={"Idempotency-Key": "fatura-4821"},
)
r.raise_for_status()
task = r.json()

while task["status"] in ("pending_approval", "queued", "running"):
    time.sleep(3)
    task = client.get(f"/tasks/{task['id']}").json()

if task["status"] == "completed":
    print(client.get(f"/tasks/{task['id']}/result").json()["output"]["text"])
else:
    print(task["status"], task["error"])

PHP

<?php
const AIDEED_BASE = "https://aideed.com.br/api/developers/v1";

function aideed(string $method, string $path, ?array $body = null, array $headers = []): array
{
    $ch = curl_init(AIDEED_BASE . $path);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge([
        "Authorization: Bearer " . getenv("AIDEED_API_KEY"),
        "Content-Type: application/json",
    ], $headers));
    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }
    $out = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $out;
}

$task = aideed("POST", "/agents/agt_sandbox_cobranca/tasks",
    ["input" => "Envie o lembrete de vencimento da fatura 4821", "external_ref" => "4821"],
    ["Idempotency-Key: fatura-4821"]);

while (in_array($task["status"], ["pending_approval", "queued", "running"], true)) {
    sleep(3);
    $task = aideed("GET", "/tasks/" . $task["id"]);
}

if ($task["status"] === "completed") {
    echo aideed("GET", "/tasks/" . $task["id"] . "/result")["output"]["text"], PHP_EOL;
}

Conferir a assinatura do webhook

JavaScript

import crypto from "node:crypto";
import express from "express";

const app = express();

// o corpo bruto: a assinatura é sobre os bytes recebidos, não sobre o JSON reinterpretado
app.post("/aideed/eventos", express.raw({ type: "application/json" }), (req, res) => {
  const pairs = (req.get("X-AIDeed-Signature") ?? "").split(",").map((p) => p.split("="));
  const t = Number(pairs.find(([k]) => k === "t")?.[1]);
  const expected = crypto
    .createHmac("sha256", process.env.AIDEED_WEBHOOK_SECRET)
    .update(`${t}.${req.body}`)
    .digest("hex");
  const fresh = Math.abs(Date.now() / 1000 - t) < 300;
  const valid = pairs.some(
    ([k, v]) => k === "v1" && v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)),
  );
  if (!fresh || !valid) return res.sendStatus(401);

  const event = JSON.parse(req.body);
  // responda já e processe na sua fila; ignore event.id repetido
  res.sendStatus(200);
});

Python

import hashlib
import hmac
import os
import time


def aideed_signature_ok(header: str, body: bytes) -> bool:
    """header = X-AIDeed-Signature; body = os bytes recebidos, antes de ler o JSON."""
    secret = os.environ["AIDEED_WEBHOOK_SECRET"].encode()
    pairs = [part.split("=", 1) for part in header.split(",") if "=" in part]
    t = next((v for k, v in pairs if k == "t"), "")
    if not t.isdigit() or abs(time.time() - int(t)) > 300:
        return False
    expected = hmac.new(secret, f"{t}.".encode() + body, hashlib.sha256).hexdigest()
    return any(k == "v1" and hmac.compare_digest(v, expected) for k, v in pairs)

PHP

<?php
function aideed_signature_ok(string $header, string $body, string $secret): bool
{
    $t = 0;
    $sigs = [];
    foreach (explode(",", $header) as $part) {
        [$k, $v] = array_pad(explode("=", $part, 2), 2, "");
        if ($k === "t") $t = (int) $v;
        if ($k === "v1") $sigs[] = $v;
    }
    if ($t === 0 || abs(time() - $t) > 300) return false;
    $expected = hash_hmac("sha256", $t . "." . $body, $secret);
    foreach ($sigs as $s) {
        if (hash_equals($expected, $s)) return true;
    }
    return false;
}

$body = file_get_contents("php://input");
if (!aideed_signature_ok($_SERVER["HTTP_X_AIDEED_SIGNATURE"] ?? "", $body, getenv("AIDEED_WEBHOOK_SECRET"))) {
    http_response_code(401);
    exit;
}
$event = json_decode($body, true);
http_response_code(200); // processe depois, na sua fila

Mais do portal

Comece aqui: Visão geral · Primeiros passos

Guias: Autenticação · Conceitos · Tarefas e aprovações · Webhooks · Erros · Limites e cota · Ambiente de testes · MCP do Workforce

Referência: Referência da API · Exemplos de código · Versões e mudanças

Dados públicos: API pública do catálogo · MCP do catálogo público