# SDK Quick Reference

Common patterns at a glance. Both Python and TypeScript side by side.

### Installation

| SDK        | Command                      |
| ---------- | ---------------------------- |
| Python     | `pip install highflame`      |
| TypeScript | `npm install @highflame/sdk` |
| Rust       | `cargo add highflame`        |

Framework extras:

```bash
pip install 'highflame[langgraph]'
pip install 'highflame[crewai]'
pip install 'highflame[strands]'
```

***

### Client Initialization

{% tabs %}
{% tab title="Python" %}

```python
from highflame import Highflame

client = Highflame(api_key="hf_sk_...")
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { Highflame } from "@highflame/sdk";

const client = new Highflame({ apiKey: "hf_sk_..." });
```

{% endtab %}
{% endtabs %}

***

### Evaluate a Prompt

{% tabs %}
{% tab title="Python" %}

```python
resp = client.guard.evaluate_prompt("user message")
if resp.denied:
    raise PermissionError(resp.policy_reason)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
const resp = await client.guard.evaluatePrompt("user message");
if (resp.decision === "deny") {
  throw new Error(resp.policy_reason ?? "Blocked");
}
```

{% endtab %}
{% endtabs %}

***

### Evaluate a Tool Call

{% tabs %}
{% tab title="Python" %}

```python
resp = client.guard.evaluate_tool_call(
    "shell",
    arguments={"cmd": "ls /etc"},
)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
const resp = await client.guard.evaluateToolCall(
  "shell",
  { cmd: "ls /etc" },
);
```

{% endtab %}
{% endtabs %}

***

### Full GuardRequest

{% tabs %}
{% tab title="Python" %}

```python
from highflame import GuardRequest

resp = client.guard.evaluate(GuardRequest(
    content="text to evaluate",
    content_type="prompt",          # "prompt" | "response" | "tool_call" | "file"
    action="process_prompt",        # "process_prompt" | "call_tool" | "read_file" | "write_file" | "connect_server"
    mode="enforce",                 # "enforce" | "monitor" | "alert"
    session_id="sess_abc123",
))
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
const resp = await client.guard.evaluate({
  content: "text to evaluate",
  content_type: "prompt",
  action: "process_prompt",
  mode: "enforce",
  session_id: "sess_abc123",
});
```

{% endtab %}
{% endtabs %}

***

### Shield Decorators / Wrappers

{% tabs %}
{% tab title="Python" %}

```python
from highflame.shield import Shield

shield = Shield(client)

@shield.prompt
def chat(message: str) -> str: ...

@shield.tool
def shell(cmd: str) -> str: ...

@shield.toolresponse
def fetch(url: str) -> str: ...

@shield.modelresponse
def generate(prompt: str) -> str: ...
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { Shield } from "@highflame/sdk";

const shield = new Shield(client);

const chat = shield.prompt(async (msg: string) => llm.complete(msg));
const shell = shield.tool(async function shell(cmd: string) { ... });
const fetch = shield.toolResponse(async (url: string) => http.get(url));
const gen = shield.modelResponse(async (prompt: string) => llm.complete(prompt));
```

{% endtab %}
{% endtabs %}

***

### Async Evaluation

{% tabs %}
{% tab title="Python" %}

```python
resp = await client.guard.aevaluate_prompt("message")
resp = await client.guard.aevaluate(request)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
// All TypeScript methods are async by default
const resp = await client.guard.evaluatePrompt("message");
```

{% endtab %}
{% endtabs %}

***

### Error Handling

{% tabs %}
{% tab title="Python" %}

```python
from highflame import BlockedError, AuthenticationError, RateLimitError, APIError, APIConnectionError

try:
    resp = client.guard.evaluate(request)
except BlockedError as e:       # from Shield decorators only
    print(e.response.policy_reason)
except AuthenticationError as e:
    print(f"401: {e.detail}")
except RateLimitError as e:
    print(f"429: {e.detail}")
except APIError as e:
    print(f"{e.status}: {e.detail}")
except APIConnectionError as e:
    print(f"Network error: {e}")
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { BlockedError, AuthenticationError, RateLimitError, APIError, APIConnectionError } from "@highflame/sdk";

try {
  const resp = await client.guard.evaluate(request);
} catch (err) {
  if (err instanceof BlockedError) console.error(err.response.policy_reason);
  else if (err instanceof AuthenticationError) console.error(`401: ${err.detail}`);
  else if (err instanceof RateLimitError) console.error(`429: ${err.detail}`);
  else if (err instanceof APIError) console.error(`${err.status}: ${err.detail}`);
  else if (err instanceof APIConnectionError) console.error(`Network: ${err.message}`);
}
```

{% endtab %}
{% endtabs %}

***

### Enforcement Modes

| Mode        | `resp.denied` / `decision`     | `resp.alerted`     | Use for                         |
| ----------- | ------------------------------ | ------------------ | ------------------------------- |
| `"enforce"` | `True` / `"deny"` on violation | `False`            | Production enforcement          |
| `"monitor"` | Always `False` / `"allow"`     | `False`            | Shadow testing, rollout staging |
| `"alert"`   | Always `False` / `"allow"`     | `True` if violated | Alerting without blocking       |

***

### ZeroID — Issue and Verify Tokens

{% tabs %}
{% tab title="Python" %}

```python
from highflame.zeroid import ZeroIDClient

client = ZeroIDClient(base_url="https://auth.zeroid.dev", account_id="acct-demo", project_id="proj-prod")

# Register agent
reg = client.agents.register(name="My Agent", external_id="my-agent", sub_type="tool_agent", trust_level="first_party", created_by="dev@example.com")

# Issue token
token = client.tokens.issue(grant_type="api_key", api_key=reg.api_key)

# Verify locally (fast, no revocation check)
identity = client.tokens.verify(token.access_token)

# Verify with revocation check (online)
session = client.tokens.session(token.access_token)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { ZeroIDClient } from "@highflame/sdk";

const client = new ZeroIDClient({ baseUrl: "https://auth.zeroid.dev", accountId: "acct-demo", projectId: "proj-prod" });

// Register agent
const reg = await client.agents.register({ name: "My Agent", external_id: "my-agent", sub_type: "tool_agent", trust_level: "first_party", created_by: "dev@example.com" });

// Issue token
const token = await client.tokens.issue({ grant_type: "api_key", api_key: reg.api_key });

// Verify locally (fast)
const identity = await client.tokens.verify(token.access_token);

// Verify with revocation check (online)
const session = await client.tokens.session(token.access_token);
```

{% endtab %}
{% endtabs %}

***

### ZeroID Identity Helper Methods

{% tabs %}
{% tab title="Python" %}

```python
identity.has_scope("data:read")    # bool
identity.has_tool("bash")          # bool
identity.is_delegated()            # bool
identity.delegated_by()            # str | None
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
identity.hasScope("data:read");    // boolean
identity.hasTool("bash");          // boolean
identity.isDelegated();            // boolean
identity.delegatedBy();            // string | undefined
```

{% endtab %}
{% endtabs %}

***

### ZeroID + Shield — Two-Layer Pattern

{% tabs %}
{% tab title="Python" %}

```python
identity = zeroid.tokens.verify_bearer(request.headers["Authorization"])

resp = shield_client.guard.evaluate(GuardRequest(
    content=prompt,
    content_type="prompt",
    action="process_prompt",
    session_id=session_id,
    context={
        "trust_level": identity.trust_level,
        "sub_type": identity.sub_type,
        "delegation_depth": identity.delegation_depth,
        "delegated_by": identity.delegated_by(),
        "scopes": identity.scopes,
    },
))
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
const identity = await zeroid.tokens.verifyBearer(request.headers.authorization);

const resp = await shieldClient.guard.evaluate({
  content: prompt,
  content_type: "prompt",
  action: "process_prompt",
  session_id: sessionId,
  context: {
    trust_level: identity.trust_level,
    sub_type: identity.sub_type,
    delegation_depth: identity.delegation_depth,
    delegated_by: identity.delegatedBy(),
    scopes: identity.scopes,
  },
});
```

{% endtab %}
{% endtabs %}

***

### Streaming

{% tabs %}
{% tab title="Python" %}

```python
for event in client.guard.stream(request):
    if event.type == "decision":
        print(event.data.get("decision"))

# Async
async for event in client.guard.astream(request):
    if event.type == "decision":
        print(event.data.get("decision"))
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
for await (const event of client.guard.stream(request)) {
  if (event.type === "decision") {
    console.log(event.data);
  }
}
```

{% endtab %}
{% endtabs %}

***

### Client Options Reference

| Option (Python)   | Option (TypeScript) | Default          | Description                    |
| ----------------- | ------------------- | ---------------- | ------------------------------ |
| `api_key`         | `apiKey`            | required         | Service key or raw JWT         |
| `base_url`        | `baseUrl`           | Highflame SaaS   | Guard service URL              |
| `token_url`       | `tokenUrl`          | Highflame SaaS   | Token exchange URL             |
| `timeout`         | `timeout`           | `30.0` / `30000` | Per-request timeout (s / ms)   |
| `max_retries`     | `maxRetries`        | `2`              | Retries on 429/5xx             |
| `account_id`      | `accountId`         | —                | Account scope                  |
| `project_id`      | `projectId`         | —                | Project scope                  |
| `default_headers` | `defaultHeaders`    | —                | Extra headers on every request |


---

# Agent Instructions: 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.highflame.ai/guides/sdk-quick-reference.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.
