Metadata-Version: 2.3
Name: hikigai-agentsdk
Version: 0.3.4
Summary: Official Python SDK for building, deploying, and managing HIPAA-compliant AI agents on the Hikigai healthcare platform. Supports Google ADK agent types (LLM, Sequential, Parallel, Loop), MCP connector integration, BYOK model configuration, and one-line Cloud Run deployment.
Project-URL: Homepage, https://hikigai.ai
Author-email: Sai Daya Shankar <sshankar@hikigai.ai>
License: MIT License
        
        Copyright (c) 2026 Hikigai
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
Keywords: agents,ai,deployment,hikigai,llm
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: hikigai-core<0.3.0,>=0.2.9
Requires-Dist: pydantic>=2.0.0
Requires-Dist: typing-extensions>=4.0.0
Provides-Extra: dev
Requires-Dist: mypy>=1.0.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: live
Requires-Dist: websockets>=13.0; extra == 'live'
Description-Content-Type: text/markdown

# hikigai-agentsdk

Python SDK for deploying and managing AI agents on the Hikigai platform.

## Installation

```bash
pip install hikigai-agentsdk
```

This will automatically install `hikigai-core` (the shared namespace dependency) alongside
`hikigai-agentsdk`.

Pin a version if needed:

```bash
pip install hikigai-agentsdk==0.3.4
```

## Quick Start

```python
from hikigai.agentsdk import AgentClient, AgentConfig, InputSchema, OutputSchema, StringField

# Run `hikigai login` once (your role must allow deploying), then:
client = AgentClient()

# Deploy an agent
agent = client.deploy(AgentConfig(
    name="my-agent",
    display_name="My AI Agent",
    description="A helpful AI assistant",
    instruction="You are a helpful assistant that answers questions",
    model="claude-3.5-sonnet",
    input_schema=InputSchema(fields={"message": StringField(required=True)}),
    output_schema=OutputSchema(fields={"response": StringField()}),
    tools=[],
    timeout=60,
    memory_mb=512,
    version="1.0.0"
))

print(f"Agent deployed! ID: {agent.id}")
```
## Authentication

There is nothing to paste. The same code runs on your computer and in your
deployed App; the SDK picks the right credential:

| Where | How | Lasts |
|---|---|---|
| Your computer (local development) | `hikigai login` once, Approve in the browser | 6 hours, one project, your role |
| Inside an App deployed on Hikigai | `HIKIGAI_API_KEY` injected by the platform | 5-minute token, renewed by the SDK |

### On your computer: `hikigai login`

Installing this package gives you the `hikigai` command:

```bash
hikigai login                  # opens the browser: pick the project, check the code, Approve
hikigai login --project <id>   # or name the project here
hikigai whoami                 # who, which project, time left
hikigai token                  # print the token (curl / Postman: Authorization: Bearer <token>)
hikigai logout                 # end it now
```

The sign-in is saved in `~/.hikigai/credentials.json` (readable only by you)
and `AgentClient()` with no arguments uses it. It works for one project, with your
role in that project, for 6 hours: invoke, stream, live voice, rooms, speech,
MCP, and deploy / manage if your role allows. See or end your sign-ins in the
console under **CLI logins**. It does not work inside deployed Apps. To use a
local platform: `hikigai login --platform-url http://localhost:8000` and
`AgentClient(base_url="http://localhost:8000")`.

### Inside a deployed App

No credentials are needed. The platform injects `HIKIGAI_API_KEY` (a Deploy
key, `hikigai_deploy_...`), `HIKIGAI_PROJECT_ID`, `HIKIGAI_APP_ID`,
`HIKIGAI_PLATFORM_URL` (the platform helper inside the App; use it for all
platform calls) and `HIKIGAI_PUBLIC_PLATFORM_URL` (the public address, for
browsers) into the container, and the SDK reads them:

```python
client = AgentClient()  # reads the injected env vars
```

The SDK exchanges the Deploy key for a workload token
(`POST $HIKIGAI_PLATFORM_URL/api/v1/auth/exchange`; the platform adds the cloud
identity proof for you); the token lasts 5 minutes and is renewed
automatically. The SDK caches it and retries once on 401.

Order: explicit `api_key=` / `project_id=` / `base_url=` arguments, then the
`HIKIGAI_*` environment variables, then your `hikigai login`. Project API keys
were removed: an old one gets `PROJECT_KEYS_REMOVED`.

Errors from the platform carry a machine-readable code on the exception
(`err.code`) and a readable `err.message`: `DEPLOY_KEY_REQUIRED`,
`INVALID_KEY` and `CLI_SESSION_INVALID` (login ended or revoked: run
`hikigai login`) raise `AuthenticationError` (401); `KEY_PROJECT_MISMATCH`,
`CLI_PROJECT_MISMATCH`, `CLI_SESSION_NOT_ALLOWED`, `APP_DEPLOY_REQUIRED`,
`APP_STOPPED`, `REQUIRES_ATTESTATION`, `PLATFORM_NETWORK_REQUIRED` and
`DEPLOY_KEY_NOT_ALLOWED` raise `PermissionDeniedError` (403); `RATE_LIMITED`
raises `RateLimitError` (429).

## Direct API Methods (Alternative Approach)

For custom integrations or when you need direct HTTP control, you can call the API endpoints directly:

### Authentication Flow

**Step 1: Sign in and take the token**

Run `hikigai login` once, then send the token from `hikigai token` on every
call. It works for the project you signed in to, with your role there (6
hours). It is not exchanged for another token (`/api/v1/auth/exchange` only
accepts a deployed App's Deploy key).

```bash
curl --location 'http://localhost:8000/api/v1/agents/my-agent/status' \
--header "Authorization: Bearer $(hikigai token)" \
--header 'X-Project-ID: YOUR_PROJECT_ID'
```

### Step 2: Deploy Agent via API

**Python Example:**

```python
import os
import subprocess

import requests


class HikigaiAPIClient:
    """Deploy / manage with your `hikigai login` token, sent as it is on every call."""

    def __init__(self, token: str, project_id: str, base_url: str = "http://localhost:8000"):
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {token}",  # from `hikigai token`
            "X-Project-ID": project_id,
            "Content-Type": "application/json",
        }

    def deploy_agent(self, config: dict) -> dict:
        """Deploy an agent via API."""
        response = requests.post(f"{self.base_url}/api/v1/agents/deploy", headers=self.headers, json=config)
        response.raise_for_status()
        return response.json()


# Deploy agent
client = HikigaiAPIClient(
    token=subprocess.check_output(["hikigai", "token"], text=True).strip(),
    project_id=os.environ["HIKIGAI_PROJECT_ID"],
)
config = {
    "name": "medical-coder",
    "display_name": "Medical Coding Assistant",
    "description": "Extracts ICD-10 and CPT codes",
    "instruction": "You are a medical coding expert...",
    "model": "claude-3.5-sonnet",
    "timeout": 60,
    "memory_mb": 512,
    "input_schema": {
        "fields": {
            "clinical_note": {"type": "string", "required": True}
        }
    },
    "output_schema": {
        "fields": {
            "icd10_codes": {"type": "array"},
            "cpt_codes": {"type": "array"}
        }
    },
    "tools": []
}

result = client.deploy_agent(config)
print(f"Agent deployed! ID: {result['agent_id']}")
```

For complete API documentation, see the [Python AgentSDK Docs](../docs/sdk/agentsdk.md#direct-api-methods).
## Platform Events

React to platform facts (`agent.deployed`, `agent.deleted`, `job.*`,
`invocation.completed`) instead of polling. Register a signed webhook, or open a live
stream:

> Runs inside a deployed App (`AgentClient()` with no arguments), or on your
> computer after `hikigai login`.

```python
sub = client.events.create_webhook(
    url="https://app.example.com/hooks/hikigai",
    event_types=["agent.deployed", "agent.deleted"],
)
print(sub.secret)   # shown ONCE — store it in your secret manager
```

Verify every delivery before trusting it — over the **raw** body, since
re-serializing parsed JSON will not reproduce the signed bytes:

```python
from hikigai.agentsdk import parse_webhook_event, SignatureVerificationError

try:
    event = parse_webhook_event(
        secret=os.environ["HIKIGAI_WEBHOOK_SECRET"],
        signature_header=request.headers["X-Hikigai-Signature"],
        body=request.get_data(as_text=True),
    )
except SignatureVerificationError:
    return "", 400
```

Deliveries are at-least-once, so dedupe on `event["id"]`. For a live
subscription instead of an endpoint (`pip install 'hikigai-agentsdk[live]'`):

```python
async with client.events.stream(patterns=["agent.*"]) as stream:
    async for event in stream:
        print(event["type"], event["data"])
```

See the [Platform Events guide](../docs/sdk/agentsdk.md#platform-events-webhooks--live-stream).


## Rooms & WebRTC

### SFU Mode (Recommended for agents in calls)

Join rooms via HTTP with SFU (Selective Forwarding Unit) for voice agents to
participate in multi-party calls:

```python
import os
from hikigai.agentsdk.rooms import connect_media

# Get media token for agent to join call (inside the deployed App)
media = await connect_media(
    base_url=os.environ["HIKIGAI_PLATFORM_URL"],
    room="support-call-123",
    api_key=os.environ["HIKIGAI_API_KEY"],
    project_id=os.environ["HIKIGAI_PROJECT_ID"],
    agent_id="agent_support",
)

print(media["token"])      # JWT for hikigai-media
print(media["sfu_url"])    # platform-provided; don't hardcode
print(media["ice_servers"]) # STUN/TURN config

# Use with aiortc to:
# 1. Join SFU with WHIP (HTTP SDP exchange)
# 2. Send agent's TTS audio track
# 3. Receive user audio for STT
# 4. Use DataChannels for in-call events
```

**Agent Use Cases:**
- Voice agents in customer support calls
- AI moderators in multi-party rooms
- Real-time transcription/translation agents
- In-call coaching assistants

Use `RoomSession` for WebSocket pub/sub (join/publish/who/presence) — not for
media. For calls, use `connect_media` above.

**See:** [FEATURES-WEBRTC-ROOMS.md](../docs/FEATURES-WEBRTC-ROOMS.md) for topology comparison and integration guide.


## Features

- 🚀 **Simple Deployment**: Deploy agents with a single function call
- 🔧 **Tool Integration**: Add custom tools, OpenAPI specs, or MCP servers
- 📊 **Schema Validation**: Define input/output schemas for type safety
- ☁️ **Multi-Cloud**: Deploy to GCP Cloud Run, GCP Agent Engine, or AWS Bedrock
- 🔒 **HIPAA Compliant**: Built-in compliance checking
- 📈 **Versioning**: Semantic versioning support
- 🔔 **Platform Events**: Signed webhooks + live event stream via `client.events`
- 📞 **Rooms & WebRTC**: WebSocket pub/sub rooms + SFU media via `connect_media`

## Documentation

Full documentation: 

## License

MIT
