# 与 AI 代理配合使用

本页中的示例为代理提供 Tomba 工具，这些工具会调用 [agents.tomba.io](/mpp/introduction)，并从 InFlow 余额中为每个请求付费。整个过程不涉及 Tomba 账户或 API 密钥。每个示例都包含 2 个部分：发出付费请求的辅助函数，以及供您的代理框架调用该辅助函数的工具。

## 开始之前

- 一个生产环境中的 [InFlow](https://inflowpay.ai) 账户，带有 USDC 或 USDT 余额以及 API 密钥。请将该密钥放入 `INFLOW_API_KEY` 环境变量。
- 您的模型提供商的 API 密钥：Vercel AI SDK 和 LangChain 示例使用 `ANTHROPIC_API_KEY`，CrewAI 的默认模型使用 `OPENAI_API_KEY`。

这些示例已使用 `@inflowpayai/mpp-buyer` 0.7.3、`mppx` 0.8.19、`ai` 7.0.122、`@ai-sdk/anthropic` 4.0.68、`httpx` 0.28.1、`langchain` 1.4.3、`langchain-anthropic` 1.7.5 和 `crewai` 1.15.23 验证。

## JavaScript

JavaScript 辅助函数使用 InFlow 的买家 SDK，该 SDK 需要 Node.js 22 或更高版本。Node.js 22.18 及更高版本可以直接运行下面的 TypeScript 文件；请将它们放在 `package.json` 中设置了 `"type": "module"` 的项目中。

```bash
npm install @inflowpayai/mpp-buyer@0.7 mppx@0.8
```

### 支持付款的 fetch

`mppx.fetch` 会发送请求，通过 InFlow 支付 `402` 质询，然后携带凭据再次发送请求。将以下内容保存为 `tomba.ts`：

```typescript
import { Mppx, inflow } from "@inflowpayai/mpp-buyer";

const apiKey = process.env.INFLOW_API_KEY;
if (!apiKey) throw new Error("Set INFLOW_API_KEY");

const mppx = Mppx.create({
    // Pay only through mppx.fetch; leave globalThis.fetch unchanged.
    polyfill: false,
    methods: [inflow({ apiKey, environment: "production" })],
});

// Calls an agents.tomba.io endpoint and pays for it when it answers 402.
export async function tomba(
    path: string,
    params: Record<string, string>,
): Promise<unknown> {
    const url = new URL(path, "https://agents.tomba.io");
    url.search = new URLSearchParams(params).toString();

    const response = await mppx.fetch(url);
    const body: unknown = await response.json();
    if (!response.ok) {
        const charged = response.headers.get("X-Payment-Charged");
        throw new Error(
            `Tomba returned ${response.status} (charged: ${charged}): ${JSON.stringify(body)}`,
        );
    }
    return body;
}
```

如果 InFlow 拒绝付款，`mppx.fetch` 会抛出异常。要记录您支付的内容，请使用 `@inflowpayai/mpp-buyer` 导出的 `Receipt.fromResponse(response)` 读取成功响应的收据。

### Vercel AI SDK

```bash
npm install ai@7 @ai-sdk/anthropic@4 zod@4
```

将以下内容保存为 `agent.ts`，放在 `tomba.ts` 旁边，然后使用 `node agent.ts` 运行：

```typescript
import { anthropic } from "@ai-sdk/anthropic";
import { generateText, stepCountIs, tool } from "ai";
import { z } from "zod";
import { tomba } from "./tomba.ts";

const result = await generateText({
    model: anthropic("claude-opus-5-5"),
    tools: {
        domain_search: tool({
            description: "Find email addresses at a company from its domain.",
            inputSchema: z.object({
                domain: z
                    .string()
                    .describe("Company domain, for example stripe.com"),
            }),
            execute: ({ domain }) => tomba("/domain-search", { domain }),
        }),
        email_verifier: tool({
            description: "Check whether an email address is deliverable.",
            inputSchema: z.object({ email: z.string().email() }),
            execute: ({ email }) => tomba("/email-verifier", { email }),
        }),
    },
    stopWhen: stepCountIs(5),
    prompt: "Find an engineering contact at stripe.com and verify the address.",
});

console.log(result.text);
```

## Python

Python 示例需要 Python 3.10 或更高版本。

### Python 辅助函数

该辅助函数会发出[不使用 CLI 付款](/mpp/quickstart#pay-without-the-cli)中所述的调用。它使用 `TOMBA_MPP_CURRENCY` 中设置的币种付款（未设置时为 `USDC`）。

```bash
pip install "httpx==0.28.*"
```

将以下内容保存为 `tomba_mpp.py`：

```python
"""Call agents.tomba.io and pay for each request through InFlow."""

import base64
import json
import os
import re
import time

import httpx

AGENTS_URL = "https://agents.tomba.io"
INFLOW_URL = "https://api.inflowpay.ai"
INFLOW_API_KEY = os.environ["INFLOW_API_KEY"]
CURRENCY = os.environ.get("TOMBA_MPP_CURRENCY", "USDC")


def _payment_challenges(header):
    """Parse the Payment challenges in a WWW-Authenticate value."""
    challenges = []
    for part in re.split(r",\s*(?=Payment\s)", header):
        scheme, _, params = part.strip().partition(" ")
        if scheme == "Payment":
            pairs = re.findall(r'(\w+)="((?:[^"\\]|\\.)*)"', params)
            challenges.append({k: re.sub(r"\\(.)", r"\1", v) for k, v in pairs})
    return challenges


def _currency(challenge):
    encoded = challenge["request"]
    padded = encoded + "=" * (-len(encoded) % 4)
    return json.loads(base64.urlsafe_b64decode(padded))["currency"]


def _pay(challenge):
    """Fulfil a challenge with InFlow and return the payment credential."""
    headers = {"X-API-KEY": INFLOW_API_KEY}
    response = httpx.post(
        f"{INFLOW_URL}/v1/transactions/mpp",
        headers=headers,
        json={"challenge": challenge, "options": {}},
        timeout=30,
    )
    response.raise_for_status()
    transaction = response.json()
    while transaction["state"] == "pending":
        time.sleep(transaction.get("retryAfterSeconds", 5))
        response = httpx.get(
            f"{INFLOW_URL}/v1/transactions/{transaction['transactionId']}/mpp",
            headers=headers,
            timeout=30,
        )
        response.raise_for_status()
        transaction = response.json()
    if transaction["state"] != "ready":
        raise RuntimeError(f"InFlow payment {transaction['state']}")
    return transaction["credential"]


def paid_get(path, params):
    """GET an agents.tomba.io endpoint, paying when it answers 402."""
    url = f"{AGENTS_URL}{path}"
    response = httpx.get(url, params=params, timeout=60)
    if response.status_code == 402:
        offers = _payment_challenges(response.headers["WWW-Authenticate"])
        challenge = next(c for c in offers if _currency(c) == CURRENCY)
        credential = _pay(challenge)
        response = httpx.get(
            url,
            params=params,
            headers={"Authorization": f"Payment {credential}"},
            timeout=60,
        )
    if response.is_error:
        charged = response.headers.get("X-Payment-Charged")
        raise RuntimeError(
            f"Tomba returned {response.status_code} (charged: {charged}): {response.text}"
        )
    return response.json()
```

### LangChain

```bash
pip install "langchain==1.4.*" "langchain-anthropic==1.7.*"
```

```python
from langchain.agents import create_agent
from langchain.tools import tool

from tomba_mpp import paid_get


@tool
def domain_search(domain: str) -> dict:
    """Find email addresses at a company from its domain, for example stripe.com."""
    return paid_get("/domain-search", {"domain": domain})


@tool
def email_verifier(email: str) -> dict:
    """Check whether an email address is deliverable."""
    return paid_get("/email-verifier", {"email": email})


agent = create_agent("anthropic:claude-opus-5-5", tools=[domain_search, email_verifier])

if __name__ == "__main__":
    result = agent.invoke(
        {"messages": [{"role": "user", "content": "Find an engineering contact at stripe.com and verify the address."}]}
    )
    print(result["messages"][-1].text)
```

### CrewAI

```bash
pip install "crewai==1.15.*"
```

该代理使用 CrewAI 的默认模型。如需使用其他模型，请将 `llm` 传给 `Agent`。

```python
from crewai import Agent, Crew, Task
from crewai.tools import tool

from tomba_mpp import paid_get


@tool("Domain search")
def domain_search(domain: str) -> dict:
    """Find email addresses at a company from its domain, for example stripe.com."""
    return paid_get("/domain-search", {"domain": domain})


@tool("Email verifier")
def email_verifier(email: str) -> dict:
    """Check whether an email address is deliverable."""
    return paid_get("/email-verifier", {"email": email})


researcher = Agent(
    role="Lead researcher",
    goal="Find and verify contacts at target companies",
    backstory="You research B2B contacts with Tomba.",
    tools=[domain_search, email_verifier],
)

task = Task(
    description="Find an engineering contact at stripe.com and verify the address.",
    expected_output="The contact's name, email address, and verification status.",
    agent=researcher,
)

if __name__ == "__main__":
    print(Crew(agents=[researcher], tasks=[task]).kickoff())
```

## 选择币种

每个 `402` 都提供 1 个 USDC 质询和 1 个 USDT 质询，您的 InFlow 账户必须持有您所支付质询的币种。

- Python 辅助函数使用 `TOMBA_MPP_CURRENCY` 付款。如果没有质询提供该币种，它会抛出 `StopIteration`。
- `mppx.fetch` 会支付其方法能够处理的第一个质询。如需优先使用某种币种，请将 `orderChallenges` 传给 `Mppx.create`；它接收候选质询，并按尝试顺序返回它们：

```typescript
import { Mppx, inflow } from "@inflowpayai/mpp-buyer";

const apiKey = process.env.INFLOW_API_KEY;
if (!apiKey) throw new Error("Set INFLOW_API_KEY");

const mppx = Mppx.create({
    polyfill: false,
    methods: [inflow({ apiKey, environment: "production" })],
    // Try the USDT challenge first.
    orderChallenges: (candidates) =>
        [...candidates].sort(
            (a, b) =>
                Number(b.challenge.request.currency === "USDT") -
                Number(a.challenge.request.currency === "USDT"),
        ),
});
```

## 错误和计费

当最终响应为错误状态时，JavaScript 和 Python 辅助函数都会抛出错误。错误消息包含状态、`X-Payment-Charged` 的值以及 Tomba 的响应体。带有 `X-Payment-Charged: false` 的响应不收费。[计费](/mpp/introduction#billing)和[错误](/mpp/introduction#errors)列出了所有结果。

每个付费请求都会扣费，包括重复的请求，因此请存储代理可能再次需要的结果，而不要重复请求。
