# Hikigai AgentSDK - LLM Context

## Overview

`hikigai-agentsdk` - Python SDK for deploying and managing AI agents on the Hikigai platform. It supports single-agent (LLM) and multi-agent workflows (Sequential, Parallel, Loop), MCP connectors, and healthcare-specific metadata tracking.

## Installation

```bash
pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ hikigai-agentsdk
```

## Quick Start

### 1. Simple LLM Agent
```python
from hikigai.agentsdk import AgentClient, AgentConfig, InputSchema, OutputSchema, StringField

client = AgentClient(
    api_key="your-api-key",
    project_id="your-project-id"
)

# Deploy a simple agent
agent = client.deploy(AgentConfig(
    name="medical-summarizer",
    display_name="Clinical Note Summarizer",
    description="Summarizes clinical notes into SOAP format",
    instruction="You are a clinical assistant. Summarize the input into SOAP format.",
    model="gemini-2.0-flash",
    category="documentation",
    version="1.0.0",
    input_schema=InputSchema(fields={"note": StringField(required=True)}),
    output_schema=OutputSchema(fields={"summary": StringField()})
))
```

### 2. Multi-Agent Workflow (Sequential)
```python
from hikigai.agentsdk import AgentConfig, SubAgentConfig

config = AgentConfig(
    name="diagnostic-workflow",
    agent_type="sequential",
    sub_agents=[
        SubAgentConfig(
            name="extractor",
            model="gemini-2.0-flash",
            instruction="Extract symptoms from text",
        ),
        SubAgentConfig(
            name="analyzer",
            model="gemini-2.0-flash",
            instruction="Analyze symptoms and suggest diagnosis",
        )
    ],
    # ... rest of config
)
```

## Key APIs

### AgentClient

#### Methods
- `deploy(config: AgentConfig) -> DeployedAgent` - Deploy a new agent or workflow.
- `list_agents() -> List[DeployedAgent]` - List all deployed agents in project.
- `get_agent(agent_id: str) -> DeployedAgent` - Get agent by ID or slug.
- `update_agent(agent_id: str, update: Dict) -> DeployedAgent` - Update metadata/config and redeploy.
- `delete_agent(agent_id: str)` - Delete an agent.

### AgentConfig (Core Model)

#### Identity & Type
- `name` (str, slug format)
- `display_name` (str)
- `agent_type` (llm, sequential, parallel, loop)
- `instruction` (str) - System prompt
- `model` (str) - Default: "gemini-2.0-flash"

#### Multi-Agent & Advanced
- `sub_agents` (List[SubAgentConfig]) - For workflows.
- `planner_config` (PlannerConfig) - Enable thought-chain reasoning.
- `code_execution` (bool) - Enable Python code execution.
- `generation_config` (GenerationConfig) - temperature, max_output_tokens, etc.

#### State & Schemas
- `input_schema` (InputSchema | Dict) - Required validation.
- `output_schema` (OutputSchema | Dict) - Required validation.
- `output_key` (str) - Key to store output in workflow state.

#### Compliance & Cloud
- `hipaa_compliant` (bool) - Default: True.
- `risk_tier` (low, moderate, high, critical)
- `cloud_provider` (gcp, aws) - Default: "gcp".

### SubAgentConfig
Used for defining members of a workflow. Includes `name`, `agent_type`, `model`, `instruction`, and optional `tools`/`sub_agents`.

### PlannerConfig
Enables chain-of-thought reasoning.
- `type`: "BuiltInPlanner"
- `include_thoughts`: bool
- `thinking_budget`: int (tokens)

### EventsClient (Accessible via client.events)

Platform event bus: tenant webhooks and a live event stream. Deployment pipelines and tooling react to `job.*`, `agent.deployed`, `agent.deleted`, `invocation.completed`,
`storage.*`, `stream.*` instead of polling.

#### Webhook management
- `create_webhook(url=..., event_types=[...], description=None)` -> `WebhookSubscription` (`.secret` shown ONCE)
- `list_webhooks()` / `get_webhook(id)` / `delete_webhook(id)`
- `update_webhook(id, url=..., event_types=..., description=..., is_active=...)` - omitted fields unchanged
- `rotate_secret(id)` -> new secret (old one stops verifying immediately)
- `test_webhook(id)` -> `{"delivered": bool, "delivery": {...}}` synthetic `webhook.test` ping
- `list_deliveries(id, status=None, limit=50)` -> `[WebhookDelivery]` (`status`: pending | success | failed | dead)
- `redeliver(id, delivery_id)` - retry a failed/dead delivery now

#### Signature verification (pure functions - no client, no network)
```python
from hikigai.agentsdk import parse_webhook_event, SignatureVerificationError

event = parse_webhook_event(
    secret=os.environ["HIKIGAI_WEBHOOK_SECRET"],
    signature_header=request.headers["X-Hikigai-Signature"],
    body=request.get_data(as_text=True),   # RAW body — re-serialized JSON will NOT match
)
```
- `verify_webhook_signature(secret, signature_header, body, tolerance_seconds=300)` -> bool
- `parse_webhook_event(...)` -> envelope dict, raises `SignatureVerificationError`
- Header: `X-Hikigai-Signature: t=<unix-ts>,v1=<hex hmac_sha256(secret, "<t>.<raw-body>")>`
- Delivery is AT-LEAST-ONCE — dedupe on `event["id"]`

#### Live stream (requires `hikigai-agentsdk[live]`)
```python
async with client.events.stream(patterns=["agent.*"]) as stream:
    async for event in stream:
        print(event["type"], event["data"])
```
At-most-once, no replay cursor; `reconnect()` resumes from now.


## Integration Features

- **MCP Connectors**: Use `ConnectorConfig` to link external data (Epic, FHIR).
- **Tools**: Support for custom tools, OpenAPI fragments, and built-in tools.
- **Healthcare Spec**: Includes PHI redaction flags, clinical confidence, and safety metrics.

## Documentation

Full docs: https://docs.hikigai.com/agentsdk
