# Hikigai AppSDK - LLM Context

## Overview

`hikigai-appsdk` - Python SDK for invoking AI agents in your applications, with advanced capabilities like MCP connectors, plugins (e.g. SONA personalization), and healthcare clinical confidence/safety tracking.

## Installation

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

## Quick Start

```python
from hikigai.appsdk import AppClient

client = AppClient(
    api_key="your-api-key",
    project_id="your-project-id",
    # Optional SONA config for personalization tracking/suggestions
    sona_url="http://localhost:8002",
    sona_api_key="sona-api-key"
)

# Get an agent
agent = client.agent("medical-coder")

# 1. Basic Invocation
response = agent.invoke("Patient presents with fever and cough...")
print(response.content)

# 2. Invocation with MCP connectors and Plugins (SONA)
response = agent.invoke(
    input="Patient presents with fever and cough...",
    connectors={"epic-ehr": {"EPIC_CLIENT_ID": "xxx"}},
    plugin_context={"sona": {"user_id": "dr-smith-uuid"}}
)

if response.status == "success":
    print("Agent Content:", response.content)
    
    # Optional structured output
    if response.output:
        print("Structured Data:", response.output)
    
    # Healthcare Clinical Confidence and Safety Flags
    if response.confidence:
        print("Confidence:", response.confidence.score)
    for flag in response.safety_flags:
        print("Safety Warning:", flag.message)
        
    # SONA Personalization plugins logic
    if response.plugins and "sona" in response.plugins:
        sona_data = response.plugins["sona"]
        print("SONA Note ID:", sona_data.get("output_id"))

# 3. Stream responses
for chunk in agent.stream("Tell me a story"):
    print(chunk, end="")

# 4. Session-based conversations
session_agent = agent.with_session("user-123")
session_agent.invoke("What is diabetes?")
```

## Key APIs

### AppClient

Main client for agent invocation.

#### Initialization args
- `api_key: Optional[str]` - API key (can be sourced from `HIKIGAI_API_KEY`)
- `project_id: Optional[str]` - Project ID (can be sourced from `HIKIGAI_PROJECT_ID`)
- `base_url: Optional[str]` - Base URL for SDK requests
- `sona_url: Optional[str]` - Base URL for SONA client requests
- `sona_api_key: Optional[str]` - Headers API Key for SONA client requests

#### Methods / Properties
- `agent(agent_id: str) -> RuntimeAgent` - Get agent by slug or ID
- `list_agents() -> List[RuntimeAgent]` - List all available agents
- `sona -> SONAClient` - Allows accessing personalization features securely.

### RuntimeAgent

Represents a deployed agent ready for invocation.

#### Methods
- `invoke(input, session_id, provider, model, timeout, connectors, plugin_context) -> InvokeResponse` - Synchronous call. Returns a structured output container.
- `stream(...) -> Iterator[str]` - Stream agent textual chunks
- `with_session(session_id: str) -> RuntimeAgent` - Create session-based context

### InvokeResponse

Rich structured response from agent invocation including healthcare metadata.

#### Fields
- `content` (str) - Response content
- `status` (str) - success, error, etc.
- `output` (Dict, optional) - Rich dictionary response
- `confidence` (ClinicalConfidence, optional) - Contains `.score`, `.quality_metrics`, `.reasoning`
- `safety_flags` (List[SafetyFlag]) - Each flag has a `.severity` and `.message`
- `citations` (List[ClinicalCitation])
- `metadata` (InvocationMetadata) - Latency, token usage, tool calls, phi-redaction flag, trace ID.
- `plugins` (Dict, optional) - SONA output_id, etc.

### SONAClient (Accessible via client.sona)

Manages note-writing patterns securely per-user.

#### Methods
- `submit_edit(output_id, final_text, user_id)`
- `approve_output(output_id, user_id)`
- `get_preferences(user_id)`
- `update_preferences(user_id, agent_id, **kwargs)`
- `get_suggestions(user_id)`
- `respond_to_suggestion(pattern_id, response)`

## Error Handling

Core exceptions: `HikigaiError`, `AuthenticationError`, `RateLimitError`, `AgentNotFoundError`, `InvocationError`, `ConfigurationError`.

```python
try:
    response = agent.invoke("input")
except AuthenticationError:
    print("Invalid API key")
except InvocationError as e:
    print(f"Failed to run: {e}")
```

## Documentation

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