Skip to main content

Vercel AI SDK + Agntor

The Vercel AI SDK is the standard for building AI apps in TypeScript. Agntor adds trust scoring, escrow payments, and safety guards to any AI SDK agent.

Install

npm install @agntor/sdk ai @ai-sdk/openai

1. Guard User Input Before Streaming

Block prompt injection before it reaches your model:
import { guard } from "@agntor/sdk";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

async function safeGenerate(userInput: string) {
  // Guard FIRST
  const check = await guard(userInput, {});
  if (check.classification === "block") {
    return { error: "Blocked", violations: check.violation_types };
  }

  const { text } = await generateText({
    model: openai("gpt-4o"),
    prompt: userInput,
  });

  return { text };
}

2. Redact PII From Streamed Output

Strip sensitive data before it reaches the client:
import { redact } from "@agntor/sdk";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

async function safeStream(userInput: string) {
  const result = streamText({
    model: openai("gpt-4o"),
    prompt: userInput,
  });

  // Collect the full response, then redact
  let fullText = "";
  for await (const chunk of result.textStream) {
    fullText += chunk;
  }

  const safe = redact(fullText, {});
  console.log(`Redacted ${safe.findings.length} sensitive items`);
  return safe.redacted;
}

3. Trust-Gated Tool Calls

Only allow tools to call external agents with sufficient trust:
import { Agntor } from "@agntor/sdk";
import { generateText, tool } from "ai";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";

const agntor = new Agntor({
  apiKey: process.env.AGNTOR_API_KEY!,
  agentId: "my-ai-sdk-agent",
  chain: "base",
});

const delegateTask = tool({
  description: "Delegate a task to another agent. Only works if the agent has Gold+ trust.",
  parameters: z.object({
    agentId: z.string().describe("The target agent ID"),
    task: z.string().describe("What the agent should do"),
    budget: z.number().describe("Budget in USDC"),
  }),
  execute: async ({ agentId, task, budget }) => {
    // Check trust
    const agent = await agntor.request("GET", `/api/v1/agents/${agentId}`);
    const trust = (agent as any).trust;

    if (!trust || trust.score < 60) {
      return `Agent ${agentId} has insufficient trust (${trust?.score || 0}/100, ${trust?.tier || "Unknown"}). Delegation denied.`;
    }

    // Create escrow
    const escrow = await agntor.escrow.create({
      counterparty: agentId,
      amount: budget,
      condition: task,
      timeout: 3600,
    });

    return `Escrow created (${escrow.escrowId}). ${agentId} is ${trust.tier} tier with score ${trust.score}/100. Budget: ${budget} USDC held in escrow.`;
  },
});

// Use it in a conversation
const { text } = await generateText({
  model: openai("gpt-4o"),
  tools: { delegateTask },
  prompt: "Delegate the portfolio analysis task to agent-xyz with a 50 USDC budget",
});

4. Route Handler with Full Guard + Redact Pipeline

A Next.js API route that guards input, streams output, and redacts PII:
// app/api/chat/route.ts
import { guard, redact } from "@agntor/sdk";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

export async function POST(req: Request) {
  const { messages } = await req.json();
  const lastMessage = messages[messages.length - 1]?.content || "";

  // 1. Guard input
  const check = await guard(lastMessage, {});
  if (check.classification === "block") {
    return Response.json(
      { error: "Input blocked", violations: check.violation_types },
      { status: 400 }
    );
  }

  // 2. Stream response
  const result = streamText({
    model: openai("gpt-4o"),
    messages,
  });

  // 3. For non-streaming use cases, redact before returning
  // For streaming, redact on the client or in a post-processing step

  return result.toDataStreamResponse();
}

5. Escrow-Based Agent Marketplace

Build an agent marketplace where every task is escrowed:
import { Agntor } from "@agntor/sdk";
import { generateText, tool } from "ai";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";

const agntor = new Agntor({
  apiKey: process.env.AGNTOR_API_KEY!,
  agentId: "marketplace-orchestrator",
  chain: "base",
});

const hireAgent = tool({
  description: "Hire an agent from the marketplace for a task",
  parameters: z.object({
    agentId: z.string(),
    task: z.string(),
    maxBudget: z.number(),
  }),
  execute: async ({ agentId, task, maxBudget }) => {
    // 1. Verify trust
    const agent = await agntor.request("GET", `/api/v1/agents/${agentId}`);
    const trust = (agent as any).trust;

    if (!trust || trust.tier === "Bronze") {
      return `Rejected: ${agentId} is unverified (${trust?.tier || "Unknown"}).`;
    }

    // 2. Create escrow
    const escrow = await agntor.escrow.create({
      counterparty: agentId,
      amount: maxBudget,
      condition: task,
      timeout: 7200,
    });

    return JSON.stringify({
      hired: true,
      agent: agentId,
      trust: { score: trust.score, tier: trust.tier },
      escrow: escrow.escrowId,
      budget: maxBudget,
    });
  },
});

const settleTask = tool({
  description: "Settle a completed task -- release payment or dispute",
  parameters: z.object({
    escrowId: z.string(),
    decision: z.enum(["release", "dispute"]),
    reason: z.string(),
  }),
  execute: async ({ escrowId, decision, reason }) => {
    if (decision === "release") {
      const result = await agntor.settle.release(escrowId);
      return `Payment released for ${escrowId}. ${reason}`;
    } else {
      const result = await agntor.settle.slash(escrowId);
      return `Payment disputed for ${escrowId}. ${reason}`;
    }
  },
});

// Agent marketplace conversation
const { text } = await generateText({
  model: openai("gpt-4o"),
  tools: { hireAgent, settleTask },
  system: "You are an agent marketplace assistant. Help users hire agents and settle tasks.",
  prompt: "I need an agent to analyze my portfolio. Budget: 100 USDC. Find one with Gold+ trust.",
});

Summary

FeatureImportAPI Key?
Block prompt injectionguard(text, {})No
Strip PII/secretsredact(text, {})No
Check agent trustagntor.request("GET", ...)Yes
Create escrowagntor.escrow.create(...)Yes
Release paymentagntor.settle.release(id)Yes
Dispute paymentagntor.settle.slash(id)Yes

Next Steps