Metadata-Version: 2.4
Name: nyxa-ai
Version: 0.0.1
Summary: Agents, tools, RAG, streaming, and HITL for the Nyxa framework
Author-email: Al-Amin Islam Nerob <alamin@aincoder.com>
License-Expression: MIT
Project-URL: Repository, https://github.com/NyxaDev/Nyxa
Requires-Python: >=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: nyxa>=0.0.1
Requires-Dist: pydantic-ai-slim<2.0,>=1.0
Requires-Dist: httpx>=0.27
Provides-Extra: openai
Requires-Dist: pydantic-ai-slim[openai]<2.0,>=1.0; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: pydantic-ai-slim[anthropic]<2.0,>=1.0; extra == "anthropic"
Provides-Extra: gemini
Requires-Dist: pydantic-ai-slim[google]<2.0,>=1.0; extra == "gemini"
Provides-Extra: mcp
Requires-Dist: nyxa-mcp>=0.0.1; extra == "mcp"
Requires-Dist: pydantic-ai-slim[mcp]<2.0,>=1.0; extra == "mcp"
Provides-Extra: ag-ui
Requires-Dist: pydantic-ai-slim[ag-ui]<2.0,>=1.0; extra == "ag-ui"
Provides-Extra: sqlite-vec
Requires-Dist: sqlite-vec>=0.1; extra == "sqlite-vec"
Provides-Extra: pgvector
Requires-Dist: pgvector>=0.3; extra == "pgvector"
Provides-Extra: local-embeddings
Requires-Dist: model2vec<1,>=0.10; extra == "local-embeddings"
Provides-Extra: all
Requires-Dist: nyxa-ai[ag-ui,anthropic,gemini,mcp,openai]; extra == "all"
Requires-Dist: nyxa-ai[local-embeddings,pgvector,sqlite-vec]; extra == "all"
Dynamic: license-file

# nyxa-ai

AI agents, tools, RAG, streaming, and human-in-the-loop approvals for
the Nyxa framework — declarative `Agent` classes on a pluggable
provider layer (pydantic-ai engines), typed tools with approval
gates, conversations, classification/reranking, hosted file stores,
media generation, queueing, SSE/AG-UI streaming, and a complete fake
suite. `import nyxa_ai` is lazy — no engine or provider SDK loads until
used.

## Features

- **Declarative agents** — `class Support(Agent[Answer])`: class attrs
  for `instructions`, `tools`, `output` (pydantic type), `provider`,
  `model`, `temperature`/`top_p`/`max_tokens`, `max_steps`, `timeout`,
  `retries`, `conversational`, `middleware`, `skills`,
  `provider_options`/`model_settings`, prompt caching
  (`cache_instructions`, `cache_tool_definitions`), model tiers
  (`use_cheapest_model`/`use_smartest_model`), and
  `without_broadcasting`. `get_*` hooks supply dynamic values.
- **Prompting** — `await agent.prompt(text)` → `AgentResponse[T]`
  (`.text`, `.parsed`, `.usage`, steps); `agent.stream(text)` →
  `StreamableAgentResponse` (SSE-renderable from routes, Vercel AI
  SDK v5 + AG-UI protocols, `broadcast_on` channel fan-out);
  `await agent.queue(text)` → `QueuedAgentResponse` with
  `.then`/`.catch`; conversations via `for_user`/`for_participant`/
  `continue_`/`continue_last_conversation`.
- **Tools** — `Tool` subclasses declare a pydantic `Args` model +
  `handle(args, ctx)`; approval gates via `require_approval()` /
  `needs_approval()` / `Approval`. Built-ins: `web_search`,
  `web_fetch`, `code_execution`, `file_search` (with
  `FileSearchFilter`), `ToolSearch` (strategy-filtered tool sets),
  `mcp_stdio`/`mcp_http` clients and `MCPServerTool` remote wrappers,
  `NativeTool` provider-side tools, `LoadSkill`.
- **Skills** — `Skill` bundles (`SKILL.md` + files) from dirs,
  objects, or lazy callables; `resolve_skills`; `LoadSkill` tool
  loads them into context.
- **HITL approvals** — tool calls pause the run into a
  `PendingApprovalStore` (memory or database, TTL'd); resolve with
  `app.ai.approve(run_id)` / `deny(run_id, reason)` /
  `decide(run_id, Decisions)`; `Decisions` per-call approve/reject
  with `approve_remaining`/`reject_remaining`.
- **Conversations** — `Conversation` records + `ConversationStore`
  protocol (memory + database stores; messages as serialized blobs,
  `group_messages`, `page`); `manager.conversations()`,
  `conversation_messages()`, `pending_approvals_for()`.
- **Manager** — `app.ai`: `agent(...)`, `summarize`, `classify`,
  `choose`, `rerank`/`rerank_items`, `image`, `audio`,
  `transcription`, `embed`/`embeddings`, `stores`, `engine()`/
  `extend(engine)`, `resolve`/`provider_config`, `approve`/`deny`/
  `decide`, and the fake suite.
- **Media** — `app.ai.image(prompt)` (`.quality`/`.portrait`/
  `.landscape`/`.square`/`.attachments`), `audio`, `transcription`
  builders → `generate()`/`queue()` → `ImageResponse`/`AudioResponse`/
  `TranscriptionResponse` with `GeneratedImage`/`TranscriptionSegment`/
  usage types.
- **RAG** — `VectorStore` protocol with `MemoryVectorStore`,
  `SqliteVecStore`, `PgVectorStore` (`vector_store_for(app)`);
  `SimilaritySearch` tool (`using_model(Model, column="embedding")`);
  hosted `FileStorage`/`FileStorageTools` and `stores()` CRUD
  (create/attach/detach/delete) over provider vector stores.
- **Classification & reranking** — `app.ai.classify(content)` with
  `Boolean`/`Choice`/`Score` question types → `BooleanAnswer`/
  `ChoiceAnswer`/`ScoreAnswer` in `ClassificationResponse`;
  `rerank(documents)` → `RerankResponse`/`RerankResult`/`RerankUsage`;
  `choose` helper.
- **Chat surface** — `ChatRequest`/`ChatProtocol` parse Vercel AI SDK
  and AG-UI bodies (with pending `Decisions`); `to_ui_messages` /
  `to_client_state` serialize history back for clients.
- **Queueing** — `InvokeAgent`/`InvokeMedia` jobs run prompts and
  media generation on `nyxa-jobs`; `QueuedAgentResponse`/
  `QueuedMediaResponse` futures; `broadcast_agent_on_queue` streams
  progress on a broadcast channel.
- **Events** — full lifecycle telemetry: prompting/steps/tool calls/
  approvals/streaming/classify/rerank/media/files/stores/failover —
  all emitted on `app.events`.
- **Engine seam** — `Engine` protocol with `AgentSpec`, `ToolSpec`,
  `ModelRef`, `EngineResult`, `EngineStream`, `StreamEvent`,
  `StepView`; `manager.extend(engine)` plugs new engines (pydantic-ai
  - OpenAI-responses engines ship).
- **CLI + kit** — `nyxa add nyxa-ai`, `ai:install`, `make:agent`
  (`--structured/--conversational/--test`), `make:tool` (`--approval`),
  `eval:run`, `eval:gate --min=`, `nyxa utils` embedding-model
  download; `AiKit` scaffolds an `nyxa new` AI app with a `/chat`
  route; `Eval`/`EvalCase`/`EvalResult` drive evals.
- **Testing** — `MyAgent.fake(responses)` / `app.ai.fake()`,
  `fake_media`, `fake_classification`, `fake_reranking`,
  `fake_files`, `fake_stores`, `prevent_stray_prompts`,
  `assert_queued`, `clear_fakes`.
- **Errors** — typed failures for stray prompts, decisions mismatch,
  missing keys/extras, provider capability/config, queue unavailable,
  media serialization, skills, tool search, untrusted locators.

## Install

```bash
nyxa add nyxa-ai                   # writes config/ai.py
nyxa add "nyxa-ai[openai]"         # or [anthropic] / [gemini] / [mcp] / [ag-ui]
```

Set provider keys in `config/ai.py` (`ai.providers.<name>.api_key`
etc.) or env vars.

## Usage

```python
from nyxa_ai import Agent, Tool, ToolContext


class Weather(Tool):
    class Args(BaseModel):
        city: str

    async def handle(self, args: Args, ctx: ToolContext) -> str:
        return f"Sunny in {args.city}"


class Assistant(Agent):
    instructions = "You are helpful."
    tools = [Weather]
    conversational = True


agent = Assistant().for_user(user)
response = await agent.prompt("Weather in Paris?")
response.text  # final text
response.usage.total_tokens  # accounting
```

Streaming from a route (SSE via the response renderer):

```python
async def chat(ctx):
    return Assistant().stream("Tell me a story").vercel(5)
```

## Public API

### Agents

- **`Agent[T]`** — declarative base: `Agent.make(**kwargs)`,
  `await agent.prompt(text, **opts) -> AgentResponse[T]`,
  `agent.stream(text)` / `await agent.queue(text)` /
  `agent.broadcast_on_queue(text, channel)`,
  `agent.for_user(owner)` / `for_participant` / `continue_(id, as_)` /
  `continue_last_conversation(owner)`, `name`, `description`,
  `get_instructions`/`get_tools`/`get_messages`/`get_middleware`/
  `get_skills`, `Agent.fake(responses)`, `Agent.prevent_stray_prompts()`,
  `Agent.clear_fakes()`.
- **`AnonymousAgent`** — untyped ad-hoc agent (`manager.agent(...)`
  product).
- **`StepMiddleware`** — `handle(step: StepView, next)` protocol for
  per-step interception.
- **`ToolDecl`** / **`MiddlewareDecl`** — declaration value types.

### Manager + provider

- **`AiManager`** — bound as `app.ai` (see Features → Manager).
- **`AiProvider`** — binds `app.ai`, publishes `ai.*` config,
  registers the `StreamableAgentResponse` SSE renderer, the five
  commands, the `nyxa utils` embedding action, and `configure()`.

### Responses / streaming / chat

- **`AgentResponse[T]`** — `.text`, `.parsed` (structured output),
  `.usage`, steps/records.
- **`StreamableAgentResponse[T]`** — async-iterates `StreamEvent`s;
  `.vercel(version=5)`, `.ag_ui(thread_id, run_id)`, `.using_protocol`,
  `.broadcast_on(channel)`, `.then(fn)`, `await .result()`,
  `.to_response()` (SSE).
- **`StreamProtocol`** — encoder protocol for custom wire formats.
- **`ChatRequest`** / **`ChatProtocol`** — parsed chat body (Vercel /
  AG-UI) incl. `Decisions`.
- **`to_ui_messages(stored)`** / **`to_client_state(...)`** — history
  serialization for clients.

### Tools

- **`Tool`** — subclass with `Args` model; `handle(args, ctx)`,
  `needs_approval(args)`, `require_approval(reason=None)`,
  `without_approval()`, `name`, `tool_spec(ctx)`.
- **`ToolContext`** — per-run context (`.container`, `.bind(run_ctx)`).
- **`Approval`** — approval requirement value.
- **`NativeTool`** — provider-side tool wrapper.
- **`MCPServerTool`** — adapts a remote MCP tool (`mcp_client()`,
  `name`, `tool_spec`, `handle`).
- **`ToolSearch`** — `ToolSearch(tools, strategy=None)` — searchable
  tool-set wrapper (raises `ToolSearchUnsupportedError` when the
  provider can't search).
- **`mcp_stdio(command, args=None, **kw)`** / **`mcp_http(url, **kw)`**
  — MCP client factories.
- **`web_search` / `web_fetch` / `code_execution` /
  `file_search(vector_store_ids, filters=..., max_results=...)`** —
  built-in native tool factories.

### Engine seam

- **`Engine`** — engine protocol (`manager.extend()`).
- **`AgentSpec`** / **`ToolSpec`** / **`ModelRef`** — resolved agent/
  tool/model references.
- **`EngineResult`** / **`EngineStream`** / **`StreamEvent`** /
  **`StepView`** — run results, event streams, and the middleware
  step view.

### Messages

- **`Message`** / **`StoredMessage`** / **`MessagePage`** — conversation
  units and pagination.
- **`Usage`** — token accounting.
- **`StepRecord`** — persisted per-step record.
- **`PendingApproval`** — an unresolved tool approval in a stored run.

### Conversations + approvals

- **`Conversation`** — record with `participant()` owner resolution.
- **`ConversationStore`** — protocol: `create`/`load`/`latest`/
  `append`/`list`/`messages`/`describe_messages`/
  `conversation_belongs_to`/`pending_approvals_for` (memory + db
  drivers; `ai.conversations.store`).
- **`PendingRun`** — serialized paused run (`.to_json()`/`.from_json`).
- **`PendingApprovalStore`** — protocol: `save`/`load`/`delete`/
  `find_for_conversation`/`prune` (`ai.approvals.store`, `ttl`).
- **`Decision`** — `Decision.approve(args=None)` / `.reject(reason)` /
  `.is_bare_reject`.
- **`Decisions`** — `Decisions()` → `.approve(id, args)` / `.reject(id,
  reason)` / `.approve_remaining()` / `.reject_remaining()` /
  `.resolve(pending)`.

### Classification + reranking

- **`Classification`** — facade over `manager.classify`.
- **`Boolean` / `Choice` / `Score`** — question types; answers are
  **`BooleanAnswer` / `ChoiceAnswer` / `ScoreAnswer`** in
  **`ClassificationResponse`**.
- **`RerankResponse` / `RerankResult` / `RerankUsage`** — rerank
  output types.

### Skills + file storage

- **`Skill`** — a `SKILL.md` bundle; **`resolve_skills(sources)`**;
  **`LoadSkill`** — the loader tool.
- **`FileStorage`** / **`FileStorageTools`** — hosted file store
  accessor + its tools.

### Media

- **`ImageResponse` / `AudioResponse` / `TranscriptionResponse`** —
  generation results (`generate()`/`queue()`).
- **`GeneratedImage` / `ImageUsage` / `TranscriptionSegment` /
  `TranscriptionUsage` / `MediaSource`** — value types.

### Queueing

- **`InvokeAgent` / `InvokeMedia`** — the queue jobs.
- **`QueuedAgentResponse` / `QueuedMediaResponse`** — job futures with
  `.then(fn)` / `.catch(fn)`.

### Attachments

- **`Attachment`** / **`Image` / `Document` / `Video` / `Audio` /
  `FileRef`** — prompt attachment types.

### Testing

- **`AgentFake`** — `Agent.fake()`/`manager.fake()`: canned responses,
  recorded prompts, assertions.
- **`MediaFake` / `RecordedMediaCall`** — `manager.fake_media()`:
  recorded generate calls.
- **`ClassificationFake`** — `manager.fake_classification(...)`.
- **`RerankingFake`** — `manager.fake_reranking(...)`.
- **`FilesFake`** — `manager.fake_files()`: `upload`/`retrieve`/
  `remove`, `assert_uploaded`/`assert_deleted`/
  `assert_nothing_uploaded`.
- **`StoresFake`** — `manager.fake_stores()`: `create`/`get`/`delete`/
  `attach`/`detach`/`members`.

### Events (emitted on `app.events`)

`AgentPrompting`/`AgentPrompted`, `AgentQueued`,
`AgentResponseStreamed`, `StartingStep`/`StepCompleted`/`StepFailed`,
`InvokingTool`/`ToolInvoked`/`ToolFailed`, `ToolCallStarted`/
`ToolCallFinished`, `ToolApprovalRequested`/`ToolApprovalResolved`,
`ApprovalRequested`/`ApprovalResolved`, `FailoverTriggered`,
`Classifying`/`Classified`, `Reranking`/`Reranked`,
`GeneratingImage`/`ImageGenerated`, `GeneratingAudio`/`AudioGenerated`,
`GeneratingTranscription`/`TranscriptionGenerated`, `StoringFile`/
`FileStored`, `AddingFileToStore`/`FileAddedToStore`,
`RemovingFileFromStore`/`FileRemovedFromStore`, `CreatingStore`/
`StoreCreated`/`StoreDeleted`, `FileDeleted`.

### Errors

`AiError` (base), `AgentOutputError`, `ApprovalError`,
`ApprovalNotResumableError`, `ConversationError`,
`ConversationNotFoundError`, `ConversationConflictError`,
`ConversationOwnershipError`, `DecisionsMismatchError`,
`MediaSerializationError`, `MissingExtraError`, `MissingKeyError`,
`ProviderCapabilityError`, `ProviderConfigError`,
`QueueUnavailableError`, `SkillError`, `StrayPromptError`,
`ToolSearchUnsupportedError`, `UnknownProviderError`,
`UntrustedLocatorError`.

## Configuration

`nyxa add nyxa-ai` writes `config/ai.py` (the `config` dict's keys
namespace as `ai.*`):

```python
config = {
    "default": None,  # default provider name
    "providers": {},  # {name: {driver, api_key, models…}}
    "conversations": {"store": "memory"},  # "memory" | "database"
    "approvals": {"store": "memory", "ttl": 3600},
    "embeddings": {"dimensions": None},
}
```

Model tiers `models.text.cheapest`/`models.text.smartest` resolve via
`use_cheapest_model`/`use_smartest_model`.

## Testing

```python
from nyxa_ai import Agent

Assistant.fake(["hello"])
resp = await Assistant().prompt("hi")
assert resp.text == "hello"

app.ai.prevent_stray_prompts()  # any unfaked prompt raises
app.ai.assert_queued()  # a prompt was queued
app.ai.clear_fakes()
```

## License

MIT
