Skip to main content

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

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

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):

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 StreamEvents; .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.*):

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

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

Metadata

Release files for nyxa-ai 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nyxa-ai 0.0.1
File Size Uploaded Provenance Actions
nyxa_ai-0.0.1.tar.gz 221.1 kB Without provenance Details for nyxa_ai-0.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nyxa-ai 0.0.1
File Interpreter ABI Platform Actions
nyxa_ai-0.0.1-py3-none-any.whl Python 3 none any Details for nyxa_ai-0.0.1-py3-none-any.whl

Total release size: 417.4 kB

Release files / nyxa_ai-0.0.1.tar.gz

Download URL nyxa_ai-0.0.1.tar.gz
Size 221.1 kB
Tags Source
SHA-256 checksum
How to use checksums
837aa949a37c7b8b1c0b6c4cee2dc4d72a2a4d209c246df6ca85ef5b1dfa3961
BLAKE2b-256 checksum
How to use checksums
eef9f7d8b6ef1d8e4812c1b6aa69b3f03893bcca13727d184636ddc949746990
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.18 {"installer":{"name":"uv","version":"0.12.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / nyxa_ai-0.0.1-py3-none-any.whl

Download URL nyxa_ai-0.0.1-py3-none-any.whl
Size 196.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0b964b23cdc6801796dc4bec7476e064bc5fbbe160bc8e6ac8af19eb73c2ce3f
BLAKE2b-256 checksum
How to use checksums
48cfaa2f61f4530a4b593b805031b56e55ac7fc40b39472da369c95b0e4a0888
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.18 {"installer":{"name":"uv","version":"0.12.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for nyxa-ai 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page