# Einsatz mit KI-Agenten

Die Beispiele auf dieser Seite geben einem Agenten Tomba-Tools, die [agents.tomba.io](/mpp/introduction) aufrufen und jede Anfrage aus einem InFlow-Guthaben bezahlen. Weder ein Tomba-Konto noch ein API-Schlüssel ist beteiligt. Jedes Beispiel besteht aus zwei Teilen: einem Helfer, der eine bezahlte Anfrage stellt, und Tools für Ihr Agent-Framework, die den Helfer aufrufen.

## Bevor Sie beginnen

- Ein [InFlow](https://inflowpay.ai)-Konto in der Produktionsumgebung mit einem Guthaben in USDC oder USDT und einem API-Schlüssel. Legen Sie den Schlüssel in der Umgebungsvariable `INFLOW_API_KEY` ab.
- Ein API-Schlüssel für Ihren Modellanbieter: `ANTHROPIC_API_KEY` für die Beispiele mit Vercel AI SDK und LangChain und `OPENAI_API_KEY` für das Standardmodell von CrewAI.

Die Beispiele wurden mit `@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 und `crewai` 1.15.23 geprüft.

## JavaScript

Der JavaScript-Helfer verwendet das Buyer-SDK von InFlow, das Node.js 22 oder neuer benötigt. Node.js 22.18 und neuer führen die folgenden TypeScript-Dateien direkt aus; legen Sie sie in ein Projekt, dessen `package.json` `"type": "module"` setzt.

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

### fetch mit Zahlungsunterstützung

`mppx.fetch` sendet die Anfrage, bezahlt die `402`-Challenge über InFlow und sendet die Anfrage mit dem Credential erneut. Speichern Sie dies als `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;
}
```

Lehnt InFlow eine Zahlung ab, löst `mppx.fetch` eine Exception aus. Um festzuhalten, was Sie bezahlt haben, lesen Sie die Quittung einer erfolgreichen Antwort mit `Receipt.fromResponse(response)`, das `@inflowpayai/mpp-buyer` exportiert.

### Vercel AI SDK

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

Speichern Sie dies als `agent.ts` neben `tomba.ts` und führen Sie es mit `node agent.ts` aus:

```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

Die Python-Beispiele benötigen Python 3.10 oder neuer.

### Python-Helfer

Der Helfer führt die unter [Ohne die CLI bezahlen](/mpp/quickstart#pay-without-the-cli) beschriebenen Aufrufe aus. Er bezahlt in der in `TOMBA_MPP_CURRENCY` festgelegten Währung (`USDC`, wenn nicht gesetzt).

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

Speichern Sie dies als `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.*"
```

Der Agent verwendet das Standardmodell von CrewAI. Um ein anderes zu verwenden, übergeben Sie `llm` an `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())
```

## Eine Währung wählen

Jede `402` bietet eine Challenge in USDC und eine in USDT, und Ihr InFlow-Konto muss die Währung der Challenge besitzen, die Sie bezahlen.

- Der Python-Helfer bezahlt in `TOMBA_MPP_CURRENCY`. Er löst `StopIteration` aus, wenn keine Challenge diese Währung anbietet.
- `mppx.fetch` bezahlt die erste Challenge, die seine Methoden verarbeiten können. Um eine Währung zu bevorzugen, übergeben Sie `orderChallenges` an `Mppx.create`; die Funktion erhält die infrage kommenden Challenges und gibt sie in der Reihenfolge zurück, in der sie versucht werden sollen:

```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"),
        ),
});
```

## Fehler und Abrechnung

Beide Helfer lösen einen Fehler aus, wenn die endgültige Antwort einen Fehlerstatus hat. Die Meldung enthält den Status, den Wert von `X-Payment-Charged` und den Antwort-Body von Tomba. Eine Antwort mit `X-Payment-Charged: false` hat nichts gekostet. [Abrechnung](/mpp/introduction#billing) und [Fehler](/mpp/introduction#errors) listen jedes mögliche Ergebnis auf.

Jede bezahlte Anfrage wird abgerechnet, auch Wiederholungen; speichern Sie daher Ergebnisse, die Ihr Agent erneut benötigen könnte, statt sie zweimal anzufordern.
