# Utiliser avec des agents IA

Les exemples de cette page donnent à un agent des outils Tomba qui appellent [agents.tomba.io](/mpp/introduction) et paient chaque requête depuis un solde InFlow. Aucun compte Tomba ni aucune clé API n'est nécessaire. Chaque exemple comporte deux parties : un helper qui effectue une requête payante, et des outils pour votre framework d'agents qui appellent le helper.

## Avant de commencer

- Un compte [InFlow](https://inflowpay.ai) dans l'environnement de production, avec un solde en USDC ou en USDT et une clé API. Placez la clé dans la variable d'environnement `INFLOW_API_KEY`.
- Une clé API pour votre fournisseur de modèle : `ANTHROPIC_API_KEY` pour les exemples Vercel AI SDK et LangChain, et `OPENAI_API_KEY` pour le modèle par défaut de CrewAI.

Les exemples ont été vérifiés avec `@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 et `crewai` 1.15.23.

## JavaScript

Le helper JavaScript utilise le SDK buyer d'InFlow, qui nécessite Node.js 22 ou une version ultérieure. Node.js 22.18 et les versions ultérieures exécutent directement les fichiers TypeScript ci-dessous ; placez-les dans un projet dont le `package.json` définit `"type": "module"`.

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

### Fetch avec paiement intégré

`mppx.fetch` envoie la requête, paie le challenge `402` via InFlow, puis envoie à nouveau la requête avec l'identifiant de paiement. Enregistrez ceci sous `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;
}
```

Un paiement refusé par InFlow fait lever une exception à `mppx.fetch`. Pour garder une trace de ce que vous avez payé, lisez le reçu d'une réponse réussie avec `Receipt.fromResponse(response)`, qu'exporte `@inflowpayai/mpp-buyer`.

### Vercel AI SDK

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

Enregistrez ceci sous `agent.ts` à côté de `tomba.ts`, et exécutez-le avec `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

Les exemples Python nécessitent Python 3.10 ou une version ultérieure.

### Helper Python

Le helper effectue les appels décrits dans [Payer sans la CLI](/mpp/quickstart#pay-without-the-cli). Il paie dans la devise définie dans `TOMBA_MPP_CURRENCY` (`USDC` si elle n'est pas définie).

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

Enregistrez ceci sous `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.*"
```

L'agent utilise le modèle par défaut de CrewAI. Pour en utiliser un autre, passez `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())
```

## Choisir une devise

Chaque `402` propose un challenge en USDC et un en USDT, et votre compte InFlow doit détenir la devise du challenge que vous payez.

- Le helper Python paie en `TOMBA_MPP_CURRENCY`. Il lève `StopIteration` quand aucun challenge ne propose cette devise.
- `mppx.fetch` paie le premier challenge que ses méthodes savent traiter. Pour privilégier une devise, passez `orderChallenges` à `Mppx.create` ; cette fonction reçoit les challenges candidats et les renvoie dans l'ordre où les essayer :

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

## Erreurs et facturation

Les deux helpers lèvent une erreur quand la réponse finale a un statut d'erreur. Le message inclut le statut, la valeur de `X-Payment-Charged` et le corps de la réponse de Tomba. Une réponse avec `X-Payment-Charged: false` n'a rien coûté. [Facturation](/mpp/introduction#billing) et [Erreurs](/mpp/introduction#errors) listent tous les cas.

Chaque requête payée est facturée, y compris les répétitions : stockez donc les résultats dont votre agent peut avoir de nouveau besoin au lieu de les demander deux fois.
