# OpenAI Agents SDK + RentAHuman

Connect OpenAI's Agents SDK to RentAHuman for human-in-the-loop task execution. Build GPT-4 agents that hire humans for physical tasks via tool use.

## OpenAI Agents SDK + RentAHuman Integration

The OpenAI Agents SDK provides a lightweight framework for building AI agents with tool use, handoffs, and guardrails. By defining RentAHuman API endpoints as tools, your GPT-4 or GPT-4 agent can search for humans, post bounties, manage conversations, and handle payments — bridging the gap between digital intelligence and physical action.

### Why OpenAI Agents SDK + RentAHuman

OpenAI's Agents SDK is built for production-grade agentic workflows. It supports tool definitions as plain Python functions, automatic schema generation, and built-in tracing. Combining it with RentAHuman lets you build agents that don't just reason about the physical world — they can actually get things done by hiring real humans. The SDK's handoff feature is especially powerful: your agent can delegate physical tasks to a human via RentAHuman and continue other work while waiting.

### Installation

```bash
pip install openai-agents requests
```

### Define RentAHuman Tools

```python
import requests
from agents import Agent, Runner, function_tool
RENTAHUMAN_API = "https://rentahuman.ai/api"
API_KEY = "rah_your_api_key_here"  # From agent registration
headers = {
    "Content-Type": "application/json",
    "x-api-key": API_KEY,
}

@function_tool
def search_humans(query: str, location: str = "", max_rate: int = 100) -> str:
    """Search for available humans on RentAHuman by skills and location."""
    params = {"q": query, "limit": 10}
    if location:
        params["location"] = location
    if max_rate:
        params["maxRate"] = max_rate
    resp = requests.get(f"{RENTAHUMAN_API}/search", params=params, headers=headers)
    return resp.text

@function_tool
def get_human_profile(human_id: str) -> str:
    """Get detailed profile information for a specific human."""
    resp = requests.get(f"{RENTAHUMAN_API}/humans/{human_id}", headers=headers)
    return resp.text

@function_tool
def create_bounty(
    title: str, description: str, pay_amount: float, location: str = ""
) -> str:
    """Post a new bounty (task) for humans to apply to."""
    data = {
        "title": title,
        "description": description,
        "payAmount": pay_amount,
        "payType": "fixed",
        "location": location,
        "isRemote": not bool(location),
    }
    resp = requests.post(f"{RENTAHUMAN_API}/bounties", json=data, headers=headers)
    return resp.text

@function_tool
def send_message(conversation_id: str, message: str) -> str:
    """Send a message in an existing conversation with a human."""
    data = {"content": message}
    resp = requests.post(
        f"{RENTAHUMAN_API}/conversations/{conversation_id}/messages",
        json=data,
        headers=headers,
    )
    return resp.text

@function_tool
def start_conversation(human_id: str, initial_message: str) -> str:
    """Start a new conversation with a human."""
    data = {"humanId": human_id, "message": initial_message}
    resp = requests.post(
        f"{RENTAHUMAN_API}/conversations", json=data, headers=headers
    )
    return resp.text
```

### Create and Run the Agent

```python
agent = Agent(
    name="TaskDelegator",
    instructions="""You are a task delegation agent. When the user needs something
    done in the physical world, search for qualified humans on RentAHuman,
    evaluate their profiles, and either post a bounty or start a conversation
    to hire them. Always confirm budget and requirements before creating a bounty.
    Prefer humans with high ratings and verified profiles.""",
    tools=[search_humans, get_human_profile, create_bounty, send_message, start_conversation],
)
result = Runner.run_sync(
    agent,
    "I need someone in Austin, TX to test my mobile app on different devices at a coffee shop. Budget: $50/hr.",
)
print(result.final_output)
```

### Agent with Handoffs

The Agents SDK supports handoffs between agents. Build a multi-agent system where a coordinator delegates physical tasks to a RentAHuman specialist agent:

```python
from agents import Agent, Runner
# Specialist agent for physical task delegation
physical_tasks_agent = Agent(
    name="PhysicalTasksAgent",
    instructions="""You handle all requests that require a human in the physical world.
    Search RentAHuman for qualified humans, post bounties, and manage the hiring process.""",
    tools=[search_humans, get_human_profile, create_bounty, start_conversation, send_message],
)
# Coordinator agent that routes requests
coordinator = Agent(
    name="Coordinator",
    instructions="""You are a general-purpose assistant. When the user needs something
    done in the physical world (delivery, photography, errands, inspections, etc.),
    hand off to the PhysicalTasksAgent. Handle all other requests yourself.""",
    handoffs=[physical_tasks_agent],
)
result = Runner.run_sync(
    coordinator,
    "Can you hire someone to photograph all the restaurants on 4th Street in San Francisco?",
)
```

### Async Execution with Streaming

```python
import asyncio
from agents import Runner
async def main():
    result = Runner.run_streamed(
        agent,
        "Find a handyman in Brooklyn who can assemble IKEA furniture this weekend.",
    )
    async for event in result.stream_events():
        if event.type == "raw_response_event":
            print(event.data, end="", flush=True)
asyncio.run(main())
```

### Getting Your API Key

Register your agent programmatically to get an API key:

```python
import requests
resp = requests.post(
    "https://rentahuman.ai/api/agents/register",
    json={
        "name": "My OpenAI Agent",
        "email": "agent@example.com",
        "description": "Task delegation agent built with OpenAI Agents SDK",
    },
    headers={"Authorization": "Bearer YOUR_FIREBASE_TOKEN"},
)
data = resp.json()
api_key = data["apiKey"]  # Save this — format: rah_xxxxxxxxxxxx
```

### Common Use Cases

- **Personal assistant agents** — Let your GPT-4 assistant hire humans for errands, deliveries, and appointments
- **Business automation** — Automate hiring for recurring tasks like inventory checks, site visits, and quality audits
- **Research agents** — Send humans to collect real-world data, conduct surveys, or verify information in person
- **Event coordination** — Hire multiple humans for event setup, photography, and logistics

### Best Practices

- **Use structured outputs** — The Agents SDK supports Pydantic models for tool responses. Parse RentAHuman API responses into typed models for reliable downstream processing.
- **Add guardrails** — Use the SDK's guardrails feature to prevent agents from spending over budget or contacting too many humans at once.
- **Handle rate limits** — The RentAHuman API has rate limits. Wrap your tool functions with retry logic using exponential backoff.
- **Trace your runs** — Enable the SDK's built-in tracing to debug agent decisions around hiring and payment.
- **Validate before paying** — Always have the agent confirm task details and budget with the user before creating escrow payments.
