> For the complete documentation index, see [llms.txt](https://docs.opaquepay.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.opaquepay.xyz/integrations/openai-agents.md).

# OpenAI Agents

The OpenAI Assistants API supports custom function tools. OpaquePay integrates by exposing its HTTP API as function definitions that the assistant can call.

## Setup

Define the tool functions and their JSON schemas, then wire up a dispatch loop to handle tool calls by making HTTP requests to OpaquePay.

```python
import os
import json
import requests
from openai import OpenAI

OPAQUEPAY_API_KEY = os.environ["AGENT_API_KEY"]
BASE_URL = "https://api.opaquepay.xyz/v1"
HEADERS = {"Authorization": f"Bearer {OPAQUEPAY_API_KEY}", "Content-Type": "application/json"}

def opaquepay_send_payment(to: str, amount: str, memo: str = None) -> dict:
    resp = requests.post(
        f"{BASE_URL}/transfers",
        headers=HEADERS,
        json={"to": to, "amount": amount, "currency": "USDC", "memo": memo, "confidential": True},
    )
    return resp.json()

def opaquepay_get_balance() -> dict:
    resp = requests.get(f"{BASE_URL}/account", headers=HEADERS)
    data = resp.json()
    return {"balance": data["balance"], "currency": data["currency"]}

def opaquepay_list_transactions(limit: int = 10) -> dict:
    resp = requests.get(f"{BASE_URL}/transfers?limit={limit}", headers=HEADERS)
    return resp.json()

TOOL_HANDLERS = {
    "opaquepay_send_payment": opaquepay_send_payment,
    "opaquepay_get_balance": opaquepay_get_balance,
    "opaquepay_list_transactions": opaquepay_list_transactions,
}
```

## Tool definitions

Pass these function definitions to the OpenAI assistant:

```python
tools = [
    {
        "type": "function",
        "function": {
            "name": "opaquepay_send_payment",
            "description": "Send USDC to a recipient via OpaquePay.",
            "parameters": {
                "type": "object",
                "properties": {
                    "to": {"type": "string", "description": "Handle (@alice) or Solana address"},
                    "amount": {"type": "string", "description": "Decimal amount e.g. '5.00'"},
                    "memo": {"type": "string", "description": "Optional memo"},
                },
                "required": ["to", "amount"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "opaquepay_get_balance",
            "description": "Get the current USDC balance of the agent's OpaquePay wallet.",
            "parameters": {"type": "object", "properties": {}},
        },
    },
    {
        "type": "function",
        "function": {
            "name": "opaquepay_list_transactions",
            "description": "Get recent transaction history.",
            "parameters": {
                "type": "object",
                "properties": {
                    "limit": {"type": "integer", "default": 10},
                },
            },
        },
    },
]
```

## Full example with Assistants API

```python
import json
import os
from openai import OpenAI

openai_client = OpenAI()

# Create assistant with OpaquePay tools
assistant = openai_client.beta.assistants.create(
    name="Payment Agent",
    instructions="You are a helpful agent that can make payments on behalf of the user.",
    tools=tools,
    model="gpt-4o",
)

# Create a thread and run
thread = openai_client.beta.threads.create()
openai_client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="Pay @perplexity 0.05 USDC for a search and confirm once done",
)

run = openai_client.beta.threads.runs.create_and_poll(
    thread_id=thread.id,
    assistant_id=assistant.id,
)

# Handle tool calls
while run.status == "requires_action":
    tool_calls = run.required_action.submit_tool_outputs.tool_calls
    tool_outputs = []

    for tool_call in tool_calls:
        fn_name = tool_call.function.name
        fn_args = json.loads(tool_call.function.arguments)
        result = TOOL_HANDLERS[fn_name](**fn_args)
        tool_outputs.append({
            "tool_call_id": tool_call.id,
            "output": json.dumps(result),
        })

    run = openai_client.beta.threads.runs.submit_tool_outputs_and_poll(
        thread_id=thread.id,
        run_id=run.id,
        tool_outputs=tool_outputs,
    )

print(run.status)  # "completed"
```

## Available tools

| Function name                      | Description                                                    |
| ---------------------------------- | -------------------------------------------------------------- |
| `opaquepay_send_payment`           | Send USDC to a handle or address                               |
| `opaquepay_get_balance`            | Get current wallet balance                                     |
| `opaquepay_list_transactions`      | Get recent transaction history                                 |
| `opaquepay_create_payment_request` | Create a payment request link (`POST /v1/transfers/requests`)  |
| `opaquepay_get_transaction`        | Look up a specific transaction by ID (`GET /v1/transfers/:id`) |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.opaquepay.xyz/integrations/openai-agents.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
