# yera 0.5.0 documentation Source: https://yera-labs.io/docs/ # Docs Our docs follow a system called Diátaxis. ## Yera These are the docs for the python lib Practical Theoretical Learning Tutorials Guided learning routes Conceptual Design & key concepts Working How-to guides Solve problems Reference Technical documentation ## Yera Link ●Not yet available. --- Source: https://yera-labs.io/docs/yera/tutorials/ # Tutorials *Learn Yera by Building Real Apps* These tutorials guide you through building real Yera applications, from your first install to a production deployment. Each section builds on the last. If you are new to Yera, start with the Quickstart. **Quickstart**: Install Yera and run your first application. **Basic Apps**: Build a conversational chatbot and a data processing pipeline. **Tools**: Build apps with tool-calling to reach out to external systems and Python libraries. **User Interfaces**: Orchestrate front-end elements from your Yera application. **Agents**: Build multi-agent system for complex workflows. Understand how context is shared between them. **Deployment**: Move your application from local development to a hosted environment. **Security & Permissions**: Implement authentication and permission controls in a realistic scenario. **Governance**: Learn about Yera's governance features for secure, compliant applications once they're up and running. --- Source: https://yera-labs.io/docs/yera/tutorials/quickstart/ # Quickstart *Install Yera and run your first app* By the end of this section you will have Yera installed and a working application running on your machine via the Yera CLI. ## Before You Start You'll need - Python 3.10 or above - At least one supported LLM provider, configured and ready: We currently support - Anthropic and OpenAI via an API key set as an environment variable. - Azure CLI logged in - AWS CLI logged in with creds available. - Ollama running locally at localhost:11434 - llama-cpp-python and directories full of GGUF files If you're not sure which provider to use, any will work for these tutorials. ## Contents **Installation**: Install Yera and its dependencies. **Setup**: Configure Yera, find your model providers and the models they offer. **Hello**: Run the hello command and check everything's working. --- Source: https://yera-labs.io/docs/yera/tutorials/quickstart/installation/ # Installation By the end of this step, Yera will be installed on your machine. Yera requires python 3.10 and above, and is available via `PyPI`. We recommend `uv` ## Install from PyPI ```bash uv add yera ``` If you prefer `pip`: ```bash pip install yera ``` The standard install includes support for Anthropic, OpenAI, Azure, and AWS out of the box. ### Optional Extras To run models locally, install the relevant optional extra: - Llama-cpp: `uv add yera[llama-cpp]` - Ollama: `uv add yera[ollama]` ## Verifying the Install Confirm Yera is installed correctly by running: ```bash yera --version ``` You should see the current version printed in your terminal. If you see an error instead, check that your Python environment is active. ### Windows On some Windows setups the `yera` entry point isn't added to your PATH automatically. If the command above isn't found, use `python -m yera.cli` instead — it behaves identically. Anywhere these tutorials use `yera`, you can substitute `python -m yera.cli`. Alternatively, you can add the Scripts directory to your PATH to use `yera` directly. ## Next Now you have Yera installed, the next step is to configure it. --- Source: https://yera-labs.io/docs/yera/tutorials/quickstart/setup/ # Setup *Configure Yera and set up your first profile* By the end of this step, Yera will be configured with your available providers and ready to run applications. ## Running Setup ```bash yera setup ``` You'll be asked for a profile name first. A profile packages your provider connections and model defaults into a named configuration. This is useful later if you want to switch between different setups, like a work profile with AWS and a personal one with OpenAI. Hit enter to accept `default` as the name, or type your own. ## Detecting Providers Yera will scan your environment and configure connections to whatever it finds. It will not copy any credentials secrets, it will only store information on how to find them. If a provider can't be auto-detected, you may be asked whether you'd like to enter its config manually. It's fine to skip these with `n`. You can always configure additional providers later with `yera setup provider`. ## Choosing Your Default Model Once providers are configured, Yera finds the available models for each and asks you to pick a default LLM. You'll navigate a tree: ``` ├── 0: anthropic (9 models) ├── 1: aws (54 models) ├── 2: azure (2 models) ... ``` Select a provider, then a model family, then a specific model. ## Finishing Up When complete, Yera will display a summary of your new profile. --- Source: https://yera-labs.io/docs/yera/tutorials/quickstart/hello/ # Your First App *Run your first Yera application* **PLACEHOLDER** By the end of this step, you'll have a Yera application running in your browser. ## Running Hello ```bash yera hello ``` Your browser will open automatically at `http://localhost:8919` with a chat interface ready to use. ## Trying It Out You'll be greeted by hello-bot, a simple chatbot connected to Wikipedia. Ask it about anything — it will look it up and respond in the chat. When you're done, press `Ctrl+C` in your terminal to stop the app. ## What You Just Ran Here's the code behind it: [SOURCE CODE] You don't need to understand all of this yet. By the end of the Basic Apps tutorials, you'll have built something very similar — and every line will make sense. You've confirmed that Yera is installed and working. The next section moves on to building your own apps from scratch. --- Source: https://yera-labs.io/docs/yera/tutorials/basic-apps/ # Basic Apps *Build your first Yera applications* By the end of this section, you will have built two working applications: a conversational chatbot and a data processing pipeline. Along the way you'll learn the core parts of Yera's Python API. This handful of functions will be used in almost every Yera app you'll ever write. **Import**: Import Yera and explore the functions and models available to your apps. **App**: Build and run your first Yera app using the `@yr.app` decorator. **Text Input**: Accept input from the user inside a running app. **Chat**: Combine input and response into an interactive chatbot. **Struct**: Extract structured data from text using the LLM. **Pipeline**: Use `yr.Struct` to build a data processing pipeline for a cybersecurity analyst. --- Source: https://yera-labs.io/docs/yera/tutorials/basic-apps/import/ # Import Yera *Import Yera and Explore your Models* At the end of this tutorial you'll have been introduced to Yera's single-import design and how to explore your available models via the model atlases. ## Import Yera is designed so its entire Python API lives behind a single import. Just import yera ```Python import yera as yr ``` We conventionally alias it as `yr`. This will be used through the rest of the docs. That's it. `yr` is the entry point for everything you want to use. If you inspect it with tab completion or `dir(yr)` you'll see a whole bunch of stuff. We'll work our way through them throughout these tutorials, but I'd like to draw your attention to one of them in particular. ## Model Atlases Yera contains model atlases at the top-level import. For now the only one there is the one containing all your LLMs, but in future Yera will support various other models types such as text-to-speech, speech-to-text, embeddings and more. An atlas is the means by which you explore and use models in your Yera apps. It contains all the models available to your current profile. Try printing `yr.llm` ```python print(yr.llm) ``` and you should see like this ``` ┌─[llm] ├─ Default: ollama.gemma4.gemma4-31b │ ├── anthropic/ │ └── ... ├── ollama/ │ ├── gemma4/ │ │ └── gemma4-31b │ └── ... └── openai/ └── ... ``` showing the different providers and the models available in them as well as your configured default. The models and groupings all live as attributes on the atlas. Have an explore to see what you can use. We'll come to how to use models via atlases at a later tutorial, just note that your configured default will be what the apps you build will run with. ## Summary You now know about the Yera top-level import, its design and the LLM model atlas. In the next tutorial you'll build your first app. --- Source: https://yera-labs.io/docs/yera/tutorials/basic-apps/app/ # The app decorator In this tutorial you'll build your first Yera app. You'll learn about the `@yr.app` decorator and the `yr.response` function. ## The app decorator The app decorator turns a python function into a Yera app. All Yera API functions must be used within a function that has been decorated with `yr.app`. You can use it without parameters like this ```python import yera as yr @yr.app def nothing(): pass ``` Or give it inputs like so ```python import yera as yr @yr.app(name="Does Nothing") def nothing(): pass ``` this is how you can set metadata, change the model it uses, set a system prompt etc. We will come back to this in later tutorials, but for now we'll keep it simple and just use the bare `yr.app`. ## Your first app Now let's build your first app. We're going to build something that tells us what the capital of France is. Before that, let's introduce a function: `yr.response`. This function invokes the active LLM with the prompt it receives as input. ```python response_text = yr.response(prompt) ``` Let's build the app. You're going to import yera, write a function that invokes `yr.response` and then decorate the lot with `yr.app` ```python import yera as yr @yr.app def capital(): yr.response("What is the capital of France?") ``` ## Running it If you're in Jupyter, just invoke it ```python capital() ``` if you're running a python script it'll need to be inside a main guard ```python if __name__ == "__main__": capital() ``` or you can save it to `capital.py` and just run it via the command line ``` yera run capital.py ``` You should see something like this ``` ╭────────────────────────────── Startup ──────────────────────────────╮ │ Started: 2026-06-23 11:54:52 │ │ Top-level App: capital │ ╰─────────────────────────────────────────────────────────────────────╯ ╭────────────────────────────── capital ──────────────────────────────╮ │ Identifier: __main__.capital │ ╰─────────────────────────────────────────────────────────────────────╯ { "content": "What is the capital of France?" } The capital of France is **Paris**. ╭─────────────────────────────── Exit ────────────────────────────────╮ │ Completed successfully │ │ │ │ Exit code: 0 │ │ Reason: Yera program completed successfully. │ │ Return value: None │ │ │ │ Run time: 1.60 s │ ╰─────────────────────────────────────────────────────────────────────╯ ``` ## Next pass --- Source: https://yera-labs.io/docs/yera/tutorials/basic-apps/input/ # Input Handling user input in Yera. --- Source: https://yera-labs.io/docs/yera/tutorials/basic-apps/chat/ # Chat *Building a basic chatbot.* By the end of this tutorial, you will have built a functional AI chatbot that can handle user input and exit gracefully. We'll start by building the logic from scratch so you can see how the interaction loop works, and then we'll use Yera's built-in shortcuts to simplify the code. ## A Basic Interaction Loop Fundamentally, a chatbot is just a loop where the user sends a prompt, the prompt is submitted to the LLM, and receives the response. You've already seen the two pieces we'll use in that loop - `yr.text_input` lets you request text input from the user. - `yr.response` lets you send a prompt to the active LLM. Let's start by importing Yera and creating a chatbot function. You'll want a loop with the input and response bits inside ```python import yera as yr @yr.app def chatbot(): while True: prompt = yr.text_input() yr.response(prompt) ``` Try it out now. Notice that there's no easy way to quit the program, it'll just keep looping unless you force it to quit. This clearly isn't a great user experience. We don't want them stuck in there forever, so we should also add the ability to quit by typing `/quit`. Inside the loop, between the input and response we detect this, and trigger `yr.quit` and `break` out of the loop. `yr.quit` is a new function for you and represents a normal exit of a Yera program such as a user quitting. It clears up the running process and other bits that are supporting your app behind the scenes. Give it a try by running your program again, asking a few questions and then typing "/quit". You should see your chatbot exit gracefully. Here's what you should have now. ```python import yera as yr @yr.app def chatbot(): while True: prompt = yr.text_input() if prompt.startswith("/quit"): yr.quit() break yr.response(prompt) ``` ## The `yr.chat` Function The code you just wrote is a pattern used repeatedly when building interactive agents: get input, check for user quit, do something with it. Yera has a handy function that implements it for you so you don't have to keep writing it yourself. Using `yr.chat` you can build a chatbot in a few lines: ```python import yera as yr @yr.app def chatbot(): for prompt in yr.chat(): yr.response(prompt) ``` Try running this and doing the same stuff as before. You'll see it behaves the same way and exits gracefully when asked as well. ## Summary You now have your first working chatbot and know how to build interactive agent loops in Yera. In the next tutorial we'll look at `yr.Struct`, Yera's feature for extracting structured data from text. This is the first step towards building your first data pipeline. --- Source: https://yera-labs.io/docs/yera/tutorials/basic-apps/structs/ # Structs Introducing structured generation. --- Source: https://yera-labs.io/docs/yera/tutorials/basic-apps/data-pipeline/ # Data Pipelines Putting it together to make your first data pipeline. --- Source: https://yera-labs.io/docs/yera/tutorials/tools/ # Tools Placeholder content --- Source: https://yera-labs.io/docs/yera/tutorials/tools/tool/ # Tools Placeholder content --- Source: https://yera-labs.io/docs/yera/tutorials/tools/tools-with-creds/ # Tools Placeholder content --- Source: https://yera-labs.io/docs/yera/tutorials/tools/wikibot/ # Tools Placeholder content --- Source: https://yera-labs.io/docs/yera/tutorials/tools/knowledge-graph/ # Tools Placeholder content --- Source: https://yera-labs.io/docs/yera/tutorials/user-interfaces/ # User Interfaces Placeholder content --- Source: https://yera-labs.io/docs/yera/tutorials/agents/ # Agents Placeholder content --- Source: https://yera-labs.io/docs/yera/tutorials/deploy/ # Deployment placeholder --- Source: https://yera-labs.io/docs/yera/how-to-guides/ # How-to Guides Welcome to the Yera Kit How-to guides --- Source: https://yera-labs.io/docs/yera/how-to-guides/docs-in-your-ai-tools/ # Make the Docs Accessible to Your Tools *Give Cursor, Claude Code and other AI coding tools the Yera docs.* The Yera docs are available as an MCP server at `https://yera-labs.io/mcp`. Connect your AI coding tool to it and its agent can search and read these docs while it helps you build Yera apps, instead of guessing from whatever it learned in training. The server is free, read-only and needs no sign-in. When your tool connects, it also receives a short overview of how Yera fits together. ## What your tool can do with it - **Search** the docs: tutorials, the API reference and the CLI reference. - **Read** any page as Markdown. - **Browse** a section, such as every `yr` function or every `yera` command. ## Claude Code ```bash claude mcp add --transport http yera-docs https://yera-labs.io/mcp ``` ## Cursor Add the server to `.cursor/mcp.json` in your project, or to `~/.cursor/mcp.json` to use it in every project: ```json { "mcpServers": { "yera-docs": { "url": "https://yera-labs.io/mcp" } } } ``` ## VS Code Add the server to `.vscode/mcp.json` in your project: ```json { "servers": { "yera-docs": { "type": "http", "url": "https://yera-labs.io/mcp" } } } ``` ## OpenAI Codex ```bash codex mcp add yera-docs --url https://yera-labs.io/mcp ``` This adds the server to `~/.codex/config.toml`: ```toml [mcp_servers.yera-docs] url = "https://yera-labs.io/mcp" ``` ## Windsurf In the Cascade panel, open the `…` menu and choose **Open MCP config file**, then add the server. Note the key is `serverUrl`, not `url`: ```json { "mcpServers": { "yera-docs": { "serverUrl": "https://yera-labs.io/mcp" } } } ``` ## Other tools Any tool that supports remote MCP servers over Streamable HTTP can use `https://yera-labs.io/mcp`. No authentication is needed: where a tool asks, choose none. ### ChatGPT In **Settings** > **Connectors** > **Advanced settings**, turn on **Developer mode**. Then choose **Create**, paste the URL, set authentication to **No authentication**, confirm you trust it and save. ### Claude (desktop and web) In **Settings** > **Connectors**, choose **Add custom connector**, name it "Yera docs" and paste the URL. Custom connectors may need a paid Claude plan. ### Cline Under **MCP Servers** > **Remote Servers**, enter the URL and choose **Streamable HTTP**. If you edit `cline_mcp_settings.json` by hand, the type is spelled `streamableHttp`: ```json { "mcpServers": { "yera-docs": { "type": "streamableHttp", "url": "https://yera-labs.io/mcp" } } } ``` ### Continue In `~/.continue/config.yaml`: ```yaml mcpServers: - name: Yera docs type: streamable-http url: https://yera-labs.io/mcp ``` ### Gemini CLI In `~/.gemini/settings.json`, or `.gemini/settings.json` in your project (note `httpUrl`): ```json { "mcpServers": { "yera-docs": { "httpUrl": "https://yera-labs.io/mcp" } } } ``` Run `/mcp` to check it's connected. ### Goose Run `goose configure`, choose **Add Extension** > **Remote Extension (Streamable HTTP)**, and enter the URL. In the desktop app, go to **Extensions** > **Add custom extension** and choose the **Streamable HTTP** type. ### JetBrains AI Assistant In **Settings** > **Tools** > **AI Assistant** > **Model Context Protocol (MCP)**, choose **Add** and paste: ```json { "mcpServers": { "yera-docs": { "url": "https://yera-labs.io/mcp" } } } ``` ### Kiro In `.kiro/settings/mcp.json` in your project, or `~/.kiro/settings/mcp.json`: ```json { "mcpServers": { "yera-docs": { "url": "https://yera-labs.io/mcp" } } } ``` ### opencode In `opencode.json` in your project, or `~/.config/opencode/opencode.json`: ```json { "mcp": { "yera-docs": { "type": "remote", "url": "https://yera-labs.io/mcp" } } } ``` ### Zed In `~/.config/zed/settings.json`, Zed calls MCP servers context servers: ```json { "context_servers": { "yera-docs": { "url": "https://yera-labs.io/mcp" } } } ``` ## Check it works Ask your tool something like *"Using the Yera docs, how do I show a table of results?"* It should search the docs and open the `yr.table` page before it answers. ## Without MCP If your tool doesn't support MCP, point it at the docs as plain text instead: - `/llms-full.txt`: every docs page in one file. - Any docs page with `index.md` added to its address, e.g. `https://yera-labs.io/docs/yera/reference/api/table/index.md`. The docs describe the latest Yera release. If you're on an older version, some details may differ. --- Source: https://yera-labs.io/docs/yera/explanations/ # Concepts Welcome to the Yera Kit Concepts documentation. --- Source: https://yera-labs.io/docs/yera/reference/api/ # Yera Kit API *The public API of the Yera Python library* Placeholder --- Source: https://yera-labs.io/docs/yera/reference/api/app-group/ # App *The core primitives for building a Yera app.* The core decorators and utilities for defining a Yera app's structure. --- Source: https://yera-labs.io/docs/yera/reference/api/app/ # yr.app ``` app( fn: Callable | None = None, name: str | None = None, description: str | None = None, llm: LLMContext | None = None, sys_prompt: str | None = None, ) → AppFunctionWrapper | Callable[[Callable], AppFunctionWrapper] ``` Decorator that turns a Python function into a Yera app. Usable bare (`@app`) or with keyword arguments (`@app(name=..., llm=..., sys_prompt=...)`). The wrapped function's signature is validated against Yera's supported type system at decoration time; arguments and return values are coerced at call time. ## Parameters fn type: Callable | None = None The function being decorated when used bare. Left as `None` when the decorator is invoked with arguments. name type: str | None = None Display name for the app. Defaults to the function's `__name__`. description type: str | None = None Optional human-readable description recorded in the app metadata. llm type: LLMContext | None = None Optional `LLMContext` entered for the duration of each run. Falls back to the active profile's default llm if omitted. sys_prompt type: str | None = None Optional system prompt emitted once the llm context is entered. ## Returns type: AppFunctionWrapper | Callable[[Callable], AppFunctionWrapper] An `AppFunctionWrapper` callable that runs the function under the Yera event-stream runtime when invoked. When called with arguments (`fn is None`), returns a decorator that produces the wrapper. --- Source: https://yera-labs.io/docs/yera/reference/api/exit/ # yr.exit ``` exit( exit_code: int, reason: str, return_value: object, error_cause: ErrorCause | None = None, ) → None ``` End the current app run. ## Parameters exit_code type: int Process-style exit code; `0` for success, non-zero for failure. reason type: str Human-readable summary of why the run ended. return_value type: object Value to return to the caller, or `None`. error_cause type: ErrorCause | None = None Optional structured cause metadata for failure exits. See `ErrorCause`. --- Source: https://yera-labs.io/docs/yera/reference/api/quit/ # yr.quit ``` quit() → None ``` End the current app run as a user-initiated quit. Distinct from `exit`: signals that the user chose to stop rather than the app completing or failing. --- Source: https://yera-labs.io/docs/yera/reference/api/session_title/ # yr.session_title ``` session_title( title: str, ) → None ``` Set the title associated with the current session. Session-aware hosts may persist and display the title. In runtimes without sessions, the emitted metadata update has no persistent effect. ## Parameters title type: str Title to associate with the current session. --- Source: https://yera-labs.io/docs/yera/reference/api/tool/ # yr.tool ``` tool( fn: Callable | None = None, creds: str | list[str] | None = None, insert_result: bool = True, ) → DecoratedTool | Callable[[Callable], DecoratedTool] ``` Decorate a Python function as a Yera tool. Tools are self-contained chunks of Python an `@app` can call into — the app's LLM drives control flow, deciding when and with what arguments to invoke each tool. Usable bare (`@tool`) or with keyword arguments (`@tool(creds=...)`). If `creds` is provided, the named credential groups are resolved from the active Yera profile and bound to the tool's context before the function body runs; the body reads them back via `tool_creds`. ## Parameters fn type: Callable | None = None The function being decorated when used bare. Left as `None` when the decorator is invoked with arguments. creds type: str | list[str] | None = None Credential group(s) the tool needs access to. A single group name, a list of group names, or `None` for no credentials. Group names are configured in the active Yera profile; the resolved keys appear as `.` in `tool_creds`. insert_result type: bool = True whether to add the return value of this tool to the active LLM context. ## Returns type: DecoratedTool | Callable[[Callable], DecoratedTool] A `DecoratedTool` callable that resolves credentials and runs the function under the tool credential context when invoked. When called with arguments (`fn is None`), returns a decorator that produces the wrapper. ## Raises InvalidToolCredsArgumentError If `creds` is not `None`, a `str`, or `list[str]`. Example: ```python @yr.tool(creds=["db"]) def get_customer(customer_id: str) -> dict: creds = yr.tool_creds() conn = psycopg.connect( host=creds.require("db.host"), port=creds.require("db.port"), user=creds.require("db.user"), password=creds.require("db.password"), ) with conn.cursor() as cur: cur.execute("SELECT * FROM customers WHERE id = %s", (customer_id,)) return cur.fetchone() ``` --- Source: https://yera-labs.io/docs/yera/reference/api/tool_creds/ # yr.tool_creds ``` tool_creds() → ToolCreds ``` Return the active tool's credentials. Call from inside a `@tool`-decorated function to read the credentials the tool declared with `creds=...`. The returned `ToolCreds` is a read-only snapshot of the configured credential groups, flattened to dotted keys. ## Examples ```python @yr.tool(creds=["my_api"]) def call_api(prompt: str) -> str: api_key = yr.tool_creds().require("my_api.api_key") ... ``` ## Returns type: ToolCreds The active tool's credential snapshot. ## Raises RuntimeError When called outside an active tool invocation. --- Source: https://yera-labs.io/docs/yera/reference/api/workspace/ # yr.workspace The active app's workspace. Provides access to the app's memory: chat history and programmatic state. Use subscript syntax to read and write values: ## Examples ```python workspace["customer_name"] = "Alice" name = workspace["customer_name"] ``` ``` 'Alice' ``` --- Source: https://yera-labs.io/docs/yera/reference/api/chat/ # yr.chat ``` chat( stop_str: str = '/quit', ) → Generator[str] ``` Yield user prompts until one starts with `stop_str`. Repeatedly prompts the user for text input, yielding each prompt. When the user submits a prompt starting with `stop_str`, the run quits and iteration stops. ## Parameters stop_str type: str = '/quit' Prefix that, when matched, ends the chat loop. Default = "/quit" --- Source: https://yera-labs.io/docs/yera/reference/api/gen/ # yr.gen ``` gen( on_wire: bool = True, instruction: str | None = None, **kwargs, ) → str ``` Generate a response from the active LLM with optional instruction and visibility control. ## Parameters on_wire type: bool = True Whether to include the response back in the LLM context. instruction type: str | None = None Optional system instruction to guide generation (e.g., for structured outputs). **kwargs type: object Additional keyword arguments passed directly to the underlying LLM (e.g., `temperature`, `max_tokens`, etc.). ## Returns type: str The generated text response from the LLM. --- Source: https://yera-labs.io/docs/yera/reference/api/insert/ # yr.insert ``` insert( prompt: str, ) → None ``` Insert a prompt into the active LLM context. Unlike `response`, this does **not** generate a response; it merely appends the given prompt to the conversation history. ## Parameters prompt type: str The user message to insert into the LLM context. --- Source: https://yera-labs.io/docs/yera/reference/api/response/ # yr.response ``` response( prompt: str, **kwargs, ) → str ``` Send a prompt to the active LLM and return its text response. Tokens will simultaneously be pushed onto the event stream for display in your UI or printed to stdout. ## Parameters prompt type: str The user-message prompt to send. **kwargs type: str | int | float | bool Additional options forwarded to the underlying LLM (e.g. provider-specific generation parameters). ## Returns type: str The LLM's text response. --- Source: https://yera-labs.io/docs/yera/reference/api/struct/ # yr.Struct Inherits: `BaseModel` Subclasses: `Condition` Base class for structured-generation specs. Subclass `Struct` to declare the shape of a value the LLM should produce, then call `fill` on the subclass to generate a populated instance from a prompt. Unknown fields are rejected at construction time: structs are intended to be fixed in structure, separating *data* (the struct) from *behaviour* (defined elsewhere). Passing fields not declared on the subclass raises a `ValidationError`. ## Examples ```python class Person(Struct): name: str age: int occupation: str bio = "Dr. John Smith is a 36-year-old data scientist." Person.fill(bio) ``` ``` Person(name='John Smith', age=36, occupation='data scientist') ``` ## Methods __init_subclass__ — Initialise subclass with an expects result field populated. expects_result — Return whether this struct expects an LLM result. get_tool_name — Return the tool name (class name) used when calling the LLM. get_call_id — Return the stored tool call ID, or raise if unset. set_call_id — Set the tool call ID for this struct instance. fill — Generate an instance of this struct from a prompt. form — Ask the user to fill in this struct as a form. __hash__ — Hash by field values, recursively freezing containers. model_json_schema — Return the JSON schema for this struct with extra strictness applied. # Struct.__init_subclass__ ``` __init_subclass__( expects_result: bool = False, **kwargs, ) → None ``` Initialise subclass with an expects result field populated. # Struct.expects_result ``` expects_result() → bool ``` Return whether this struct expects an LLM result. # Struct.get_tool_name ``` get_tool_name() → str ``` Return the tool name (class name) used when calling the LLM. # Struct.get_call_id ``` get_call_id() → str ``` Return the stored tool call ID, or raise if unset. ## Returns type: str The call ID string assigned via `set_call_id`. ## Raises ValueError If no call ID has been set (`__call_id__` is None). # Struct.set_call_id ``` set_call_id( call_id: str, ) → None ``` Set the tool call ID for this struct instance. ## Parameters call_id type: str String identifier assigned by the LLM tool-calling API. # Struct.fill ``` fill( instruction: str | None = None, on_wire: bool = False, **kwargs, ) → Self ``` Generate an instance of this struct from a prompt. Sends the prompt to the active LLM and parses its response into an instance of the calling subclass. ## Parameters instruction type: str | None = None extra prompt instruction to inform struct generation. on_wire type: bool = False whether the llm text output from this fill is included back in the context. **kwargs type: str | int | float | bool Additional options forwarded to the underlying LLM (e.g. provider-specific generation parameters). ## Returns type: Self An instance of the calling subclass, populated from the LLM's response. # Struct.form ``` form( label: str | None = None, ) → Self ``` Ask the user to fill in this struct as a form. Each field is presented with a widget suited to its type. Submissions that fail validation are shown again with their errors until one is valid. ## Parameters label type: str | None = None Optional question shown above the form. ## Returns type: Self An instance of the calling subclass built from the accepted submission. ## Examples ```python class Deploy(Struct): service: str replicas: int = 1 Deploy.form("Deploy which service?") ``` # Struct.__hash__ ``` __hash__() → int ``` Hash by field values, recursively freezing containers. Allows `Struct` instances to be used as members in hashable containers and as `dict` keys. Mutating fields after hashing will make the instance unfindable in the collection; treat hashed structs as immutable. # Struct.model_json_schema ``` model_json_schema( by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, schema_generator: type[GenerateJsonSchema] = _StrictSchema, mode: JsonSchemaMode = 'validation', union_format: Literal['any_of', 'primitive_type_array'] = 'any_of', ) → dict ``` Return the JSON schema for this struct with extra strictness applied. Overridden to ensure all nested objects have `additionalProperties: false`. ## Returns type: dict A JSON schema dict with `additionalProperties: false` for all objects. --- Source: https://yera-labs.io/docs/yera/reference/api/sys_prompt/ # yr.sys_prompt ``` sys_prompt( prompt: str, ) → None ``` Append a line to the active LLM context's system prompt. ## Parameters prompt type: str Text to add to the system prompt for subsequent `chat` and `struct` calls in the current LLM context. --- Source: https://yera-labs.io/docs/yera/reference/api/llm/ # yr.llm The configured LLM atlas, loaded lazily on first access. Resolves LLM providers and models from the user's active Yera profile. See `LLMAtlas` for the available methods and indexing behaviour. ## Raises ProfileConfigError On first access, if no profiles are configured. Run `yera setup`. ProvidersNotConfigured On first access, if no providers are configured. Run `yera setup`. --- Source: https://yera-labs.io/docs/yera/reference/api/buttons/ # yr.buttons ``` buttons( options: list[str], label: str | None = None, ) → str ``` Present the user with a set of buttons and return their selection. ## Parameters options type: list[str] Labels for the buttons to display. label type: str | None = None Optional prompt shown above the buttons. ## Returns type: str The label of the button the user clicked. --- Source: https://yera-labs.io/docs/yera/reference/api/confirm/ # yr.confirm ``` confirm( label: str | None = None, true_option: str = 'Yes', false_option: str = 'No', ) → bool ``` Present the user with a binary choice and return True/False. ## Parameters label type: str | None = None optional prompt shown above the buttons. true_option type: str = 'Yes' the button option representing true. false_option type: str = 'No' the button option representing false. ## Returns type: bool boolean value representing whether the user chose the true or false option. --- Source: https://yera-labs.io/docs/yera/reference/api/date_picker/ # yr.date_picker ``` date_picker( label: str, default_date: date | str | None = None, ) → date ``` Present the user with a date picker. ## Parameters label type: str Prompt shown alongside the picker. default_date type: date | str | None = None Optional initial date, as a `date` or ISO-format string. ## Returns type: date The date the user chose. --- Source: https://yera-labs.io/docs/yera/reference/api/slider/ # yr.slider ``` slider( min_value: float, max_value: float, label: str, default_value: float | None = None, ) → float ``` Present the user with a slider over a numeric range. ## Parameters min_value type: float Lower bound of the slider. max_value type: float Upper bound of the slider. label type: str Prompt shown alongside the slider. default_value type: float | None = None Optional initial position. Defaults to `min_value` if not provided. ## Raises InputValueError If the submitted value is outside the slider range. ## Returns type: float The value the user selected. --- Source: https://yera-labs.io/docs/yera/reference/api/text_input/ # yr.text_input ``` text_input( message: str | None = None, ) → str ``` Prompt the user for free-form text input. ## Parameters message type: str | None = None Optional label shown alongside the input field. ## Returns type: str The text the user submitted. --- Source: https://yera-labs.io/docs/yera/reference/api/tree_selector/ # yr.tree_selector ``` tree_selector( tree: TreeSelectorSource, label: str | None = None, min_selections: int = 1, max_selections: int | None = None, ) → list[str] ``` Present a nested tree and return the selected leaf values. ## Parameters tree type: TreeSelectorSource Nested option mapping or an object implementing `__yera_tree__()`. label type: str | None = None Optional prompt shown above the tree. min_selections type: int = 1 Minimum number of leaves that must be selected. max_selections type: int | None = None Optional maximum number of leaves that may be selected. ## Raises TypeError If the source cannot provide a valid tree mapping. ValueError If the supplied tree is malformed. InputValueError If the submitted selection violates its cardinality, contains duplicates, or includes a value outside the requested tree. ## Returns type: list[str] The canonical values of the selected leaves, in submitted order. --- Source: https://yera-labs.io/docs/yera/reference/api/bar_chart/ # yr.bar_chart ``` bar_chart( data: object, x: str | None = None, y: str | Sequence[str] | None = None, colour: str | Sequence[str] | None = None, horizontal: bool = False, stack: bool = True, ) → None ``` Render a bar chart. ## Parameters data type: object Chart data; typically a pandas DataFrame. x type: str | None = None Column name to use for the x-axis. y type: str | Sequence[str] | None = None Column name (or names) to plot on the y-axis. colour type: str | Sequence[str] | None = None Column name (or names) used to colour the bars. horizontal type: bool = False Orient bars horizontally rather than vertically. stack type: bool = True Stack multiple series rather than grouping side-by-side. ## Examples ```python import pandas as pd df = pd.DataFrame({"quarter": ["Q1", "Q2", "Q3", "Q4"], "revenue": [120, 145, 98, 167]}) bar_chart(df, x="quarter", y="revenue") ``` Grouped by colour: ```python df = pd.DataFrame({ "quarter": ["Q1", "Q2", "Q1", "Q2"], "revenue": [120, 145, 98, 167], "region": ["North", "North", "South", "South"], }) bar_chart(df, x="quarter", y="revenue", colour="region", stack=False) ``` --- Source: https://yera-labs.io/docs/yera/reference/api/image/ # yr.image ``` image( content: bytes, media_type: ImageMediaType = 'image/png', alt: str | None = None, ) → None ``` Render an image from image-file bytes. The image is fitted responsively to the available display width while preserving its intrinsic aspect ratio. PNG, JPEG, WebP, GIF, and SVG images are supported. Rendering depends on the active output environment. ## Parameters content type: bytes Raw contents of a PNG, JPEG, WebP, GIF, or SVG image file. media_type type: ImageMediaType = 'image/png' MIME type identifying the supplied image format. alt type: str | None = None Optional accessible description of the image. --- Source: https://yera-labs.io/docs/yera/reference/api/line_chart/ # yr.line_chart ``` line_chart( data: object, x: str | None = None, y: str | Sequence[str] | None = None, colour: str | Sequence[str] | None = None, ) → None ``` Render a line chart. ## Parameters data type: object Chart data; typically a pandas DataFrame. x type: str | None = None Column name to use for the x-axis. y type: str | Sequence[str] | None = None Column name (or names) to plot on the y-axis. colour type: str | Sequence[str] | None = None Column name (or names) used to colour the lines. ## Examples ```python import pandas as pd df = pd.DataFrame({"time": [1, 2, 3], "value": [4, 5, 6]}) line_chart(df, x="time", y="value") ``` --- Source: https://yera-labs.io/docs/yera/reference/api/markdown/ # yr.markdown ``` markdown( content: str, ) → None ``` Render a markdown block. Can be called directly to emit a single block, or used as a stream handle to append further chunks over time. ## Parameters content type: str the markdown content to display --- Source: https://yera-labs.io/docs/yera/reference/api/spinner/ # yr.spinner ``` spinner( message: str = 'Working', glyph: str = 'run', colour: NamedColour = 'orange', end_message: str = 'Done', end_glyph: str = 'check', end_colour: NamedColour = 'green', ) → SpinnerStream ``` Show a configurable spinner while a block of work runs. The spinner may change its message, glyph, and colour while active. On successful exit it resolves to the configured completion appearance; on exceptional exit it uses the fixed failure appearance. ## Parameters message type: str = 'Working' Initial message shown alongside the spinner. glyph type: str = 'run' Initial registered glyph name. colour type: NamedColour = 'orange' Initial named colour. end_message type: str = 'Done' Message shown after successful completion. end_glyph type: str = 'check' Registered glyph shown after successful completion. end_colour type: NamedColour = 'green' Named colour shown after successful completion. ## Returns type: SpinnerStream A `SpinnerStream` context manager. --- Source: https://yera-labs.io/docs/yera/reference/api/table/ # yr.table ``` table( data: object = None, border: bool | Literal['horizontal'] = True, ) → TableStream ``` Render a table. ## Parameters data type: object = None Table data. Accepts pandas DataFrames, dicts of column lists, lists of dicts, lists of lists, or any iterable that can be converted to rows. Pass `None` for an empty table. border type: bool | Literal['horizontal'] = True `True` for full borders, `False` for none, or `"horizontal"` for horizontal lines only. ## Returns type: TableStream A `TableStream` handle whose `add_rows` method appends rows to the same table. --- Source: https://yera-labs.io/docs/yera/reference/api/condition/ # yr.condition ``` condition( instruction: str, on_wire: bool = False, **kwargs, ) → bool ``` Use the active LLM to evaluate a boolean condition. ## Parameters instruction type: str Instruction text describing what the condition checks. on_wire type: bool = False Whether the field should be included in LLM context (default: False). **kwargs type: object Additional keyword arguments passed to the model fill method. ## Returns type: bool Boolean value representing whether the condition holds. --- Source: https://yera-labs.io/docs/yera/reference/api/mcp_tools/ # yr.mcp_tools MCP tools selected by the active profile, loaded lazily. --- Source: https://yera-labs.io/docs/yera/reference/api/option/ # yr.option ``` option( label: str, description: str | None = None, ) → Option ``` Create an Option instance. ## Parameters label type: str The visible label for the option. description type: str | None = None Optional descriptive text. ## Returns type: Option An Option instance with given label and description. --- Source: https://yera-labs.io/docs/yera/reference/api/result/ # yr.result Result block implementation. --- Source: https://yera-labs.io/docs/yera/reference/api/section/ # yr.section ``` section( title: str, summary: str | None = None, auto_collapse: bool = True, glyph: str = 'thread', colour: NamedColour | None = None, ) → Section ``` Group output blocks into a mutable, collapsible section. Sections may contain ordinary output blocks or nested sections. While the context is open, its title, glyph, and colour may be changed through the returned section object. The `success()` and `error()` methods apply standard completion appearances without closing the section. In the web UI, the section may collapse automatically when its context exits. ## Parameters title type: str Heading shown in the section header. summary type: str | None = None Optional summary shown for the completed section. auto_collapse type: bool = True Whether the section collapses when it completes. glyph type: str = 'thread' Name of the glyph shown in the section header. colour type: NamedColour | None = None Optional named colour applied to the section heading. ## Returns type: Section A `Section` context manager. ## Examples ```python with section("Loading data", glyph="spinner") as current: load_data() current.success("Data loaded") ``` --- Source: https://yera-labs.io/docs/yera/reference/api/select/ # yr.select ``` select( *options, instruction: str | None = None, name: str = 'Selection', on_wire: bool = False, **kwargs, ) → str ``` Use the active LLM to choose between a set of options. ## Parameters *options type: str | Option = () One or more option labels or Option instances. instruction type: str | None = None Instruction text to describe the purpose of this selection. name type: str = 'Selection' Name for the generated class (default: "Selection"). on_wire type: bool = False Whether the field should be included in the LLM context (default: False). **kwargs type: object Additional keyword arguments passed to the model fill method. ## Returns type: str The selected option ## Raises ValueError If fewer than two options are provided or labels are not unique. --- Source: https://yera-labs.io/docs/yera/reference/api/input-group/ # Input *UI widgets for receiving input from users.* Interactive input elements for collecting text, selections, dates, and numeric values from users. --- Source: https://yera-labs.io/docs/yera/reference/api/llms-group/ # LLMs *Functions for interacting with large language models.* DSL functions for sending prompts, shaping model output, and generating structured data. --- Source: https://yera-labs.io/docs/yera/reference/api/models-group/ # Models *Access to AI model providers and capabilities.* Atlas and provider objects for accessing the AI models configured in your Yera profile. --- Source: https://yera-labs.io/docs/yera/reference/api/other-group/ # Other --- Source: https://yera-labs.io/docs/yera/reference/api/output-group/ # Output *UI blocks for displaying content to users.* Output elements for rendering text, tables, charts, and status indicators in the Yera UI. --- Source: https://yera-labs.io/docs/yera/reference/cli/ # Yera Kit CLI Placeholder --- Source: https://yera-labs.io/docs/yera/reference/cli/cred/ # yera cred Manage credential groups and secrets. # yera cred put Set a single credential leaf. ``` yera cred put KEY [VALUE] ``` ## Arguments KEY type: str (required) Exact dotted leaf key. VALUE type: str = None Credential value. Omit for interactive prompt or stdin. # yera cred get Print the plain value of a single credential leaf. ``` yera cred get KEY [--allow-missing] ``` ## Arguments KEY type: str (required) Exact dotted leaf key. ## Options --allow-missing type: bool = False Exit successfully without output if the key is absent. # yera cred list Inspect credentials for the active credential group. ``` yera cred list [PATH] [--keys-only] [--reveal] ``` ## Arguments PATH type: str = None Optional dotted namespace used to scope the output. ## Options --keys-only type: bool = False Print credential names without values. --reveal type: bool = False Print decoded values instead of redacted placeholders. # yera cred delete Delete one credential leaf. ``` yera cred delete KEY ``` ## Arguments KEY type: str (required) Exact dotted credential name. # yera cred patch Merge credential leaves into a namespace. ``` yera cred patch PATH [JSON_STR] [--from-file STR] ``` ## Arguments PATH type: str (required) Dotted namespace to merge into. JSON_STR type: str = None Inline JSON object to merge. ## Options --from-file type: str = None JSON file path, or `-` for standard input. # yera cred replace Replace all credential leaves beneath a namespace. ``` yera cred replace PATH [JSON_STR] [--from-file STR] ``` ## Arguments PATH type: str (required) Dotted namespace to replace. JSON_STR type: str = None Inline JSON object to store. ## Options --from-file type: str = None JSON file path, or `-` for standard input. # yera cred clear Delete credential leaves beneath an optional namespace. ``` yera cred clear [PATH] [--force] ``` ## Arguments PATH type: str = None Optional dotted namespace to clear. ## Options --force type: bool = False Whether destructive bulk deletion is permitted. # yera cred list-groups List all credential groups with credential counts and authorised roots. ``` yera cred list-groups ``` # yera cred use-group Set `[tool.yera.overrides] cred-group` in `pyproject.toml`. Non-interactive: does not touch credentials.json or authorised_roots. ``` yera cred use-group NAME ``` ## Arguments NAME type: str (required) Credential group name to write under `[tool.yera.overrides]`. # yera cred get-group Show active credential group or inspect a named group's metadata. ``` yera cred get-group [NAME] ``` ## Arguments NAME type: str = None Credential group name to inspect. If omitted, prints the active group name. If provided, prints the named group's metadata as JSON. # yera cred allow-group Add the current project root to a credential group's authorised roots. ``` yera cred allow-group NAME ``` ## Arguments NAME type: str (required) Credential group name to authorise for this project root. # yera cred rename-group Atomically rename a credential group in credentials.json. ``` yera cred rename-group OLD_NAME NEW_NAME ``` ## Arguments OLD_NAME type: str (required) Existing credential group name. NEW_NAME type: str (required) New credential group name. Must pass name validation. # yera cred delete-group Delete a credential group and all its credentials from credentials.json. ``` yera cred delete-group NAME [--force] ``` ## Arguments NAME type: str (required) Credential group name to delete. ## Options --force type: bool = False Must be true; the command refuses to delete without `--force`. # yera cred export-group Export a credential group as a portable protected-store document. ``` yera cred export-group NAME [--output-file PATH] ``` ## Arguments NAME type: str (required) Credential group name to export. ## Options --output-file type: Path = None Path to write the exported JSON. Uses atomic writing with restricted permissions on POSIX. Omit to write to standard output. --- Source: https://yera-labs.io/docs/yera/reference/cli/delete/ # Yera Delete The `delete` command removes configuration entries and stored data from `yera.toml`, the model universe, and `credentials.json`. Most destructive subcommands require `--force` to prevent accidental data loss. Scoped variants (`delete hub`, `delete model`, `delete cred`) target a single named entry, while plural forms (`delete hubs`, `delete models`, `delete creds`) operate in bulk and always require `--force`. # yera delete Delete config entries and Yera object data. # yera delete config Delete yera.toml. ``` yera delete config [--force] ``` ## Options --force type: bool = False Must be true; the command refuses to delete without `--force`. # yera delete provider Remove a provider or one of its connections from yera.toml. ``` yera delete provider PROVIDER_TYPE [--connection STR] [--force] ``` ## Arguments PROVIDER_TYPE type: Literal (required) choices: anthropic, openai, mistral, aws, azure, ollama, llama_cpp Provider type to remove. ## Options --connection type: str = None If set, remove only this connection rather than the entire provider. Raises an error if any Yera profile references this connection. --force type: bool = False Required when removing an entire provider. The command refuses to delete without `--force`. # yera delete providers Remove all providers from yera.toml. ``` yera delete providers [--force] ``` ## Options --force type: bool = False Must be true; the command refuses to delete without `--force`. # yera delete model Remove one model entry from the universe. ``` yera delete model MODEL_ID --connection STR --model-type LITERAL ``` ## Arguments MODEL_ID type: str (required) Yera model id to remove. ## Options --connection type: str (required) Connection name the model was discovered under. Required since the same model id can exist under multiple connections. --model-type type: Literal (required) choices: llm, embedding, tts, stt, reranker Model type of the entry to remove. # yera delete models Remove all models from the universe, optionally filtered by type. ``` yera delete models [MODEL_TYPE] [--force] ``` ## Arguments MODEL_TYPE type: Literal = None choices: llm, embedding, tts, stt, reranker If set, remove only models of this type. ## Options --force type: bool = False Must be true; the command refuses to delete without `--force`. # yera delete profile Remove a named Yera profile from yera.toml. ``` yera delete profile PROFILE_NAME ``` ## Arguments PROFILE_NAME type: str (required) Yera profile name to remove. # yera delete profiles Remove all Yera profiles and the active default from yera.toml. ``` yera delete profiles [--force] ``` ## Options --force type: bool = False Must be true; the command refuses to delete without `--force`. # yera delete mcp Remove an MCP server, its imported tools, and its stored secrets. The server is also removed from every profile that enables it. Credential-group values referenced by static headers are kept. ``` yera delete mcp SERVER_NAME ``` ## Arguments SERVER_NAME type: str (required) MCP server connection to remove. --- Source: https://yera-labs.io/docs/yera/reference/cli/doctor/ # Yera Doctor The `doctor` command inspects the credential configuration for the current project and reports whether it is correctly set up. It checks which credential group is active, whether that group exists in the credentials store, and whether the current project root is in the group's authorised roots list. Run it whenever a project fails to authenticate or after moving a project to a new machine or workspace. # yera doctor Print credential health for the current project. ``` yera doctor ``` --- Source: https://yera-labs.io/docs/yera/reference/cli/get/ # Yera Get The `get` command reads and prints resolved configuration values, stored objects, and credential data. It covers the full breadth of Yera's config surface — settings, hubs, providers, profiles, models, and credentials — and always prints the fully resolved value rather than the raw file contents. Use `get` to verify what Yera will actually see at runtime, or to script config inspection in CI. # yera get Get config entries and Yera object data. # yera get setting Print the resolved value of a single setting. ``` yera get setting SETTING_NAME ``` ## Arguments SETTING_NAME type: str (required) Settings field name: one of `enable_telemetry`, `log_level`, `max_retries`, `timeout_seconds`. The printed value is fully resolved (`pyproject.toml` → `yera.toml` → model defaults). # yera get settings Print all resolved top-level settings. ``` yera get settings ``` # yera get providers Print all configured providers as JSON. ``` yera get providers ``` # yera get provider Print one provider's config including all connections as JSON. ``` yera get provider PROVIDER_TYPE ``` ## Arguments PROVIDER_TYPE type: Literal (required) choices: anthropic, openai, mistral, aws, azure, ollama, llama_cpp Provider type to inspect. # yera get profile Print the currently active Yera profile as JSON. ``` yera get profile ``` # yera get profiles Print all configured Yera profiles as JSON. ``` yera get profiles ``` # yera get model Print all entries for a model id visible under the active Yera profile as JSON. Since the same model id can exist under multiple connections, all matching entries visible in the active profile are printed. ``` yera get model MODEL_ID ``` ## Arguments MODEL_ID type: str (required) Yera model id, e.g. aws.meta.llama3. # yera get models Print all models visible under the active Yera profile as JSON. ``` yera get models [MODEL_TYPE] ``` ## Arguments MODEL_TYPE type: Literal = None choices: llm, embedding, tts, stt, reranker Filter by model type. --- Source: https://yera-labs.io/docs/yera/reference/cli/guide/ # yera guide Run the Yera guide app. ``` yera guide [--no-browser] ``` ## Options --no-browser type: bool = False Run interactively in the terminal instead of the browser. --- Source: https://yera-labs.io/docs/yera/reference/cli/hello/ # yera hello Run the Yera Hello app. ``` yera hello [--no-browser] ``` ## Options --no-browser type: bool = False Run interactively in the terminal instead of the browser. --- Source: https://yera-labs.io/docs/yera/reference/cli/profile/ # Yera Profile The `profile` command manages the fields of a Yera profile — the named configuration bundle that ties together a set of provider connections and default models. Use `profile set` subcommands to assign which connection each provider should use and which model should serve as the default for each modality. All setters target the active profile by default and accept a `--profile` flag to target a named one instead. # yera profile Operate on fields within a Yera profile. # yera profile set Set a field on a Yera profile. # yera profile set anthropic Set the active anthropic connection on a Yera profile. ``` yera profile set anthropic CONNECTION_NAME [--profile STR] ``` ## Arguments CONNECTION_NAME type: str (required) Name of an existing anthropic connection. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set openai Set the active openai connection on a Yera profile. ``` yera profile set openai CONNECTION_NAME [--profile STR] ``` ## Arguments CONNECTION_NAME type: str (required) Name of an existing openai connection. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set mistral Set the active mistral connection on a Yera profile. ``` yera profile set mistral CONNECTION_NAME [--profile STR] ``` ## Arguments CONNECTION_NAME type: str (required) Name of an existing mistral connection. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set aws Set the active aws connection on a Yera profile. ``` yera profile set aws CONNECTION_NAME [--profile STR] ``` ## Arguments CONNECTION_NAME type: str (required) Name of an existing aws connection. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set azure Set the active azure connection on a Yera profile. ``` yera profile set azure CONNECTION_NAME [--profile STR] ``` ## Arguments CONNECTION_NAME type: str (required) Name of an existing azure connection. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set ollama Set the active ollama connection on a Yera profile. ``` yera profile set ollama CONNECTION_NAME [--profile STR] ``` ## Arguments CONNECTION_NAME type: str (required) Name of an existing ollama connection. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set llama-cpp Set the active llama-cpp connection on a Yera profile. ``` yera profile set llama-cpp CONNECTION_NAME [--profile STR] ``` ## Arguments CONNECTION_NAME type: str (required) Name of an existing llama_cpp connection. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set llm Set the default LLM model on a Yera profile. ``` yera profile set llm MODEL_ID [--profile STR] ``` ## Arguments MODEL_ID type: str (required) Yera model id to set as default LLM. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set embedding Set the default embedding model on a Yera profile. ``` yera profile set embedding MODEL_ID [--profile STR] ``` ## Arguments MODEL_ID type: str (required) Yera model id to set as default embedding. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set tts Set the default TTS model on a Yera profile. ``` yera profile set tts MODEL_ID [--profile STR] ``` ## Arguments MODEL_ID type: str (required) Yera model id to set as default TTS. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set stt Set the default STT model on a Yera profile. ``` yera profile set stt MODEL_ID [--profile STR] ``` ## Arguments MODEL_ID type: str (required) Yera model id to set as default STT. ## Options --profile type: str = None Profile to update. Defaults to the active profile. # yera profile set reranker Set the default reranker model on a Yera profile. ``` yera profile set reranker MODEL_ID [--profile STR] ``` ## Arguments MODEL_ID type: str (required) Yera model id to set as default reranker. ## Options --profile type: str = None Profile to update. Defaults to the active profile. --- Source: https://yera-labs.io/docs/yera/reference/cli/run/ # Yera Run The `run` command loads a single agent from a Python file, starts the Yera dev server, and opens the UI directly on that agent's chat page. It is the single-file counterpart to `dev`, which discovers all agents under a directory. Use `run` when you want to target one specific agent file without scanning a whole project tree. # yera run Run Yera apps from a Python file or directory and bring up the browser UI. ``` yera run [LOCATION] [--port INT] [--host STR] [--browser] ``` ## Arguments LOCATION type: str = None Path to a .py file or directory containing them. ## Options --port type: int = 8991 Bind port. --host type: str = '127.0.0.1' Bind address (not a URL). --browser type: bool = True aliases: --no-browser negative: --no-browser Whether to open a browser window or run headless. --- Source: https://yera-labs.io/docs/yera/reference/cli/set/ # Yera Set The `set` command writes individual configuration values to `yera.toml` or `pyproject.toml`. Use it for non-interactive config changes: setting a named hub as the default, pointing a project at a credential group, activating a profile, or writing a settings field. Most subcommands accept a `--project` flag to write the value into the project-local `pyproject.toml` rather than the shared `yera.toml`. # yera set Set config entries and Yera object data. # yera set setting Write a setting value to yera.toml or pyproject.toml. ``` yera set setting SETTING_NAME VALUE [--project] ``` ## Arguments SETTING_NAME type: str (required) Settings field name: one of `enable_telemetry`, `log_level`, `max_retries`, `timeout_seconds`. VALUE type: str (required) Literal value to store (e.g. a number, `true`/`false`, or text). For `log_level`, use a standard logging level name such as `DEBUG` or `INFO`. ## Options --project type: bool = False If true, write under `pyproject.toml` `[tool.yera]`; otherwise write under `yera.toml` `[settings]`. # yera set profile Set the active Yera profile. ``` yera set profile PROFILE_NAME [--project] ``` ## Arguments PROFILE_NAME type: str (required) Yera profile name to set as active. ## Options --project type: bool = False If true, write the project-level profile override in `pyproject.toml` `[tool.yera.profiles]`; otherwise write `[profiles] default` in `yera.toml`. --- Source: https://yera-labs.io/docs/yera/reference/cli/setup/ # Yera Setup The `setup` command provides interactive wizards for first-time and ongoing configuration of Yera. The default `yera setup` runs a guided flow that detects available provider credentials, configures provider connections, discovers models, and creates a named profile. Subcommands cover individual concerns: `setup hub` registers a hub connection, `setup cred-group` walks through credential group creation and project authorisation, and `setup provider` / `setup models` let you add or refresh a single provider without re-running the full wizard. # yera setup Run setup for Yera. ``` yera setup [--no-browser] ``` ## Options --no-browser type: bool = False Run setup interactively in the terminal instead of the browser. # yera setup provider Interactive setup for a Yera provider connection. # yera setup provider anthropic Set up anthropic provider connection. ``` yera setup provider anthropic [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this anthropic connection. # yera setup provider ollama Set up ollama provider connection. ``` yera setup provider ollama [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this ollama connection. # yera setup provider openai Set up openai provider connection. ``` yera setup provider openai [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this openai connection. # yera setup provider mistral Set up mistral provider connection. ``` yera setup provider mistral [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this mistral connection. # yera setup provider aws Set up aws provider connection. ``` yera setup provider aws [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this aws connection. # yera setup provider azure Set up azure provider connection. ``` yera setup provider azure [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this azure connection. # yera setup provider llama-cpp Set up llama_cpp provider connection. ``` yera setup provider llama-cpp [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this llama_cpp connection. # yera setup provider openrouter Set up openrouter provider connection. ``` yera setup provider openrouter [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this openrouter connection. # yera setup provider gemini Set up gemini provider connection. ``` yera setup provider gemini [CONNECTION_NAME] ``` ## Arguments CONNECTION_NAME type: str = 'default' Name for this gemini connection. # yera setup cred-group Configure a protected credential group for the current project. ``` yera setup cred-group ``` # yera setup models Discover and write available models for provider connections. # yera setup models aws Discover and write models for aws connections. ``` yera setup models aws [--connection STR] ``` ## Options --connection type: str = None Specific aws connection to discover models for. Omit for all connections. # yera setup models anthropic Discover and write models for anthropic connections. ``` yera setup models anthropic [--connection STR] ``` ## Options --connection type: str = None Specific anthropic connection to discover models for. Omit for all connections. # yera setup models azure Discover and write models for azure connections. ``` yera setup models azure [--connection STR] ``` ## Options --connection type: str = None Specific azure connection to discover models for. Omit for all connections. # yera setup models llama-cpp Discover and write models for llama_cpp connections. ``` yera setup models llama-cpp [--connection STR] ``` ## Options --connection type: str = None Specific llama_cpp connection to discover models for. Omit for all connections. # yera setup models openai Discover and write models for openai connections. ``` yera setup models openai [--connection STR] ``` ## Options --connection type: str = None Specific openai connection to discover models for. Omit for all connections. # yera setup models mistral Discover and write models for mistral connections. ``` yera setup models mistral [--connection STR] ``` ## Options --connection type: str = None Specific mistral connection to discover models for. Omit for all connections. # yera setup models ollama Discover and write models for ollama connections. ``` yera setup models ollama [--connection STR] ``` ## Options --connection type: str = None Specific ollama connection to discover models for. Omit for all connections. # yera setup models openrouter Discover and write models for openrouter connections. ``` yera setup models openrouter [--connection STR] ``` ## Options --connection type: str = None Specific openrouter connection to discover models for. Omit for all connections. # yera setup models gemini Discover and write models for gemini connections. ``` yera setup models gemini [--connection STR] ``` ## Options --connection type: str = None Specific gemini connection to discover models for. Omit for all connections. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ # Yera Implementation Placeholder --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/ # yera.apps App decorator and runtime context. Exposes `app`, the decorator that turns a Python function into a Yera app, and `get_app_context`, which returns the currently executing app's runtime context. The latter is mostly for framework code; user code rarely needs it. ## Submodules builtin context dataclasses decorator discovery exceptions registry --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/builtin/ # yera.apps.builtin Provide Yera's built-in applications. ## Submodules guide hello registry --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/builtin/guide/ # yera.apps.builtin.guide Provide Yera's built-in guide application. ## Submodules app prompt --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/builtin/guide/app/ # yera.apps.builtin.guide.app Define Yera's built-in introductory guide application. ## Symbols def guide — An interactive assistant for learning about Yera and building Yera applications. # guide ``` guide() → None ``` An interactive assistant for learning about Yera and building Yera applications. The guide uses the active profile's default language model and maintains conversational context across questions. It provides practical assistance with Yera's public primitives, application composition, and execution. ## Submodules yr --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/builtin/guide/prompt/ # yera.apps.builtin.guide.prompt Define the system prompt for Yera's built-in guide. --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/builtin/hello/ # yera.apps.builtin.hello Tests for Yera's built-in Hello application. ## Submodules app --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/builtin/hello/app/ # yera.apps.builtin.hello.app Yera's built-in Hello app that wraps the Setup and Guide apps. ## Symbols def hello — Run Yera's Hello app. # hello ``` hello() → None ``` Run Yera's Hello app. The app runs interactive setup and, when setup produces a usable default language model, offers to open the Yera Guide. ## Submodules yr --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/builtin/registry/ # yera.apps.builtin.registry Declare Yera's built-in applications and their visibility. ## Symbols class BuiltinAppDefinition — Describe a built-in application. def merge_with_visible_builtins — Combine project apps with visible built-ins. def visible_builtin_apps — Return built-in apps intended for the Apps screen. # BuiltinAppDefinition Describe a built-in application. ## Parameters app type: AppFunctionWrapper Wrapped Yera application exposed by the definition. visible_in_apps type: bool = True Whether the app appears in the Apps screen. # merge_with_visible_builtins ``` merge_with_visible_builtins( project_apps: dict[str, AppFunctionWrapper], ) → dict[str, AppFunctionWrapper] ``` Combine project apps with visible built-ins. ## Parameters project_apps type: dict[str, AppFunctionWrapper] Applications discovered from a user project. ## Returns type: dict[str, AppFunctionWrapper] Visible built-ins followed by the supplied project apps. ## Raises ValueError If a project app uses the reserved `builtin/` namespace. # visible_builtin_apps ``` visible_builtin_apps() → dict[str, AppFunctionWrapper] ``` Return built-in apps intended for the Apps screen. ## Returns type: dict[str, AppFunctionWrapper] A new mapping containing each visible built-in app. --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/context/ # yera.apps.context Per-invocation app context, accessible via a `ContextVar`. The `@app` decorator pushes an `AppContext` onto a stack on entry and pops it on exit; user code reads the current context via `get_app_context`. ## Symbols class AppContext — Per-invocation runtime context for an executing app. def get_app_context — Return the currently executing app's runtime context. def no_active_app_context — Return ``True`` if no app context is currently active. # AppContext Per-invocation runtime context for an executing app. Pushed onto a `ContextVar` stack on entry and popped on exit. Tracks the app's metadata, an instance counter, and its position in the app stack (top-level vs. nested). Managed by the `@app` decorator; not constructed by user code. ## Attributes metadata `AppMetadata` describing the app this context belongs to. instance_number Counter for this app's invocations within a single run. ## Methods __enter__ — Push this context onto the stack and return it. __exit__ — Pop this context off the stack. top_level — Return whether this context is the outermost app on the stack. # AppContext.__enter__ ``` __enter__() ``` Push this context onto the stack and return it. # AppContext.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) ``` Pop this context off the stack. # AppContext.top_level ``` top_level() → bool ``` Return whether this context is the outermost app on the stack. ## Raises RuntimeError If called before the context has been entered. # get_app_context ``` get_app_context() → AppContext ``` Return the currently executing app's runtime context. For framework code that needs to inspect the running app (e.g. its metadata or position in the app stack). User code in an app's body rarely needs this. ## Returns type: AppContext The active `AppContext`. ## Raises RuntimeError If called outside an active app invocation. # no_active_app_context ``` no_active_app_context() → bool ``` Return `True` if no app context is currently active. --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/dataclasses/ # yera.apps.dataclasses Dataclasses describing app signatures, metadata, and invocations. ## Symbols class AppInput — One parameter of an app's signature, captured as plain data. class AppInstance — A specific invocation of an app. class AppMetadata — Static description of an app, captured at decoration time. # AppInput One parameter of an app's signature, captured as plain data. Built from an `inspect.Parameter` when the `@app` decorator runs, then frozen into `AppMetadata.params` so the runtime, registry, and tooling can inspect the app's inputs without re-reading the function object. ## Attributes name type: str Parameter name. type type: str String rendering of the parameter's type annotation. kind type: str String rendering of the parameter kind (positional, keyword-only, etc.). has_default type: bool Whether the parameter has a default value. default_value type: Any The default value, or `None` if `has_default` is `False`. ## Methods from_parameter — Build an ``AppInput`` from an ``inspect.Parameter``. # AppInput.from_parameter ``` from_parameter( p: Parameter, ) → AppInput ``` Build an `AppInput` from an `inspect.Parameter`. # AppInstance A specific invocation of an app. An app can be called multiple times within a single run (e.g. a nested app called in a loop); each call gets a unique `instance_id` so events can be attributed to the right invocation. ## Attributes app_id type: str The app's identifier (module-qualified name). instance_id type: int Counter distinguishing this invocation from other calls to the same app in the same run. # AppMetadata Static description of an app, captured at decoration time. Built once by the `@app` decorator and registered with the app registry under `identifier`. Used by the runtime, the console renderer, and any downstream tooling that needs to introspect apps without holding the function object. ## Attributes name type: str Display name (defaults to the function's `__name__`). module type: str Fully-qualified module the app was defined in. identifier type: str `.` — the unique key the registry looks the app up by. params type: list[AppInput] The app's parameter list as `AppInput` entries. return_type type: str String rendering of the declared return type. docs type: str | None The wrapped function's docstring, if any. description type: str | None Optional human-readable description passed to the decorator. ## Methods make_instance — Create an [`AppInstance`][yera.apps.dataclasses.AppInstance] for the ``ix``-th invocation of this app. pretty_print — Render the app's metadata as a human-readable multi-line string. # AppMetadata.make_instance ``` make_instance( ix: int, ) → AppInstance ``` Create an `AppInstance` for the `ix`-th invocation of this app. # AppMetadata.pretty_print ``` pretty_print() → str ``` Render the app's metadata as a human-readable multi-line string. --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/decorator/ # yera.apps.decorator App function wrapping and the `@app` decorator. Provides `AppFunctionWrapper`, which adapts a plain Python function into a Yera app — validating its signature against the supported type system, registering it with the app registry, and driving the execution lifecycle (event stream, model contexts, system prompt, argument coercion, return-type checking, exit-event handling). The `app` decorator is the normal entry point; wrappers are not to be constructed directly. ## Symbols def app — Decorator that turns a Python function into a Yera app. class AppFunctionWrapper — Wraps a Python function as a Yera app. # app ``` app( fn: Callable | None = None, name: str | None = None, description: str | None = None, llm: LLMContext | None = None, sys_prompt: str | None = None, ) → AppFunctionWrapper | Callable[[Callable], AppFunctionWrapper] ``` Decorator that turns a Python function into a Yera app. Usable bare (`@app`) or with keyword arguments (`@app(name=..., llm=..., sys_prompt=...)`). The wrapped function's signature is validated against Yera's supported type system at decoration time; arguments and return values are coerced at call time. ## Parameters fn type: Callable | None = None The function being decorated when used bare. Left as `None` when the decorator is invoked with arguments. name type: str | None = None Display name for the app. Defaults to the function's `__name__`. description type: str | None = None Optional human-readable description recorded in the app metadata. llm type: LLMContext | None = None Optional `LLMContext` entered for the duration of each run. Falls back to the active profile's default llm if omitted. sys_prompt type: str | None = None Optional system prompt emitted once the llm context is entered. ## Returns type: AppFunctionWrapper | Callable[[Callable], AppFunctionWrapper] An `AppFunctionWrapper` callable that runs the function under the Yera event-stream runtime when invoked. When called with arguments (`fn is None`), returns a decorator that produces the wrapper. # AppFunctionWrapper Wraps a Python function as a Yera app. Validates the wrapped function's signature against Yera's supported type system, registers it in the app registry under its module-qualified identifier, and drives the execution lifecycle: event-stream setup, model-context entry, system-prompt emission, argument coercion, return-type checking, and exit-event handling. At the top of the call stack, execution runs in a subprocess with console output streamed via the rich renderer. When called from within an existing app context (nested), execution runs directly in the current process. Instances are normally produced by the `app` decorator rather than constructed directly. ## Parameters app_function type: Callable The Python function to wrap. name type: str | None Optional display name. Defaults to the function's **name**. description type: str | None Optional human-readable description. llm type: LLMContext | None Optional LLMContext entered for the duration of each run. sys_prompt_str type: str | None Optional system prompt emitted at run start. ## Attributes metadata `AppMetadata` describing this app. ## Methods invoke — Execute the wrapped function with the full app lifecycle. __call__ — Invoke the app. __reduce__ — Support pickling via ``cloudpickle``. # AppFunctionWrapper.invoke ``` invoke( *args, **kwargs, ) → object ``` Execute the wrapped function with the full app lifecycle. Coerces arguments to their declared types, enters the resolved model context (the supplied `llm` or the ambient default), emits the configured system prompt, calls the underlying function, validates the return value against the declared return type, and routes both the success and failure paths through `_handle_app_exit`. This is the core execution method. `__call__` dispatches to it either via a subprocess (top-level runs) or directly (nested runs); callers should use `__call__` rather than `invoke` directly. ## Parameters *args type: object = () Positional arguments forwarded to the wrapped function after coercion to their declared types. **kwargs type: object Keyword arguments forwarded to the wrapped function after coercion to their declared types. ## Returns type: object The wrapped function's return value on success. ## Raises TypeError If arguments cannot be bound to the signature or coerced to their declared types. Exception Re-raises an exception raised while executing the app, after recording its failure exit event. # AppFunctionWrapper.__call__ ``` __call__( *args, **kwargs, ) → object ``` Invoke the app. At the top of the app stack, runs the app under the console renderer so that events are pretty-printed as they stream, and returns the coerced return value once the run finishes. When nested inside an already-active app context, delegates to `invoke`. ## Parameters *args type: object = () Positional arguments for the wrapped function. **kwargs type: object Not supported, yet. Variadic keyword splats (`**kwargs`) in app definitions cannot be statically analysed by the (upcoming) SIGL compiler and are rejected at decoration time. Non-splat ones will be fine. ## Returns type: object The wrapped function's return value, coerced to the declared return type. ## Raises NotImplementedError If any keyword arguments are supplied. AppRuntimeError If the run does not terminate with an exit block, or exits with a non-zero exit code. See `AppRuntimeError`. # AppFunctionWrapper.__reduce__ ``` __reduce__() → tuple[Callable, tuple] ``` Support pickling via `cloudpickle`. The wrapped function is serialised with `cloudpickle` (rather than the standard `pickle`) so that closures, lambdas, and locally defined functions survive the round trip. On unpickling, `_unpickle_app_wrapper` reconstructs the `AppFunctionWrapper` by re-running the decorator over the restored function. --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/discovery/ # yera.apps.discovery Utilities for loading apps from files. ## Symbols def discover_apps — Discover all apps in a directory. def load_app — Load a Python file and extract the AppFunctionWrapper instance with the given identifier. def load_apps — Load a Python file and extract all AppFunctionWrapper instances. def path_to_module_name — Convert a Python file path to a dotted module name for tools and apps. # discover_apps ``` discover_apps( directory: Path | str, id_anchor: Path | None = None, ) → list[AppFunctionWrapper] ``` Discover all apps in a directory. Scans the directory tree for `.py` files and loads all apps from each file. Hidden directories (names starting with `.`) are not entered, so typical trees like `.venv` or `.git` are skipped. This function underpins the `/api/apps` endpoint exposed by the dev server: the React UI queries `/api/apps` to build the home page and to resolve `app_id` strings used in `/apps/{id}` routes. Running `yera dev` in different directories will therefore expose different sets of apps to the *same* static UI bundle. ## Parameters directory type: Path | str Directory to scan for app files. id_anchor type: Path | None = None Root directory used to compute dotted module names for app identifiers. Defaults to the project root (directory of the nearest pyproject.toml walking up from cwd), falling back to `directory` itself when no pyproject.toml is found. ## Returns type: list[AppFunctionWrapper] List of appFunctionWrapper instances. ## Raises FileNotFoundError If the directory does not exist. # load_app ``` load_app( file_path: Path | str, app_identifier: str | None = None, ) → AppFunctionWrapper ``` Load a Python file and extract the AppFunctionWrapper instance with the given identifier. ## Parameters file_path type: Path | str Path to the Python file containing one or more apps. Can be a Path object or string. app_identifier type: str | None = None Identifier of the app to load. If None, the first app is loaded. ## Returns type: AppFunctionWrapper AppFunctionWrapper instance. ## Raises ValueError If no apps are found in the file. ValueError If multiple apps are found in the file and no identifier is provided. ValueError If the specified app identifier is not found in the file. ValueError If the specified app identifier does not match the identifier of the loaded app. # load_apps ``` load_apps( file_path: Path | str, base_dir: Path | None = None, ) → list[AppFunctionWrapper] ``` Load a Python file and extract all AppFunctionWrapper instances. This helper looks for objects in the module that are instances of AppFunctionWrapper (created by the @yr.app decorator). ## Parameters file_path type: Path | str Path to the Python file containing one or more apps. Can be a Path object or string. base_dir type: Path | None = None Root directory used to compute the module name for app identifiers. Defaults to the current working directory. ## Returns type: list[AppFunctionWrapper] Dictionary mapping app identifiers to AppFunctionWrapper instances. ## Raises FileNotFoundError If the file does not exist. # path_to_module_name ``` path_to_module_name( path: Path, base_dir: Path | None = None, ) → str ``` Convert a Python file path to a dotted module name for tools and apps. This helper is used anywhere we need a stable module identifier for dynamically loaded code (e.g. CLI-loaded apps, tools discovered from the filesystem). Behaviour: - Strips the `.py` suffix from the path. - If the file is under the given `base_dir` (or current working directory when `base_dir` is None), it converts the relative path into a dotted module name, using each directory component as a segment. - If the file is not under `base_dir`, it falls back to the filename stem. ## Examples - path: /repo/demos/apps/basic_chatbot.py, base_dir=/repo -> "demos.apps.basic_chatbot" - path: /tmp/basic_chatbot.py, base_dir=/repo -> "basic_chatbot" --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/exceptions/ # yera.apps.exceptions App-specific exceptions. ## Symbols class AppRuntimeError — Raised when an app exits with a non-zero exit code. class ErrorCause — Structured metadata about the cause of an app exit error. class StreamEndedError — Raised when an event iterator ends without a terminating event. # AppRuntimeError Inherits: `RuntimeError` Raised when an app exits with a non-zero exit code. Raised by the app decorator instead of calling sys.exit, so callers can catch a normal exception and e.g. call sys.exit(exit_code) in a runner. # ErrorCause Inherits: `BaseModel` Structured metadata about the cause of an app exit error. Always includes error_type. May include additional fields like block_type for specific error types (e.g., UnsupportedAwaitUserBlockError). # StreamEndedError Inherits: `RuntimeError` Raised when an event iterator ends without a terminating event. Signals that the producer stopped — process died, stream closed — before emitting a lifecycle or prompt event. Subclasses `RuntimeError` so existing broad handlers keep working during the transition. --- Source: https://yera-labs.io/docs/yera/reference/implementation/apps/registry/ # yera.apps.registry Process-local registry mapping app IDs to their metadata. Used by the decorator to resolve the *actual* app name (including nested apps) when constructing AppRuntimeError on the consumer side. ## Symbols def get_app_metadata — Look up metadata for the given app_id. def get_app_name — Return the display name for the given app_id, or None if unknown. def register_app — Register metadata for a given app_id in the current process. # get_app_metadata ``` get_app_metadata( app_id: str, ) → AppMetadata | None ``` Look up metadata for the given app_id. # get_app_name ``` get_app_name( app_id: str, ) → str | None ``` Return the display name for the given app_id, or None if unknown. # register_app ``` register_app( app_id: str, metadata: AppMetadata, ) → None ``` Register metadata for a given app_id in the current process. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/ # yera.cli Yera CLI — Cyclopts CLI. ## Symbols def main — Entry point for the Yera CLI. # main ``` main() → None ``` Entry point for the Yera CLI. ## Submodules app commands context decorators resources setup_handlers --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/__main__/ # yera.cli.__main__ Allow running the CLI via python -m yera.cli. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/app/ # yera.cli.app Cyclopts root app, sub-app registration, and meta launcher. ## Symbols def create_app — Build and return the root Cyclopts app with the meta launcher. # create_app ``` create_app() → App ``` Build and return the root Cyclopts app with the meta launcher. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/ # yera.cli.commands CLI2 command modules. ## Submodules allow cred delete doctor export get guide hello patch profile put rename run set setup --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/allow/ # yera.cli.commands.allow Credential-group project authorization operations. ## Symbols def cred_group — Add the current project root to a credential group's authorised roots. # cred_group ``` cred_group( name: str, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Add the current project root to a credential group's authorised roots. ## Parameters name type: str Credential group name to authorise for this project root. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/cred/ # yera.cli.commands.cred Credential management commands. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/delete/ # yera.cli.commands.delete Delete commands — remove config entries and files. ## Symbols def config — Delete yera.toml. def cred — Delete one credential leaf. def cred_group — Delete a credential group and all its credentials from credentials.json. def creds — Delete credential leaves beneath an optional namespace. def mcp — Remove an MCP server, its imported tools, and its stored secrets. def model — Remove one model entry from the universe. def models — Remove all models from the universe, optionally filtered by type. def profile — Remove a named Yera profile from yera.toml. def profiles — Remove all Yera profiles and the active default from yera.toml. def provider — Remove a provider or one of its connections from yera.toml. def providers — Remove all providers from yera.toml. # config ``` config( force: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Delete yera.toml. ## Parameters force type: Annotated[bool, Parameter(negative='')] = False Must be true; the command refuses to delete without `--force`. # cred ``` cred( key: str, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Delete one credential leaf. ## Parameters key type: str Exact dotted credential name. ## Raises CredentialKeyError If the name is absent or identifies a namespace. # cred_group ``` cred_group( name: str, force: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Delete a credential group and all its credentials from credentials.json. ## Parameters name type: str Credential group name to delete. force type: Annotated[bool, Parameter(negative='')] = False Must be true; the command refuses to delete without `--force`. # creds ``` creds( path: str | None = None, force: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Delete credential leaves beneath an optional namespace. ## Parameters path type: str | None = None Optional dotted namespace to clear. force type: Annotated[bool, Parameter(negative='')] = False Whether destructive bulk deletion is permitted. ## Raises YeraError If force is not enabled. CredentialKeyError If the path identifies only one credential leaf. # mcp ``` mcp( server_name: Annotated[str, Parameter(help='MCP server connection to remove.')], ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Remove an MCP server, its imported tools, and its stored secrets. The server is also removed from every profile that enables it. Credential-group values referenced by static headers are kept. ## Parameters server_name type: Annotated[str, Parameter(help='MCP server connection to remove.')] Configured MCP server connection to remove. # model ``` model( model_id: Annotated[str, Parameter(help='Yera model id to remove.')], connection: Annotated[str, Parameter(help='Connection name the model was discovered under. Required since the same model id can exist under multiple connections.')], model_type: Annotated[Literal['llm', 'embedding', 'tts', 'stt', 'reranker'], Parameter(help='Model type of the entry to remove.')], ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Remove one model entry from the universe. ## Parameters model_id type: Annotated[str, Parameter(help='Yera model id to remove.')] Yera-internal dot-delimited model id to remove. connection type: Annotated[str, Parameter(help='Connection name the model was discovered under. Required since the same model id can exist under multiple connections.')] Connection name the model was discovered under. Required because the same model id can exist under multiple connections. model_type type: Annotated[Literal['llm', 'embedding', 'tts', 'stt', 'reranker'], Parameter(help='Model type of the entry to remove.')] Model type of the entry to remove. # models ``` models( model_type: Annotated[Literal['llm', 'embedding', 'tts', 'stt', 'reranker'] | None, Parameter(help='If set, remove only models of this type.')] = None, force: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Remove all models from the universe, optionally filtered by type. ## Parameters model_type type: Annotated[Literal['llm', 'embedding', 'tts', 'stt', 'reranker'] | None, Parameter(help='If set, remove only models of this type.')] = None If set, only models of this type are removed. If omitted, all models across all types are removed. force type: Annotated[bool, Parameter(negative='')] = False Must be true; the command refuses to delete without `--force`. # profile ``` profile( profile_name: Annotated[str, Parameter(help='Yera profile name to remove.')], ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Remove a named Yera profile from yera.toml. ## Parameters profile_name type: Annotated[str, Parameter(help='Yera profile name to remove.')] Profile to remove. If it was the active default profile, the default is cleared. # profiles ``` profiles( force: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Remove all Yera profiles and the active default from yera.toml. ## Parameters force type: Annotated[bool, Parameter(negative='')] = False Must be true; the command refuses to delete without `--force`. # provider ``` provider( provider_type: Annotated[Literal['anthropic', 'openai', 'mistral', 'aws', 'azure', 'ollama', 'llama_cpp'], Parameter(help='Provider type to remove.')], connection: Annotated[str | None, Parameter(help='If set, remove only this connection rather than the entire provider. Raises an error if any Yera profile references this connection.')] = None, force: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Remove a provider or one of its connections from yera.toml. ## Parameters provider_type type: Annotated[Literal['anthropic', 'openai', 'mistral', 'aws', 'azure', 'ollama', 'llama_cpp'], Parameter(help='Provider type to remove.')] Provider type to remove. Must be a configured provider. connection type: Annotated[str | None, Parameter(help='If set, remove only this connection rather than the entire provider. Raises an error if any Yera profile references this connection.')] = None If set, remove only this connection. Raises an error if any Yera profile references it — update or remove those profiles first. force type: Annotated[bool, Parameter(negative='')] = False Required when removing an entire provider. The command refuses to delete without `--force`. # providers ``` providers( force: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Remove all providers from yera.toml. ## Parameters force type: Annotated[bool, Parameter(negative='')] = False Must be true; the command refuses to delete without `--force`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/doctor/ # yera.cli.commands.doctor Doctor command — credential health diagnostic. ## Symbols def doctor — Print credential health for the current project. # doctor ``` doctor( ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print credential health for the current project. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/export/ # yera.cli.commands.export Credential-group export operations. ## Symbols def cred_group — Export a credential group as a portable protected-store document. # cred_group ``` cred_group( name: str, output_file: Annotated[Path | None, Parameter(name=['--output-file'])] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Export a credential group as a portable protected-store document. ## Parameters name type: str Credential group name to export. output_file type: Annotated[Path | None, Parameter(name=['--output-file'])] = None Path to write the exported JSON. Uses atomic writing with restricted permissions on POSIX. Omit to write to standard output. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/get/ # yera.cli.commands.get Get commands — inspect resolved config values. ## Symbols def cred — Print the plain value of a single credential leaf. def cred_group — Show active credential group or inspect a named group's metadata. def cred_groups — List all credential groups with credential counts and authorised roots. def creds — Inspect credentials for the active credential group. def model — Print all entries for a model id visible under the active Yera profile as JSON. def models — Print all models visible under the active Yera profile as JSON. def profile — Print the currently active Yera profile as JSON. def profiles — Print all configured Yera profiles as JSON. def provider — Print one provider's config including all connections as JSON. def providers — Print all configured providers as JSON. def setting — Print the resolved value of a single setting. def settings — Print all resolved top-level settings. # cred ``` cred( key: str, allow_missing: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print the plain value of a single credential leaf. ## Parameters key type: str Exact dotted leaf key. allow_missing type: Annotated[bool, Parameter(negative='')] = False Exit successfully without output if the key is absent. ## Raises CredentialKeyError If the key identifies a namespace or is absent. # cred_group ``` cred_group( name: str | None = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Show active credential group or inspect a named group's metadata. ## Parameters name type: str | None = None Credential group name to inspect. If omitted, prints the active group name. If provided, prints the named group's metadata as JSON. # cred_groups ``` cred_groups( ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` List all credential groups with credential counts and authorised roots. # creds ``` creds( path: str | None = None, keys_only: Annotated[bool, Parameter(negative='')] = False, reveal: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Inspect credentials for the active credential group. ## Parameters path type: str | None = None Optional dotted namespace used to scope the output. keys_only type: Annotated[bool, Parameter(negative='')] = False Print credential names without values. reveal type: Annotated[bool, Parameter(negative='')] = False Print decoded values instead of redacted placeholders. ## Raises CredentialKeyError If incompatible output flags are combined or the path identifies only a single credential leaf. # model ``` model( model_id: Annotated[str, Parameter(help='Yera model id, e.g. aws.meta.llama3.')], ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print all entries for a model id visible under the active Yera profile as JSON. Since the same model id can exist under multiple connections, all matching entries visible in the active profile are printed. ## Parameters model_id type: Annotated[str, Parameter(help='Yera model id, e.g. aws.meta.llama3.')] Yera-internal dot-delimited model id, e.g. `aws.meta.llama3`. # models ``` models( model_type: Annotated[Literal['llm', 'tts', 'stt', 'embedding', 'reranker'] | None, Parameter(help='Filter by model type.')] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print all models visible under the active Yera profile as JSON. ## Parameters model_type type: Annotated[Literal['llm', 'tts', 'stt', 'embedding', 'reranker'] | None, Parameter(help='Filter by model type.')] = None If set, only models of this type are returned. # profile ``` profile( ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print the currently active Yera profile as JSON. # profiles ``` profiles( ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print all configured Yera profiles as JSON. # provider ``` provider( provider_type: Annotated[Literal['anthropic', 'openai', 'mistral', 'aws', 'azure', 'ollama', 'llama_cpp'], Parameter(help='Provider type to inspect.')], ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print one provider's config including all connections as JSON. ## Parameters provider_type type: Annotated[Literal['anthropic', 'openai', 'mistral', 'aws', 'azure', 'ollama', 'llama_cpp'], Parameter(help='Provider type to inspect.')] Provider type to inspect. Must be a configured provider. # providers ``` providers( ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print all configured providers as JSON. # setting ``` setting( setting_name: Annotated[str, Parameter(help=_SETTING_NAME_HELP)], ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print the resolved value of a single setting. # settings ``` settings( ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Print all resolved top-level settings. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/guide/ # yera.cli.commands.guide The `yera guide` CLI command that runs the Yera Guide. ## Symbols def guide — Run Yera's built-in Guide application. # guide ``` guide( no_browser: Annotated[bool, Parameter(name='--no-browser', help='Run interactively in the terminal instead of the browser.', negative='')] = False, ) → None ``` Run Yera's built-in Guide application. ## Parameters no_browser type: Annotated[bool, Parameter(name='--no-browser', help='Run interactively in the terminal instead of the browser.', negative='')] = False Run the Guide through ANSI terminal handlers instead of starting the browser UI. ## Submodules builtin_guide_app --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/hello/ # yera.cli.commands.hello The `yera hello` CLI command that runs the Hello bot. ## Symbols def hello — Run Yera's built-in Hello application. # hello ``` hello( no_browser: Annotated[bool, Parameter(name='--no-browser', help='Run interactively in the terminal instead of the browser.', negative='')] = False, ) → None ``` Run Yera's built-in Hello application. Hello runs interactive setup and then offers to open the Yera Guide. ## Parameters no_browser type: Annotated[bool, Parameter(name='--no-browser', help='Run interactively in the terminal instead of the browser.', negative='')] = False Run Hello through ANSI terminal handlers instead of starting the browser UI. ## Submodules builtin_hello_app --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/patch/ # yera.cli.commands.patch Credential subtree merge operations. ## Symbols def creds — Merge credential leaves into a namespace. # creds ``` creds( path: str, json_str: str | None = None, from_file: Annotated[str | None, Parameter(name='--from-file')] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Merge credential leaves into a namespace. ## Parameters path type: str Dotted namespace to merge into. json_str type: str | None = None Inline JSON object to merge. from_file type: Annotated[str | None, Parameter(name='--from-file')] = None JSON file path, or `-` for standard input. ## Raises CredentialKeyError If input is empty or conflicts with stored leaves. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/profile/ # yera.cli.commands.profile Profile field commands — operate on fields within a Yera profile. ## Symbols def embedding — Set the default embedding model on a Yera profile. def llm — Set the default LLM model on a Yera profile. def reranker — Set the default reranker model on a Yera profile. def stt — Set the default STT model on a Yera profile. def tts — Set the default TTS model on a Yera profile. # embedding ``` embedding( model_id: Annotated[str, Parameter(help='Yera model id to set as default embedding.')], profile: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Set the default embedding model on a Yera profile. ## Parameters model_id type: Annotated[str, Parameter(help='Yera model id to set as default embedding.')] Yera model id to set as the default embedding model. profile type: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None Profile to update. Defaults to the active profile when omitted. # llm ``` llm( model_id: Annotated[str, Parameter(help='Yera model id to set as default LLM.')], profile: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Set the default LLM model on a Yera profile. ## Parameters model_id type: Annotated[str, Parameter(help='Yera model id to set as default LLM.')] Yera model id to set as the default LLM. profile type: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None Profile to update. Defaults to the active profile when omitted. # reranker ``` reranker( model_id: Annotated[str, Parameter(help='Yera model id to set as default reranker.')], profile: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Set the default reranker model on a Yera profile. ## Parameters model_id type: Annotated[str, Parameter(help='Yera model id to set as default reranker.')] Yera model id to set as the default reranker model. profile type: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None Profile to update. Defaults to the active profile when omitted. # stt ``` stt( model_id: Annotated[str, Parameter(help='Yera model id to set as default STT.')], profile: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Set the default STT model on a Yera profile. ## Parameters model_id type: Annotated[str, Parameter(help='Yera model id to set as default STT.')] Yera model id to set as the default STT model. profile type: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None Profile to update. Defaults to the active profile when omitted. # tts ``` tts( model_id: Annotated[str, Parameter(help='Yera model id to set as default TTS.')], profile: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Set the default TTS model on a Yera profile. ## Parameters model_id type: Annotated[str, Parameter(help='Yera model id to set as default TTS.')] Yera model id to set as the default TTS model. profile type: Annotated[str | None, Parameter(help='Profile to update. Defaults to the active profile.')] = None Profile to update. Defaults to the active profile when omitted. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/put/ # yera.cli.commands.put Credential write and subtree replacement operations. ## Symbols def cred — Set a single credential leaf. def creds — Replace all credential leaves beneath a namespace. # cred ``` cred( key: str, value: str | None = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Set a single credential leaf. ## Parameters key type: str Exact dotted leaf key. value type: str | None = None Credential value. Omit for interactive prompt or stdin. ## Raises CredentialKeyError If the key conflicts with existing credentials or the supplied value is empty. # creds ``` creds( path: str, json_str: str | None = None, from_file: Annotated[str | None, Parameter(name='--from-file')] = None, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Replace all credential leaves beneath a namespace. ## Parameters path type: str Dotted namespace to replace. json_str type: str | None = None Inline JSON object to store. from_file type: Annotated[str | None, Parameter(name='--from-file')] = None JSON file path, or `-` for standard input. ## Raises CredentialKeyError If input is empty or conflicts with stored leaves. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/rename/ # yera.cli.commands.rename Credential-group rename operations. ## Symbols def cred_group — Atomically rename a credential group in credentials.json. # cred_group ``` cred_group( old_name: str, new_name: str, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Atomically rename a credential group in credentials.json. ## Parameters old_name type: str Existing credential group name. new_name type: str New credential group name. Must pass name validation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/run/ # yera.cli.commands.run Run commands: run Yera apps with the browser UI. ## Symbols def run — Run Yera apps from a file or directory. # run ``` run( location: Annotated[str | None, Parameter(help='Path to a .py file or directory containing them.')] = None, port: Annotated[int, Parameter(help='Bind port.')] = 8991, host: Annotated[str, Parameter(help='Bind address (not a URL).')] = '127.0.0.1', browser: Annotated[bool, Parameter(help='Whether to open a browser window or run headless.')] = True, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Run Yera apps from a file or directory. ## Parameters location type: Annotated[str | None, Parameter(help='Path to a .py file or directory containing them.')] = None Optional path to a .py file or directory containing apps. port type: Annotated[int, Parameter(help='Bind port.')] = 8991 Bind port. host type: Annotated[str, Parameter(help='Bind address (not a URL).')] = '127.0.0.1' Bind address (not a URL). browser type: Annotated[bool, Parameter(help='Whether to open a browser window or run headless.')] = True Open a browser upon starting. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/set/ # yera.cli.commands.set Set commands — write config values. ## Symbols def cred_group — Set ``[tool.yera.overrides] cred-group`` in ``pyproject.toml``. def profile — Set the active Yera profile. def setting — Write a setting value to yera.toml or pyproject.toml. # cred_group ``` cred_group( name: str, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Set `[tool.yera.overrides] cred-group` in `pyproject.toml`. Non-interactive: does not touch credentials.json or authorised_roots. ## Parameters name type: str Credential group name to write under `[tool.yera.overrides]`. # profile ``` profile( profile_name: Annotated[str, Parameter(help='Yera profile name to set as active.')], project: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Set the active Yera profile. ## Parameters profile_name type: Annotated[str, Parameter(help='Yera profile name to set as active.')] Name of a Yera profile that already exists in `yera.toml`. project type: Annotated[bool, Parameter(negative='')] = False If true, write the project-level profile override in `pyproject.toml` `[tool.yera.profiles]`; otherwise write `[profiles] default` in `yera.toml`. # setting ``` setting( setting_name: Annotated[str, Parameter(help=_SETTING_NAME_HELP)], value: str, project: Annotated[bool, Parameter(negative='')] = False, ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Write a setting value to yera.toml or pyproject.toml. ## Parameters setting_name type: Annotated[str, Parameter(help=_SETTING_NAME_HELP)] Settings field name to write. value type: str Literal value to store (e.g. a number, `true`/`false`, or text). For `log_level`, use a standard logging level name such as `DEBUG` or `INFO`. project type: Annotated[bool, Parameter(negative='')] = False If true, write under `pyproject.toml` `[tool.yera]`; otherwise write under `yera.toml` `[settings]`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/commands/setup/ # yera.cli.commands.setup Interactive setup commands. ## Symbols def cred_group — Configure a protected credential group for the current project. def setup — Run Yera's built-in interactive setup application. # cred_group ``` cred_group( ctx: Annotated[AppContext, Parameter(parse=False, show=False)], ) → None ``` Configure a protected credential group for the current project. # setup ``` setup( no_browser: Annotated[bool, Parameter(name='--no-browser', help='Run setup interactively in the terminal instead of the browser.', negative='')] = False, ) → None ``` Run Yera's built-in interactive setup application. By default, setup starts Yera's local UI server and opens the setup application in a browser. Terminal-only environments can run the same application through Yera's ANSI handlers with `--no-browser`. ## Parameters no_browser type: Annotated[bool, Parameter(name='--no-browser', help='Run setup interactively in the terminal instead of the browser.', negative='')] = False Run setup through ANSI terminal handlers instead of starting the browser UI. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/context/ # yera.cli.context CLI application context passed to every command. ## Symbols class AppContext — Container passed to every CLI command as ``ctx``. # AppContext Container passed to every CLI command as `ctx`. `settings` is always populated (may be `None` when validation failed and the command tolerates it). `credential_store` and `active_credential_group` are only populated when the command declares `@requires(AppResource.SECRET_STORE)`; accessing them without that declaration raises :class:`RuntimeError`. ## Methods require_active_credential_group — Return the resolved active credential group or raise ``CredentialGroupNotSpecifiedError``. set_secret_store — Populate the protected secret-store boundary. set_provider_data — Populate provider config. set_profile_data — Set the profile data in context. set_models_universe — Set the model data in context. set_secret_store_data — Populate the protected store and active credential group atomically. # AppContext.require_active_credential_group ``` require_active_credential_group() → ResolvedCredentialGroup ``` Return the resolved active credential group or raise `CredentialGroupNotSpecifiedError`. # AppContext.set_secret_store ``` set_secret_store( secret_store: CredentialStoreBackend, ) → None ``` Populate the protected secret-store boundary. ## Parameters secret_store type: CredentialStoreBackend Backend used for opaque credential values. # AppContext.set_provider_data ``` set_provider_data( providers: Providers, ) → None ``` Populate provider config. # AppContext.set_profile_data ``` set_profile_data( profiles: Profiles | None, ) → None ``` Set the profile data in context. # AppContext.set_models_universe ``` set_models_universe( models: ModelsUniverse | None, ) → None ``` Set the model data in context. # AppContext.set_secret_store_data ``` set_secret_store_data( secret_store: CredentialStoreBackend, active_credential_group: ResolvedCredentialGroup | None, ) → None ``` Populate the protected store and active credential group atomically. ## Parameters secret_store type: CredentialStoreBackend Backend used for credential groups and opaque values. active_credential_group type: ResolvedCredentialGroup | None Group selected by the current project. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/decorators/ # yera.cli.decorators App-resource decorator helpers for CLI commands. ## Symbols class AppResource — Resources that CLI commands can require or tolerate loading. def config_for — Return required app resources for a function. def requires — Attach required app resource metadata to a command function. def tolerates — Attach tolerated app resource metadata to a command function. def tolerates_for — Return tolerated app resources for a function. # AppResource Inherits: `Flag` Resources that CLI commands can require or tolerate loading. # config_for ``` config_for( function: Callable, ) → AppResource ``` Return required app resources for a function. # requires ``` requires( *resources, ) → Callable[[Callable], Callable] ``` Attach required app resource metadata to a command function. # tolerates ``` tolerates( *resources, ) → Callable[[Callable], Callable] ``` Attach tolerated app resource metadata to a command function. # tolerates_for ``` tolerates_for( function: Callable, ) → AppResource ``` Return tolerated app resources for a function. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/resources/ # yera.cli.resources Shared helpers for the Cyclopts CLI. ## Submodules common creds models providers --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/resources/common/ # yera.cli.resources.common Shared utility functions for cli resource utils. ## Symbols def utc_now_iso — UTC timestamp in ISO 8601 form for credential metadata. # utc_now_iso ``` utc_now_iso() → str ``` UTC timestamp in ISO 8601 form for credential metadata. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/resources/creds/ # yera.cli.resources.creds Credential-related helpers shared across CLI commands. ## Symbols def ensure_authorised_credential_group — Resolve or create an authorized version-two credential group. def raise_if_bare_leaf_for_prefix_command — Reject a single credential leaf where a namespace is required. def read_json_object_from_cli — Resolve JSON input from inline string or file path. def read_json_raw_from_path_or_stdin — Read raw text from a filesystem path, or stdin when *path_or_dash* is ``'-'``. def require_authorised_credential_group — Resolve an existing credential group authorized for this project. def tool_secret_info — List ordinary tool secrets owned by a credential group. # ensure_authorised_credential_group ``` ensure_authorised_credential_group( ctx: AppContext, group_name: str, ) → CredentialGroupInfo ``` Resolve or create an authorized version-two credential group. ## Parameters ctx type: AppContext Active CLI application context. group_name type: str Configured credential-group name. ## Returns type: CredentialGroupInfo Non-sensitive metadata for the authorized group. ## Raises CredentialGroupNotAuthorisedError If an existing group does not authorize the current project root. # raise_if_bare_leaf_for_prefix_command ``` raise_if_bare_leaf_for_prefix_command( path: str, creds: CredentialGroupMap, single_leaf_command: str, purpose_phrase: str, ) → None ``` Reject a single credential leaf where a namespace is required. ## Parameters path type: str Dotted credential path supplied to the prefix operation. creds type: CredentialGroupMap Credential mapping in which to classify the path. single_leaf_command type: str Suggested command for operating on the leaf, such as `yera cred put my.key`. purpose_phrase type: str Description appended to the recovery message, such as `single-leaf writes`. ## Raises CredentialKeyError If the path identifies a leaf but not a namespace. # read_json_object_from_cli ``` read_json_object_from_cli( json_str: str | None, from_file: str | None, ) → dict[str, Any] ``` Resolve JSON input from inline string or file path. Exactly one of *json_str* or *from_file* must be provided. `--from-file -` reads from `sys.stdin`. # read_json_raw_from_path_or_stdin ``` read_json_raw_from_path_or_stdin( path_or_dash: str, ) → str ``` Read raw text from a filesystem path, or stdin when *path_or_dash* is `'-'`. # require_authorised_credential_group ``` require_authorised_credential_group( ctx: AppContext, group_name: str, ) → CredentialGroupInfo ``` Resolve an existing credential group authorized for this project. ## Parameters ctx type: AppContext Active CLI application context. group_name type: str Configured credential-group name. ## Returns type: CredentialGroupInfo Non-sensitive metadata for the authorized group. ## Raises CredentialGroupNotFoundError If the group does not exist. CredentialGroupNotAuthorisedError If the current project is not authorized for the group. # tool_secret_info ``` tool_secret_info( ctx: AppContext, owner_id: str, ) → tuple[SecretInfo, ...] ``` List ordinary tool secrets owned by a credential group. ## Parameters ctx type: AppContext Active CLI application context. owner_id type: str Stable credential-group identity. ## Returns type: tuple[SecretInfo, ...] Tool-secret metadata ordered by credential name. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/resources/models/ # yera.cli.resources.models Model discovery orchestration shared across CLI commands. ## Symbols def run_model_discovery — Obtain, validate, persist, and render model configuration. # run_model_discovery ``` run_model_discovery( setup: ModelSetup, console: Console, error_console: Console, ) → list[BaseModelConfig] ``` Obtain, validate, persist, and render model configuration. ## Parameters setup type: ModelSetup Model setup bound to the target provider connection. console type: Console Console receiving progress and warning output. error_console type: Console Console receiving setup errors. ## Returns type: list[BaseModelConfig] Models persisted for the connection, or an empty list when setup cannot produce valid configuration. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/resources/providers/ # yera.cli.resources.providers Provider setup orchestration shared across CLI commands. ## Symbols def run_provider_setup — Orchestrates the end-to-end setup process for a provider connection. # run_provider_setup ``` run_provider_setup( handler: BaseProviderSetup, connection_name: str, console: Console, error_console: Console, ) → bool ``` Orchestrates the end-to-end setup process for a provider connection. This function manages the workflow of acquiring provider configuration—first attempting automatic detection and falling back to interactive user prompts. If a configuration is obtained, it is validated and persisted using the reusable provider setup operation before being persisted to the global configuration storage. ## Parameters handler type: BaseProviderSetup An instance of a provider setup handler (e.g., Azure, AWS) that implements the detection and validation logic. connection_name type: str The unique identifier to assign to this connection within the configuration file. console type: Console A Rich Console instance used for printing success messages and progress updates. error_console type: Console A Rich Console instance used for printing warnings, skips, and validation errors. ## Returns type: bool True if the provider was successfully configured and saved to storage, False if the configuration was skipped or validation failed. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/ # yera.cli.setup_handlers Provider setup handlers for interactive and automatic provider configuration. ## Submodules anthropic aws azure base gemini llama_cpp mistral ollama openai openrouter --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/anthropic/ # yera.cli.setup_handlers.anthropic Anthropic provider setup handler. ## Symbols class AnthropicSetup — Handler for configuring Anthropic provider connections. # AnthropicSetup Inherits: `BaseProviderSetup` Handler for configuring Anthropic provider connections. This class implements the logic required to discover, prompt for, and validate the environment variables used to authenticate with Anthropic's API. ## Methods detect_config — Detect and report an Anthropic connection from the environment. ask_for_config — Interactively prompts the user to configure an Anthropic connection. validate — Validate an Anthropic connection through the reusable setup operation. # AnthropicSetup.detect_config ``` detect_config() → AnthropicConnection | None ``` Detect and report an Anthropic connection from the environment. ## Returns type: AnthropicConnection | None A detected connection, or `None` when the conventional API-key environment variable is absent. # AnthropicSetup.ask_for_config ``` ask_for_config() → AnthropicConnection | None ``` Interactively prompts the user to configure an Anthropic connection. First asks the user for confirmation to proceed, then prompts for the name of the environment variable that holds the API key. ## Returns type: AnthropicConnection | None An AnthropicConnection instance containing the user-specified environment variable name, or None if the user declines the setup. # AnthropicSetup.validate ``` validate( config: AnthropicConnection, ) → None ``` Validate an Anthropic connection through the reusable setup operation. ## Parameters config type: AnthropicConnection Anthropic connection to validate. ## Raises ValueError If its API-key environment variable is absent or malformed. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/aws/ # yera.cli.setup_handlers.aws AWS Bedrock provider setup handler. ## Symbols class AWSSetup — Handler for configuring AWS Bedrock provider connections. # AWSSetup Inherits: `BaseProviderSetup` Handler for configuring AWS Bedrock provider connections. This class manages the lifecycle of AWS authentication setup, supporting automatic discovery of local ~/.aws/ profiles and manual interactive configuration of profiles and regions. ## Methods detect_config — Detect AWS profile and region configuration interactively. ask_for_config — Interactively prompts the user to configure an AWS Bedrock connection. validate — Validate an AWS connection through the reusable setup operation. # AWSSetup.detect_config ``` detect_config() → AWSConnection | None ``` Detect AWS profile and region configuration interactively. ## Returns type: AWSConnection | None The selected complete AWS connection, or `None` when no complete connection candidates are available. # AWSSetup.ask_for_config ``` ask_for_config() → AWSConnection | None ``` Interactively prompts the user to configure an AWS Bedrock connection. Prompts the user for an AWS profile name (allowing for the default chain) and a target AWS region. ## Returns type: AWSConnection | None An AWSConnection instance containing the user-provided profile and region, or None if the user declines the setup. # AWSSetup.validate ``` validate( config: AWSConnection, ) → None ``` Validate an AWS connection through the reusable setup operation. ## Parameters config type: AWSConnection AWS connection to validate. ## Raises ValueError If its credentials or connectivity cannot be validated. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/azure/ # yera.cli.setup_handlers.azure Azure OpenAI provider setup handler. ## Symbols class AzureSetup — Handler for configuring Azure OpenAI provider connections. # AzureSetup Inherits: `BaseProviderSetup` Handler for configuring Azure OpenAI provider connections. This class provides mechanisms to automatically discover Azure OpenAI resources across all accessible subscriptions or to manually configure a specific connection via user input. ## Methods detect_config — Discover and select an Azure OpenAI account. ask_for_config — Interactively prompts the user for Azure OpenAI connection details. validate — Validate an Azure connection through the reusable setup operation. # AzureSetup.detect_config ``` detect_config() → AzureConnection | None ``` Discover and select an Azure OpenAI account. ## Returns type: AzureConnection | None The selected Azure OpenAI connection, or `None` when discovery cannot produce an account. # AzureSetup.ask_for_config ``` ask_for_config() → AzureConnection | None ``` Interactively prompts the user for Azure OpenAI connection details. Collects required metadata including the endpoint, resource name, subscription ID, tenant ID, and resource group. ## Returns type: AzureConnection | None An AzureConnection instance containing the user-provided details, or None if the user declines the setup. # AzureSetup.validate ``` validate( config: AzureConnection, ) → None ``` Validate an Azure connection through the reusable setup operation. ## Parameters config type: AzureConnection Azure OpenAI connection to validate. ## Raises ValueError If a Cognitive Services token cannot be acquired. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/base/ # yera.cli.setup_handlers.base Base class for provider connection setup handlers. ## Symbols class BaseProviderSetup — Abstract base for provider connection setup handlers. # BaseProviderSetup Inherits: `ABC` Subclasses: `MistralSetup`, `AnthropicSetup`, `OllamaSetup`, `AzureSetup`, `OpenAISetup`, `OpenRouterSetup`, `AWSSetup`, `LlamaCppSetup`, `GeminiSetup` Abstract base for provider connection setup handlers. Subclasses implement provider-specific config and credential detection and prompting. The CLI command owns orchestration and all writes. ## Methods detect_config — Detect non-credential connection config from environment or files. ask_for_config — Prompt interactively for non-credential connection config fields. validate — Validate credential format. # BaseProviderSetup.detect_config ``` detect_config() → BaseConnection | None ``` Detect non-credential connection config from environment or files. Returns a dict of toml field name → value, or None if detection fails. Simple providers (Anthropic, OpenAI) return {} — no config fields. # BaseProviderSetup.ask_for_config ``` ask_for_config() → BaseConnection | None ``` Prompt interactively for non-credential connection config fields. Returns a dict of toml field name → value, or None if user declines. Simple providers return {} — no config fields to prompt for. # BaseProviderSetup.validate ``` validate( config: BaseConnection, ) → None ``` Validate credential format. ## Raises ValueError If any credential value fails format validation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/gemini/ # yera.cli.setup_handlers.gemini Gemini provider setup handler. ## Symbols class GeminiSetup — Handler for configuring Gemini Developer API connections. # GeminiSetup Inherits: `BaseProviderSetup` Handler for configuring Gemini Developer API connections. ## Methods detect_config — Detect and report a Gemini connection from the environment. ask_for_config — Prompt for a Gemini connection configuration. validate — Validate a Gemini connection through the reusable setup operation. # GeminiSetup.detect_config ``` detect_config() → GeminiConnection | None ``` Detect and report a Gemini connection from the environment. ## Returns type: GeminiConnection | None A connection referencing the first populated API-key variable in SDK precedence order, or `None` when neither variable is populated. # GeminiSetup.ask_for_config ``` ask_for_config() → GeminiConnection | None ``` Prompt for a Gemini connection configuration. ## Returns type: GeminiConnection | None The configured connection, or None when setup is declined. # GeminiSetup.validate ``` validate( config: GeminiConnection, ) → None ``` Validate a Gemini connection through the reusable setup operation. ## Parameters config type: GeminiConnection Gemini connection to validate. ## Raises ValueError If its API-key environment variable is absent or empty. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/llama_cpp/ # yera.cli.setup_handlers.llama_cpp Llama-cpp provider setup handler. ## Symbols class LlamaCppSetup — Handler for configuring Llama-cpp local model providers. # LlamaCppSetup Inherits: `BaseProviderSetup` Handler for configuring Llama-cpp local model providers. This class manages the discovery of local directories containing GGUF model files, allowing Yera to locate and load local LLMs from common installation paths or user-defined locations. ## Methods detect_config — Detect and report accessible llama.cpp model directories. ask_for_config — Interactively prompts the user to define local model directories. validate — Validate and report recoverable llama.cpp directory problems. # LlamaCppSetup.detect_config ``` detect_config() → LlamaCppConnection | None ``` Detect and report accessible llama.cpp model directories. ## Returns type: LlamaCppConnection | None A connection containing detected model directories, or `None` when no conventional directory is currently accessible. # LlamaCppSetup.ask_for_config ``` ask_for_config() → LlamaCppConnection | None ``` Interactively prompts the user to define local model directories. Displays currently detected paths and enters a loop allowing the user to manually add additional directories. Paths are expanded (e.g., ~) and resolved to absolute paths before being saved. ## Returns type: LlamaCppConnection | None A LlamaCppConnection instance containing the union of detected and manually added directories, or None if the user declines. # LlamaCppSetup.validate ``` validate( config: LlamaCppConnection, ) → None ``` Validate and report recoverable llama.cpp directory problems. ## Parameters config type: LlamaCppConnection llama.cpp connection containing model directory paths. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/mistral/ # yera.cli.setup_handlers.mistral Mistral provider setup handler. ## Symbols class MistralSetup — Handler for configuring Mistral provider connections. # MistralSetup Inherits: `BaseProviderSetup` Handler for configuring Mistral provider connections. This class implements the logic required to discover, prompt for, and validate the environment variables used to authenticate with Mistral's API. ## Methods detect_config — Detect and report a Mistral connection from the environment. ask_for_config — Interactively prompts the user to configure a Mistral connection. validate — Validate a Mistral connection through the reusable setup operation. # MistralSetup.detect_config ``` detect_config() → MistralConnection | None ``` Detect and report a Mistral connection from the environment. ## Returns type: MistralConnection | None A detected connection, or `None` when the conventional API-key environment variable is absent. # MistralSetup.ask_for_config ``` ask_for_config() → MistralConnection | None ``` Interactively prompts the user to configure a Mistral connection. First asks the user for confirmation to proceed, then prompts for the name of the environment variable that holds the API key. ## Returns type: MistralConnection | None A MistralConnection instance containing the user-specified environment variable name, or None if the user declines the setup. # MistralSetup.validate ``` validate( config: MistralConnection, ) → None ``` Validate a Mistral connection through the reusable setup operation. ## Parameters config type: MistralConnection Mistral connection to validate. ## Raises ValueError If its API-key environment variable is absent or too short. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/ollama/ # yera.cli.setup_handlers.ollama Ollama provider setup handler. ## Symbols class OllamaSetup — Handler for configuring Ollama provider connections. # OllamaSetup Inherits: `BaseProviderSetup` Handler for configuring Ollama provider connections. This class manages the setup of the connection to a local or remote Ollama server, primarily focusing on the base URL configuration and connectivity verification. ## Methods detect_config — Detect and report the resolved Ollama connection. ask_for_config — Interactively prompts the user for the Ollama server URL. validate — Validate an Ollama connection through the reusable setup operation. # OllamaSetup.detect_config ``` detect_config() → OllamaConnection ``` Detect and report the resolved Ollama connection. ## Returns type: OllamaConnection A normalized connection using the configured host or local default. # OllamaSetup.ask_for_config ``` ask_for_config() → OllamaConnection | None ``` Interactively prompts the user for the Ollama server URL. ## Returns type: OllamaConnection | None An OllamaConnection instance containing the user-provided URL, or None if the user declines the setup. # OllamaSetup.validate ``` validate( config: OllamaConnection, ) → None ``` Validate an Ollama connection through the reusable setup operation. ## Parameters config type: OllamaConnection Ollama connection to validate. ## Raises ValueError If the configured server cannot be reached. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/openai/ # yera.cli.setup_handlers.openai OpenAI provider setup handler. ## Symbols class OpenAISetup — Handler for configuring OpenAI provider connections. # OpenAISetup Inherits: `BaseProviderSetup` Handler for configuring OpenAI provider connections. This class implements the logic required to discover, prompt for, and validate the environment variables used to authenticate with OpenAI's API. ## Methods detect_config — Detect and report an OpenAI connection from the environment. ask_for_config — Interactively prompts the user to configure an OpenAI connection. validate — Validate an OpenAI connection through the reusable setup operation. # OpenAISetup.detect_config ``` detect_config() → OpenAIConnection | None ``` Detect and report an OpenAI connection from the environment. ## Returns type: OpenAIConnection | None A detected OpenAI connection, or `None` when no conventional API-key environment variable is present. # OpenAISetup.ask_for_config ``` ask_for_config() → OpenAIConnection | None ``` Interactively prompts the user to configure an OpenAI connection. First asks the user for confirmation to proceed, then prompts for the name of the environment variable that holds the API key. ## Returns type: OpenAIConnection | None An OpenAIConnection instance containing the user-specified environment variable name, or None if the user declines the setup. # OpenAISetup.validate ``` validate( config: OpenAIConnection, ) → None ``` Validate an OpenAI connection through the reusable setup operation. ## Parameters config type: OpenAIConnection OpenAI connection to validate. ## Raises ValueError If its API-key environment variable is absent or malformed. --- Source: https://yera-labs.io/docs/yera/reference/implementation/cli/setup_handlers/openrouter/ # yera.cli.setup_handlers.openrouter OpenRouter provider setup handler. ## Symbols class OpenRouterSetup — Handler for configuring OpenRouter provider connections. # OpenRouterSetup Inherits: `BaseProviderSetup` Handler for configuring OpenRouter provider connections. ## Methods detect_config — Detect and report an OpenRouter connection from the environment. ask_for_config — Prompt for an OpenRouter connection configuration. validate — Validate an OpenRouter connection through the reusable setup operation. # OpenRouterSetup.detect_config ``` detect_config() → OpenRouterConnection | None ``` Detect and report an OpenRouter connection from the environment. ## Returns type: OpenRouterConnection | None A detected connection, or `None` when the conventional API-key environment variable is absent. # OpenRouterSetup.ask_for_config ``` ask_for_config() → OpenRouterConnection | None ``` Prompt for an OpenRouter connection configuration. ## Returns type: OpenRouterConnection | None The configured connection, or None when setup is declined. # OpenRouterSetup.validate ``` validate( config: OpenRouterConnection, ) → None ``` Validate an OpenRouter connection through the reusable setup operation. ## Parameters config type: OpenRouterConnection OpenRouter connection to validate. ## Raises ValueError If its API-key environment variable is absent or malformed. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/ # yera.config Yera configuration system. ## Submodules exceptions inspection loaders replacement schema storage --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/exceptions/ # yera.config.exceptions Configuration exceptions. ## Symbols class ConfigError — A configuration file could not be read, written, or validated. class ConfigReplacementError — The global configuration cannot be replaced in its current state. class ConnectionConfigError — Raised when connection resolution or validation fails. class ConnectionNotFoundInConfigError — Named connection is missing from the provider's connections. class ConnectionNotSpecifiedError — The active Yera profile does not specify a connection for this provider. class MCPConfigError — Raised when MCP server configuration or resolution fails. class MCPInvalidConfigError — An MCP server declaration failed validation. class MCPServerNotFoundInConfigError — An MCP connection selected by a profile is not configured. class ModelInvalidConfigError — A model entry has invalid config. class ModelNotFoundInConfigError — Named model is missing from yera.toml. class ModelsConfigError — Raised when model config resolution or validation fails. class ModelTypeNotFoundInConfigError — No default model is configured for a given type. class ProfileConfigError — Raised when Yera profile config resolution or validation fails. class ProfileInvalidConfigError — The profiles section failed Pydantic validation. class ProfileNotFoundInConfigError — Named Yera profile is missing from ``yera.toml`` ``[profiles]``. class ProfileNotSpecifiedError — No active Yera profile could be resolved. class ProviderInvalidConfigError — A provider entry failed validation. class ProviderNotFoundInConfigError — Named provider is missing from ``yera.toml``. class ProvidersConfigError — Raised when provider config resolution or validation fails. class ProvidersNotConfigured — The whole providers section is missing from yera.toml. class PyprojectTomlNotFoundError — No ``pyproject.toml`` could be resolved for a project-scoped write. class SettingsError — Raised when settings validation fails fatally. # ConfigError Inherits: `YeraError` Subclasses: `ConfigReplacementError`, `ConnectionConfigError`, `MCPConfigError`, `ModelsConfigError`, `ProfileConfigError`, `ProvidersConfigError`, `PyprojectTomlNotFoundError`, `SettingsError` A configuration file could not be read, written, or validated. # ConfigReplacementError Inherits: `ConfigError` The global configuration cannot be replaced in its current state. Raised when replacement is requested for configuration that is missing or already valid. # ConnectionConfigError Inherits: `ConfigError` Subclasses: `ConnectionNotFoundInConfigError`, `ConnectionNotSpecifiedError` Raised when connection resolution or validation fails. # ConnectionNotFoundInConfigError Inherits: `ConnectionConfigError` Named connection is missing from the provider's connections. # ConnectionNotSpecifiedError Inherits: `ConnectionConfigError` The active Yera profile does not specify a connection for this provider. Raised when a provider type is needed at runtime but the active Yera profile's provider map does not include an entry for it. # MCPConfigError Inherits: `ConfigError` Subclasses: `MCPInvalidConfigError`, `MCPServerNotFoundInConfigError` Raised when MCP server configuration or resolution fails. # MCPInvalidConfigError Inherits: `MCPConfigError` An MCP server declaration failed validation. # MCPServerNotFoundInConfigError Inherits: `MCPConfigError` An MCP connection selected by a profile is not configured. # ModelInvalidConfigError Inherits: `ModelsConfigError` A model entry has invalid config. # ModelNotFoundInConfigError Inherits: `ModelsConfigError` Named model is missing from yera.toml. # ModelsConfigError Inherits: `ConfigError` Subclasses: `ModelInvalidConfigError`, `ModelNotFoundInConfigError`, `ModelTypeNotFoundInConfigError` Raised when model config resolution or validation fails. # ModelTypeNotFoundInConfigError Inherits: `ModelsConfigError` No default model is configured for a given type. # ProfileConfigError Inherits: `ConfigError` Subclasses: `ProfileInvalidConfigError`, `ProfileNotFoundInConfigError`, `ProfileNotSpecifiedError` Raised when Yera profile config resolution or validation fails. # ProfileInvalidConfigError Inherits: `ProfileConfigError` The profiles section failed Pydantic validation. # ProfileNotFoundInConfigError Inherits: `ProfileConfigError` Named Yera profile is missing from `yera.toml` `[profiles]`. # ProfileNotSpecifiedError Inherits: `ProfileConfigError` No active Yera profile could be resolved. Raised when none of CLI flag, pyproject.toml, or yera.toml default yields a profile name. # ProviderInvalidConfigError Inherits: `ProvidersConfigError` A provider entry failed validation. # ProviderNotFoundInConfigError Inherits: `ProvidersConfigError` Named provider is missing from `yera.toml`. # ProvidersConfigError Inherits: `ConfigError` Subclasses: `ProviderInvalidConfigError`, `ProviderNotFoundInConfigError`, `ProvidersNotConfigured` Raised when provider config resolution or validation fails. # ProvidersNotConfigured Inherits: `ProvidersConfigError` The whole providers section is missing from yera.toml. # PyprojectTomlNotFoundError Inherits: `ConfigError` No `pyproject.toml` could be resolved for a project-scoped write. When *message* is omitted, default user-facing copy suggests creating `pyproject.toml` or writing to `yera.toml` instead. # SettingsError Inherits: `ConfigError` Raised when settings validation fails fatally. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/inspection/ # yera.config.inspection Inspect the global Yera configuration without applying runtime resolution. This module provides a narrow interface for determining whether the global `yera.toml` file exists and can be parsed. It does not load project-level overrides or resolve active profiles, providers, or models. ## Symbols class ConfigInspection — Result of inspecting the global Yera configuration file. class ConfigStatus — State of the global Yera configuration file. def inspect_yera_toml — Inspect the global Yera configuration file. # ConfigInspection Result of inspecting the global Yera configuration file. ## Attributes path type: Path Resolved path inspected by the operation. status type: ConfigStatus State determined from file existence, TOML parsing, and schema validation. data type: dict[str, TomlValue] | None Parsed TOML data when parsing succeeds; otherwise `None`. section type: str | None Top-level section that failed schema validation; otherwise `None`. error type: str | None Parsing or validation diagnostic when inspection fails; otherwise `None`. # ConfigStatus Inherits: `str`, `Enum` State of the global Yera configuration file. ## Attributes MISSING The configured `yera.toml` path does not contain a file. VALID The file contains syntactically valid TOML. MALFORMED The file exists but cannot be parsed as TOML. INVALID The file contains valid TOML but invalid Yera configuration. # inspect_yera_toml ``` inspect_yera_toml() → ConfigInspection ``` Inspect the global Yera configuration file. Resolves the global `yera.toml` path, checks whether the file exists, and parses its TOML content when present. Parse failures are represented in the returned result rather than raised. ## Returns type: ConfigInspection The resolved path, inspection status, and any parsed data or parsing diagnostic. ## Raises OSError If the file exists but cannot be accessed. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/loaders/ # yera.config.loaders Load and validate merged config from storage into schema models. ## Submodules mcp models profiles providers settings --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/loaders/mcp/ # yera.config.loaders.mcp MCP config loader. ## Symbols def load_global_mcp_config — Load the MCP server connections defined in the global ``yera.toml``. def load_mcp_config — Load the available MCP server connections from Yera configuration. def resolve_mcp_servers — Resolve the MCP connections enabled by the active profile. # load_global_mcp_config ``` load_global_mcp_config() → MCPConfig ``` Load the MCP server connections defined in the global `yera.toml`. Unlike `load_mcp_config`, servers declared by the current project are left out, so the result lists only the connections setup manages. ## Returns type: MCPConfig Validated global MCP configuration, or an empty catalogue when no MCP section is configured. ## Raises MCPInvalidConfigError If a global server declaration is invalid. # load_mcp_config ``` load_mcp_config() → MCPConfig ``` Load the available MCP server connections from Yera configuration. ## Returns type: MCPConfig Validated MCP configuration, or an empty catalogue when no MCP section is configured. # resolve_mcp_servers ``` resolve_mcp_servers( config: MCPConfig, active_profile: Profile, ) → dict[str, MCPServerConfig] ``` Resolve the MCP connections enabled by the active profile. ## Parameters config type: MCPConfig Catalogue of available MCP server connections. active_profile type: Profile Profile containing the connection names to enable. ## Returns type: dict[str, MCPServerConfig] Selected server connections in profile declaration order. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/loaders/models/ # yera.config.loaders.models Model universe loader — reads and validates model config from yera.toml. ## Symbols def get_model_config — Look up a model by id across all type lists in the universe. def load_model_universe — Read ``[models]`` from yera.toml and build a ``ModelUniverse`` instance. def read_pyproject_yera_model_default — Read the default model id for a single type from ``[tool.yera.model_defaults]``. def read_pyproject_yera_model_defaults — Read per-type model defaults from ``[tool.yera.model_defaults]`` in pyproject.toml. def resolve_default_model — Determine the effective model id for a given type using the resolution order. # get_model_config ``` get_model_config( model_id: str, model_type: str, catalog: ModelCatalogue, ) → BaseModelConfig ``` Look up a model by id across all type lists in the universe. ## Parameters model_id type: str Yera-internal dot-delimited model id. model_type type: str The model type to look up, e.g. `"llm"`. catalog type: ModelCatalogue The runtime model catalogue filtered to the active Yera profile. ## Returns type: BaseModelConfig The matching model config object. ## Raises ModelNotFoundInConfigError If no model with the given id exists in any type list. # load_model_universe ``` load_model_universe() → ModelsUniverse ``` Read `[models]` from yera.toml and build a `ModelUniverse` instance. Returns an empty `ModelUniverse` when the section or file is absent. Validation is eager — malformed model config raises immediately via Pydantic. ## Returns type: ModelsUniverse A `ModelUniverse` instance populated from yera.toml, or an empty instance if the section is absent. ## Raises ModelInvalidConfigError If the models section fails Pydantic validation. # read_pyproject_yera_model_default ``` read_pyproject_yera_model_default( model_type: str, ) → str | None ``` Read the default model id for a single type from `[tool.yera.model_defaults]`. ## Parameters model_type type: str The model type to read the default for, e.g. `"llm"`. ## Returns type: str | None The model id string if present and valid, otherwise `None`. # read_pyproject_yera_model_defaults ``` read_pyproject_yera_model_defaults() → dict[str, str] ``` Read per-type model defaults from `[tool.yera.model_defaults]` in pyproject.toml. Each key is a model type (e.g. `"llm"`, `"embeddings"`) and each value is a Yera-internal model id string. Only string values are included — malformed entries are silently ignored. ## Returns type: dict[str, str] A dict mapping model type to default model id for any types configured in `[tool.yera.model_defaults]`. Empty dict if the section is absent. # resolve_default_model ``` resolve_default_model( model_override: str | None, catalog: ModelCatalogue, model_type: str, pyproject_model: str | None = None, ) → str ``` Determine the effective model id for a given type using the resolution order. Priority: CLI `--model` override → `pyproject.toml` model_defaults → active profile catalog default → raise. ## Parameters model_override type: str | None Explicit model id from a CLI flag, or `None`. catalog type: ModelCatalogue The runtime model catalog filtered to the active Yera profile. model_type type: str The model type to resolve the default for, e.g. `"llm"`. pyproject_model type: str | None = None Default model id from `pyproject.toml` for this type, or `None`. Callers should pass the result of `read_pyproject_yera_model_default(model_type)`. ## Returns type: str The resolved model id string. ## Raises ModelTypeNotFoundInConfigError If no default can be resolved for the given type. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/loaders/profiles/ # yera.config.loaders.profiles Yera profile loader — reads and validates profile config from yera.toml. ## Symbols def get_profile — Look up a named Yera profile from the loaded profiles config. def load_profiles — Read ``[profiles]`` from yera.toml and build a ``Profiles`` instance. def read_pyproject_yera_profile — Read Yera profile override from ``[tool.yera.profiles]`` in pyproject.toml. def resolve_active_profile — Determine the effective Yera profile name using the resolution order. # get_profile ``` get_profile( profile_name: str, profiles: Profiles, ) → Profile ``` Look up a named Yera profile from the loaded profiles config. ## Parameters profile_name type: str Name of the Yera profile to retrieve. profiles type: Profiles The loaded Yera profiles config. ## Returns type: Profile The matching Yera profile object. ## Raises ProfileNotFoundInConfigError If no profile with the given name exists in profiles. # load_profiles ``` load_profiles() → Profiles | None ``` Read `[profiles]` from yera.toml and build a `Profiles` instance. Returns an empty `Profiles` when the section or file is absent. Validation is eager — malformed profile config raises immediately via Pydantic. ## Returns type: Profiles | None A `Profiles` instance populated from yera.toml, or `None` if the section is absent. ## Raises ProfileInvalidConfigError If the profiles section fails Pydantic validation. # read_pyproject_yera_profile ``` read_pyproject_yera_profile() → str | None ``` Read Yera profile override from `[tool.yera.profiles]` in pyproject.toml. Looks for a `default` key under `[tool.yera.profiles]`, e.g. `[tool.yera.profiles] default = "work"` overrides the active Yera profile for this project. ## Returns type: str | None The profile name string if present and valid, otherwise `None`. # resolve_active_profile ``` resolve_active_profile( profile_override: str | None, profiles: Profiles, pyproject_profile: str | None = None, ) → str ``` Determine the effective Yera profile name using the resolution order. Priority: CLI `--profile` override → `pyproject.toml` profiles default → `yera.toml` profiles default → raise. ## Parameters profile_override type: str | None Explicit profile name from a CLI `--profile` flag, or `None`. profiles type: Profiles The loaded Yera profiles config. pyproject_profile type: str | None = None Active profile override from `pyproject.toml`, or `None`. Callers should pass the result of `read_pyproject_yera_profile()`. ## Returns type: str The resolved active profile name string. ## Raises ProfileNotSpecifiedError If no profile can be resolved from any source. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/loaders/providers/ # yera.config.loaders.providers Provider config loader — reads and validates provider config from yera.toml. ## Symbols def get_connection — Look up a named connection from a provider config. def get_provider_config — Look up a named provider from the loaded providers config. def load_providers — Read ``[providers]`` from yera.toml and build a ``Providers`` instance. def resolve_connection — Determine the active connection name for a provider from the Yera profile. # get_connection ``` get_connection( connection_name: str, provider_type: str, provider_config: BaseProviderConfig, ) → BaseConnection ``` Look up a named connection from a provider config. ## Parameters connection_name type: str Name of the connection to retrieve. provider_type type: str Provider type key, used in error messages. provider_config type: BaseProviderConfig The loaded provider config to look up from. ## Returns type: BaseConnection The matching connection object. ## Raises ConnectionNotFoundInConfigError If no connection with the given name exists on the provider. # get_provider_config ``` get_provider_config( provider_type: str, providers: Providers, ) → BaseProviderConfig ``` Look up a named provider from the loaded providers config. ## Parameters provider_type type: str Provider type key, e.g. `"aws"`, `"ollama"`. providers type: Providers The loaded providers config. ## Returns type: BaseProviderConfig The provider config for the given type. ## Raises ProviderNotFoundInConfigError If the provider type is not configured. # load_providers ``` load_providers() → Providers | None ``` Read `[providers]` from yera.toml and build a `Providers` instance. Returns an empty `Providers` when the section or file is absent. Validation is eager — malformed provider config raises immediately via Pydantic. ## Returns type: Providers | None A `Providers` instance populated from yera.toml, or an empty instance if the section is absent. ## Raises ProviderInvalidConfigError If any provider entry fails Pydantic validation. # resolve_connection ``` resolve_connection( provider_type: str, provider_config: BaseProviderConfig, active_profile: Profile, ) → str ``` Determine the active connection name for a provider from the Yera profile. Looks up the connection name for the given provider type in the active Yera profile's provider map. The Yera profile is the sole source of truth for which connection is active — there is no fallback. ## Parameters provider_type type: str Provider type key, e.g. `"aws"`, `"ollama"`. provider_config type: BaseProviderConfig The loaded provider config, used to validate that the resolved connection name actually exists. active_profile type: Profile The active Yera profile whose provider map is used for resolution. ## Returns type: str The resolved connection name string. ## Raises ConnectionNotSpecifiedError If the provider type is not listed in the active Yera profile's provider map. ConnectionNotFoundInConfigError If the resolved connection name does not exist on the provider config. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/loaders/settings/ # yera.config.loaders.settings Settings loader — merges and validates settings from both config sources. ## Symbols def load_and_validate_settings — Load settings from pyproject.toml and yera.toml, then validate. # load_and_validate_settings ``` load_and_validate_settings( fatal: bool = True, ) → Settings | None ``` Load settings from pyproject.toml and yera.toml, then validate. Resolution order per field: pyproject.toml → yera.toml → model default. Only keys matching `Settings` model fields are extracted from `[tool.yera]`; other keys (e.g. `hub`) are ignored. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/replacement/ # yera.config.replacement Safely replace unusable global Yera configuration. ## Symbols class ConfigReplacement — Result of replacing unusable global Yera configuration. def replace_invalid_yera_toml — Back up and replace unusable global Yera configuration. # ConfigReplacement Result of replacing unusable global Yera configuration. ## Attributes path type: Path Global configuration path replaced by the operation. backup_path type: Path Path containing the original configuration. # replace_invalid_yera_toml ``` replace_invalid_yera_toml() → ConfigReplacement ``` Back up and replace unusable global Yera configuration. Re-inspects the global configuration immediately before replacement to avoid acting on stale setup state. Only malformed TOML or schema-invalid Yera configuration can be replaced. The original file is copied into a `backups` directory beside `yera.toml`. The active configuration is then atomically replaced by an empty file, which is valid initial Yera configuration. ## Returns type: ConfigReplacement Paths to the replaced global configuration and its preserved backup. ## Raises ConfigReplacementError If the configuration is missing or valid. OSError If the backup or atomic replacement cannot be completed. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/schema/ # yera.config.schema Config Pydantic models (settings). ## Submodules mcp models profiles providers settings --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/schema/mcp/ # yera.config.schema.mcp MCP server configuration schemas. ## Symbols class MCPConfig — Configured MCP server connections available for profile selection. class MCPNoAuth — Declare that an MCP server requires no authentication. class MCPOAuthAuth — Reference a stored OAuth authorization for an MCP server. class MCPSecretHeadersAuth — Send HTTP headers whose values the connection keeps in the secret store. class MCPServerConfig — Configuration required to connect to one MCP server. class MCPStaticHeadersAuth — Reference credentials supplied as static HTTP headers. def require_http_url — Require a complete HTTP endpoint for streamable MCP transport. # MCPConfig Inherits: `BaseModel` Configured MCP server connections available for profile selection. # MCPNoAuth Inherits: `BaseModel` Declare that an MCP server requires no authentication. # MCPOAuthAuth Inherits: `BaseModel` Reference a stored OAuth authorization for an MCP server. ## Attributes type type: Literal['oauth'] Discriminator identifying OAuth authentication. authorization_id type: str Stable identity of the stored authorization. client_profile type: str | None Optional predefined OAuth client configuration. # MCPSecretHeadersAuth Inherits: `BaseModel` Send HTTP headers whose values the connection keeps in the secret store. ## Attributes type type: Literal['secret_headers'] Discriminator identifying connection-owned header authentication. secret_id type: str Owner of the header values in Yera's secret store. headers type: Annotated[list[str], Field(min_length=1)] Names of the headers sent with every request. # MCPServerConfig Inherits: `BaseModel` Configuration required to connect to one MCP server. ## Attributes url type: str Streamable HTTP endpoint exposed by the MCP server. enabled type: bool Whether this server is available to Yera. auth type: MCPAuth Authentication policy used for this server. ## Methods validate_http_url — Require a complete HTTP endpoint for streamable MCP transport. # MCPServerConfig.validate_http_url ``` validate_http_url( value: str, ) → str ``` Require a complete HTTP endpoint for streamable MCP transport. # MCPStaticHeadersAuth Inherits: `BaseModel` Reference credentials supplied as static HTTP headers. ## Attributes type type: Literal['headers'] Discriminator identifying static-header authentication. headers type: dict[str, str] Mapping of HTTP header names to credential keys. # require_http_url ``` require_http_url( value: str, ) → str ``` Require a complete HTTP endpoint for streamable MCP transport. ## Parameters value type: str The endpoint to check. ## Returns type: str The endpoint, unchanged. ## Raises ValueError If the endpoint is not an absolute HTTP or HTTPS URL. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/schema/models/ # yera.config.schema.models Model schema — universe of all discovered models and runtime catalog view. ## Symbols class AnthropicLLMCapabilities — Capabilities specific to Anthropic models. class AnthropicLLMInference — Anthropic inference settings model. class AwsLLMCapabilities — Capabilities of AWS Bedrock LLMs. class AwsLLMInference — AWS Bedrock inference settings model. class BaseModelConfig — Fields common to all model types. class EmbeddingsConfig — Config for an embeddings model. class GeminiLLMCapabilities — Capabilities reported or looked up for a Gemini model. class GeminiLLMInference — Inference settings for Gemini Developer API models. class GenericLLMCapabilities — Capabilities for a generic LLM (no provider-specific features). class GenericLLMInference — Default inference settings representation. class LlamaCppLLMCapabilities — Capabilities of llama-cpp LLMs. class LlamaCppLLMInference — Llama-cpp inference settings model. class LLMCapabilities — Base for all LLM capabilities models. class LLMConfig — Config for a large language model. class LLMInference — Base class for all LLM inference settings models. class MistralLLMCapabilities — Capabilities of Mistral LLMs. class MistralLLMInference — Mistral inference settings model. class ModelCatalogue — Runtime view of the model universe filtered to the active Yera profile. class ModelsUniverse — All discovered models across all provider connections. class OpenAILLMCapabilities — Capabilities of OpenAI LLMs. class OpenAILLMInference — OpenAI inference settings model. class OpenRouterLLMCapabilities — Capabilities reported for an OpenRouter model. class OpenRouterLLMInference — Inference settings for models invoked through OpenRouter. class RerankerConfig — Config for a reranker model. class STTConfig — Config for a speech-to-text model. class TTSConfig — Config for a text-to-speech model. class TypedCatalogue — A filtered runtime view of models of one type for the active Yera profile. # AnthropicLLMCapabilities Inherits: `LLMCapabilities` Capabilities specific to Anthropic models. # AnthropicLLMInference Inherits: `LLMInference` Anthropic inference settings model. # AwsLLMCapabilities Inherits: `LLMCapabilities` Capabilities of AWS Bedrock LLMs. # AwsLLMInference Inherits: `LLMInference` AWS Bedrock inference settings model. # BaseModelConfig Inherits: `BaseModel` Subclasses: `EmbeddingsConfig`, `LLMConfig`, `RerankerConfig`, `STTConfig`, `TTSConfig` Fields common to all model types. ## Attributes id type: str Yera-internal dot-delimited identifier. Must have at least three segments: `..`, with optional further nesting for variants e.g. `llama_cpp.meta.llama3.8b.q4_k_m`. Does not encode the connection name — that is stored separately in `connection`. model_id type: str Provider-side model identifier passed directly to the API or library, e.g. `"claude-sonnet-4-20250514"` or a HuggingFace repo id like `"meta-llama/Meta-Llama-3-8B-GGUF"`. name type: str Human-readable display name, e.g. `"Claude Sonnet 4"`. provider type: str Key into :class:`~yera.config.schema.providers.Providers` identifying which provider serves this model, e.g. `"aws"`. connection type: str Name of the provider connection under which this model was discovered, e.g. `"work"`. Together with `provider`, uniquely identifies the runtime interface and credentials to use. author type: str Who created the model, e.g. `"anthropic"` or `"meta"`. Distinct from provider — a Meta model can be served via AWS Bedrock. ## Raises ValueError If `id` has fewer than three dot-delimited segments. ## Methods id_has_minimum_depth — Check that id has at least three dot-delimited segments. id_prefix_matches_provider — Check that the first segment of id matches provider. # BaseModelConfig.id_has_minimum_depth ``` id_has_minimum_depth( v: str, ) → str ``` Check that id has at least three dot-delimited segments. ## Parameters v type: str The id string to validate. ## Returns type: str The validated id string. ## Raises ValueError If the id has fewer than three segments. # BaseModelConfig.id_prefix_matches_provider ``` id_prefix_matches_provider() → BaseModelConfig ``` Check that the first segment of id matches provider. ## Returns type: BaseModelConfig The validated model config. ## Raises ValueError If the first segment of id does not match provider. # EmbeddingsConfig Inherits: `BaseModelConfig` Config for an embeddings model. ## Attributes type type: Literal['embedding'] Discriminator field, always `"embedding"`. dimensions type: int | None Size of the embedding vector produced by the model. max_input_tokens type: int | None Maximum number of tokens the model can embed in a single request. # GeminiLLMCapabilities Inherits: `LLMCapabilities` Capabilities reported or looked up for a Gemini model. # GeminiLLMInference Inherits: `LLMInference` Inference settings for Gemini Developer API models. # GenericLLMCapabilities Inherits: `LLMCapabilities` Capabilities for a generic LLM (no provider-specific features). # GenericLLMInference Inherits: `LLMInference` Default inference settings representation. # LlamaCppLLMCapabilities Inherits: `LLMCapabilities` Capabilities of llama-cpp LLMs. # LlamaCppLLMInference Inherits: `LLMInference` Llama-cpp inference settings model. # LLMCapabilities Inherits: `BaseModel` Subclasses: `AnthropicLLMCapabilities`, `AwsLLMCapabilities`, `GeminiLLMCapabilities`, `GenericLLMCapabilities`, `LlamaCppLLMCapabilities`, `MistralLLMCapabilities`, `OpenAILLMCapabilities`, `OpenRouterLLMCapabilities` Base for all LLM capabilities models. # LLMConfig Inherits: `BaseModelConfig` Config for a large language model. ## Attributes type type: Literal['llm'] Discriminator field, always `"llm"`. context_window type: int | None Maximum number of tokens the model can process in a single request (prompt + completion). max_output_tokens type: int | None Maximum number of tokens the model can generate. # LLMInference Inherits: `BaseModel` Subclasses: `AnthropicLLMInference`, `AwsLLMInference`, `GeminiLLMInference`, `GenericLLMInference`, `LlamaCppLLMInference`, `MistralLLMInference`, `OpenAILLMInference`, `OpenRouterLLMInference` Base class for all LLM inference settings models. # MistralLLMCapabilities Inherits: `LLMCapabilities` Capabilities of Mistral LLMs. # MistralLLMInference Inherits: `LLMInference` Mistral inference settings model. # ModelCatalogue Inherits: `BaseModel` Runtime view of the model universe filtered to the active Yera profile. Never serialized — constructed by :meth:`ModelsUniverse.for_profile`. Contains only models whose `provider` and `connection` match the active Yera profile's provider map. ## Attributes llm type: TypedCatalogue[LLMConfig] Catalogue of large language models visible under the active profile. embedding type: TypedCatalogue[EmbeddingsConfig] Catalogue of embeddings models visible under the active profile. tts type: TypedCatalogue[TTSConfig] Catalogue of text-to-speech models visible under the active profile. stt type: TypedCatalogue[STTConfig] Catalogue of speech-to-text models visible under the active profile. reranker type: TypedCatalogue[RerankerConfig] Catalogue of reranker models visible under the active profile. # ModelsUniverse Inherits: `BaseModel` All discovered models across all provider connections. Serialized to and from `yera.toml` under `[models]`. Contains no defaults — those live in :class:`~yera.config.schema.profiles.Profile`. ## Attributes llm type: list[LLMConfig] All discovered large language models. embedding type: list[EmbeddingsConfig] All discovered embeddings models. tts type: list[TTSConfig] All discovered text-to-speech models. stt type: list[STTConfig] All discovered speech-to-text models. reranker type: list[RerankerConfig] All discovered reranker models. ## Methods for_profile — Build a filtered runtime ``ModelCatalogue`` for the active Yera profile. # ModelsUniverse.for_profile ``` for_profile( profile: Profile, ) → ModelCatalogue ``` Build a filtered runtime `ModelCatalogue` for the active Yera profile. Filters each model type list to models whose `provider` and `connection` match an entry in the profile's provider map, then inserts per-type defaults from the profile's `model_defaults`. ## Parameters profile type: Profile The active Yera profile to filter and resolve against. ## Returns type: ModelCatalogue A `ModelCatalogue` containing only models visible under the active profile, with defaults populated from the profile. # OpenAILLMCapabilities Inherits: `LLMCapabilities` Capabilities of OpenAI LLMs. # OpenAILLMInference Inherits: `LLMInference` OpenAI inference settings model. # OpenRouterLLMCapabilities Inherits: `LLMCapabilities` Capabilities reported for an OpenRouter model. # OpenRouterLLMInference Inherits: `LLMInference` Inference settings for models invoked through OpenRouter. # RerankerConfig Inherits: `BaseModelConfig` Config for a reranker model. ## Attributes type type: Literal['reranker'] Discriminator field, always `"reranker"`. # STTConfig Inherits: `BaseModelConfig` Config for a speech-to-text model. ## Attributes type type: Literal['stt'] Discriminator field, always `"stt"`. # TTSConfig Inherits: `BaseModelConfig` Config for a text-to-speech model. ## Attributes type type: Literal['tts'] Discriminator field, always `"tts"`. # TypedCatalogue Inherits: `BaseModel`, `Generic[M]` A filtered runtime view of models of one type for the active Yera profile. Never serialized — constructed at runtime by :meth:`ModelsUniverse.for_profile`. The `default` field is populated from the active :class:`~yera.config.schema.profiles.Profile`'s `model_defaults`. ## Attributes models type: dict[str, M] Models of this type visible under the active Yera profile. default type: str | None Yera id of the default model for this type, sourced from the active Yera profile. `None` if no default is configured — a runtime error when a default is actually needed. ## Methods default_exists — Check that the default model id exists in models. # TypedCatalogue.default_exists ``` default_exists() → TypedCatalogue ``` Check that the default model id exists in models. ## Returns type: TypedCatalogue The validated catalogue. ## Raises ValueError If default is set but not present in models. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/schema/profiles/ # yera.config.schema.profiles Yera profile schemas: top-level environment context. ## Symbols class Profile — A Yera profile — one named environment context. class ProfileModelDefaults — Yera profile model default values. class ProfileProviderConnections — Yera profile provider connection config. class Profiles — Yera profiles config loaded from ``yera.toml``. # Profile Inherits: `BaseModel` A Yera profile — one named environment context. Ties together a set of provider connections and optional model defaults. The active profile is resolved via CLI `--profile` flag → `pyproject.toml` → `yera.toml` default. ## Attributes description type: str | None Optional human-readable description of this profile, e.g. `"Work AWS account with EU endpoints"`. providers type: ProfileProviderConnections Map of provider type to connection name, e.g. `{"aws": "work", "ollama": "local"}`. Only providers needed by this profile need to be listed. model_defaults type: ProfileModelDefaults Map of model type to default model id, e.g. `{"llm": "aws.meta.llama3"}`. Optional — missing defaults are a runtime error when a default is actually needed. mcp type: list[str] Ordered names of MCP server connections enabled for this profile. # ProfileModelDefaults Inherits: `BaseModel` Yera profile model default values. # ProfileProviderConnections Inherits: `BaseModel` Yera profile provider connection config. ## Methods empty — Check if none of the profile's provider connections are configured. # ProfileProviderConnections.empty ``` empty() → bool ``` Check if none of the profile's provider connections are configured. ## Returns type: bool True if none of the profile's provider connections are configured, # Profiles Inherits: `BaseModel` Yera profiles config loaded from `yera.toml`. ## Attributes default type: str | None Name of the profile to use when no override is set. Required — setup creates a `default` profile automatically. profiles type: dict[str, Profile] Named Yera profiles, keyed by profile name. ## Raises ValueError If `default` is not a key in `profiles`. ## Methods default_profile_exists — Check that the default profile name exists in profiles. # Profiles.default_profile_exists ``` default_profile_exists() → Profiles ``` Check that the default profile name exists in profiles. ## Raises ValueError If `default` is not a key in `profiles`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/schema/providers/ # yera.config.schema.providers Provider config — one entry per provider type, each holding named connections. ## Symbols class AnthropicConnection — Connection config for the Anthropic API. class AnthropicProviderConfig — Provider config for the Anthropic API. class AWSConnection — Connection config for AWS Bedrock. class AWSProviderConfig — Provider config for AWS Bedrock. class AzureConnection — Connection config for Azure OpenAI. class AzureProviderConfig — Provider config for Azure OpenAI. class BaseConnection — Base class for all provider connections. class BaseProviderConfig — Common structure for all provider configs. class GeminiConnection — Connection config for the Gemini Developer API. class GeminiProviderConfig — Provider config for the Gemini Developer API. class LlamaCppConnection — Connection config for llama-cpp direct library mode. class LlamaCppProviderConfig — Provider config for llama-cpp direct library mode. class MistralConnection — Connection config for the Mistral API. class MistralProviderConfig — Provider config for the Mistral API. class OllamaConnection — Connection config for an Ollama instance. class OllamaProviderConfig — Provider config for Ollama. class OpenAIConnection — Connection config for the OpenAI API. class OpenAIProviderConfig — Provider config for the OpenAI API. class OpenRouterConnection — Connection config for the OpenRouter API. class OpenRouterProviderConfig — Provider config for the OpenRouter API. class Providers — Top-level provider config loaded from ``yera.toml``. # AnthropicConnection Inherits: `BaseConnection` Connection config for the Anthropic API. No connection config beyond credentials — the endpoint is fixed. ## Attributes credentials_map Names of secrets required by this connection. # AnthropicProviderConfig Inherits: `BaseProviderConfig` Provider config for the Anthropic API. ## Attributes connections type: dict[str, AnthropicConnection] Named connection configs, each declaring credential names. # AWSConnection Inherits: `BaseConnection` Connection config for AWS Bedrock. ## Attributes region type: str AWS region to connect to, e.g. `"eu-west-1"`. profile type: str Underlying AWS named profile from `~/.aws/config`. If `None`, the default AWS profile is used. credentials_map type: str Names of secrets required by this connection. # AWSProviderConfig Inherits: `BaseProviderConfig` Provider config for AWS Bedrock. ## Attributes connections type: dict[str, AWSConnection] Named connection configs, each declaring a region, optional AWS profile name, and credential names. # AzureConnection Inherits: `BaseConnection` Connection config for Azure OpenAI. ## Attributes endpoint type: str Azure OpenAI endpoint URL. api_version type: str Azure OpenAI API version string, e.g. `"2024-02-01"`. credentials_map type: str Names of secrets required by this connection. # AzureProviderConfig Inherits: `BaseProviderConfig` Provider config for Azure OpenAI. ## Attributes connections type: dict[str, AzureConnection] Named connection configs, each declaring an endpoint, API version, and credential names. # BaseConnection Inherits: `BaseModel` Subclasses: `AnthropicConnection`, `AWSConnection`, `AzureConnection`, `GeminiConnection`, `LlamaCppConnection`, `MistralConnection`, `OllamaConnection`, `OpenAIConnection`, `OpenRouterConnection` Base class for all provider connections. `credentials` declares the names of secrets this connection requires. The retrieval method resolves each name from the keyring using the path `providers...`. ## Attributes credentials_map Names of secrets required by this connection. # BaseProviderConfig Inherits: `BaseModel`, `Generic[TConnection]` Subclasses: `AnthropicProviderConfig`, `AWSProviderConfig`, `AzureProviderConfig`, `GeminiProviderConfig`, `LlamaCppProviderConfig`, `MistralProviderConfig`, `OllamaProviderConfig`, `OpenAIProviderConfig`, `OpenRouterProviderConfig` Common structure for all provider configs. Each provider holds a named collection of connections. The active connection is always determined by the active Yera profile's provider map — never by the provider itself. ## Attributes connections type: dict[str, TConnection] Named connection configs for this provider. # GeminiConnection Inherits: `BaseConnection` Connection config for the Gemini Developer API. ## Attributes api_key_loc type: str Environment variable containing the Gemini API key. # GeminiProviderConfig Inherits: `BaseProviderConfig` Provider config for the Gemini Developer API. ## Attributes connections type: dict[str, GeminiConnection] Named Gemini connection configurations. # LlamaCppConnection Inherits: `BaseConnection` Connection config for llama-cpp direct library mode. ## Attributes model_dirs type: list[str] Filesystem paths to directories containing local GGUF model files. # LlamaCppProviderConfig Inherits: `BaseProviderConfig` Provider config for llama-cpp direct library mode. ## Attributes connections type: dict[str, LlamaCppConnection] Named connection configs, each declaring one or more local model directory paths. # MistralConnection Inherits: `BaseConnection` Connection config for the Mistral API. No connection config beyond credentials — the endpoint is fixed. ## Attributes credentials_map Names of secrets required by this connection. # MistralProviderConfig Inherits: `BaseProviderConfig` Provider config for the Mistral API. ## Attributes connections type: dict[str, MistralConnection] Named connection configs, each declaring credential names. # OllamaConnection Inherits: `BaseConnection` Connection config for an Ollama instance. Supports both local and remote instances via `base_url`. Credentials are optional — only needed for secured remote instances. ## Attributes base_url type: str URL of the Ollama instance. credentials_map type: str Names of secrets required by this connection. # OllamaProviderConfig Inherits: `BaseProviderConfig` Provider config for Ollama. Supports both local and remote instances via per-connection `base_url`. ## Attributes connections type: dict[str, OllamaConnection] Named connection configs, each declaring a base URL and optional credential names. # OpenAIConnection Inherits: `BaseConnection` Connection config for the OpenAI API. No connection config beyond credentials — the endpoint is fixed. ## Attributes credentials_map Names of secrets required by this connection. # OpenAIProviderConfig Inherits: `BaseProviderConfig` Provider config for the OpenAI API. ## Attributes connections type: dict[str, OpenAIConnection] Named connection configs, each declaring credential names. # OpenRouterConnection Inherits: `BaseConnection` Connection config for the OpenRouter API. ## Attributes api_key_loc type: str Environment variable containing the OpenRouter API key. http_referer type: str | None Optional application URL used for OpenRouter attribution. app_title type: str | None Optional application name used for OpenRouter attribution. # OpenRouterProviderConfig Inherits: `BaseProviderConfig` Provider config for the OpenRouter API. ## Attributes connections type: dict[str, OpenRouterConnection] Named OpenRouter connection configurations. # Providers Inherits: `BaseModel` Top-level provider config loaded from `yera.toml`. Each field is optional — only configured providers are present. ## Attributes anthropic type: AnthropicProviderConfig | None Anthropic API provider config. openai type: OpenAIProviderConfig | None OpenAI API provider config. mistral type: MistralProviderConfig | None Mistral API provider config. aws type: AWSProviderConfig | None AWS Bedrock provider config. azure type: AzureProviderConfig | None Azure OpenAI provider config. ollama type: OllamaProviderConfig | None Ollama provider config. llama_cpp type: LlamaCppProviderConfig | None llama-cpp direct library mode provider config. openrouter type: OpenRouterProviderConfig | None OpenRouter API provider config. gemini type: GeminiProviderConfig | None Gemini Developer API provider config. ## Methods connection_for_model — Get the provider connection used by a given model. # Providers.connection_for_model ``` connection_for_model( model: BaseModelConfig, ) → BaseConnection ``` Get the provider connection used by a given model. The connection object represents all the data needed to call the provider and use the given model. ## Returns type: BaseConnection the connection config object representing the connection. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/schema/settings/ # yera.config.schema.settings Global settings schema. ## Symbols class Settings — Settings for Yera. def validate_log_level — Validate and normalise ``log_level`` to a canonical uppercase name. # Settings Inherits: `BaseModel` Settings for Yera. # validate_log_level ``` validate_log_level( value: object, ) → str ``` Validate and normalise `log_level` to a canonical uppercase name. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/storage/ # yera.config.storage On-disk path discovery and TOML read/write. ## Submodules paths read write --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/storage/paths/ # yera.config.storage.paths Path resolution helpers for config files. ## Symbols def discover_pyproject_for_read — Discover the nearest pyproject.toml containing [tool.yera], stopping at a .git directory. def discover_pyproject_for_write — Discover the nearest pyproject.toml (any content), stopping at a .git directory. def yera_toml_path — Return the resolved yera.toml path. # discover_pyproject_for_read ``` discover_pyproject_for_read() → Path | None ``` Discover the nearest pyproject.toml containing [tool.yera], stopping at a .git directory. # discover_pyproject_for_write ``` discover_pyproject_for_write() → Path | None ``` Discover the nearest pyproject.toml (any content), stopping at a .git directory. # yera_toml_path ``` yera_toml_path() → Path ``` Return the resolved yera.toml path. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/storage/read/ # yera.config.storage.read TOML reading helpers for config. ## Symbols def read_pyproject_yera — Read the pyproject.toml discovered for read and return [tool.yera] only. def read_pyproject_yera_apps_dir — Return the resolved apps directory from ``[tool.yera] apps_dir``, or None. def read_toml_at_path — Read a TOML file into a dict, returning {} when missing. def read_yera_toml — Read yera.toml using the resolved config path. # read_pyproject_yera ``` read_pyproject_yera() → dict[str, TomlValue] ``` Read the pyproject.toml discovered for read and return [tool.yera] only. # read_pyproject_yera_apps_dir ``` read_pyproject_yera_apps_dir() → Path | None ``` Return the resolved apps directory from `[tool.yera] apps_dir`, or None. The path is resolved relative to the directory containing the discovered `pyproject.toml`, not relative to cwd. Returns None when the key is absent, the value is not a string, or no qualifying pyproject.toml is found. # read_toml_at_path ``` read_toml_at_path( path: Path, ) → dict[str, TomlValue] ``` Read a TOML file into a dict, returning {} when missing. # read_yera_toml ``` read_yera_toml() → dict[str, TomlValue] ``` Read yera.toml using the resolved config path. --- Source: https://yera-labs.io/docs/yera/reference/implementation/config/storage/write/ # yera.config.storage.write Persist edits to `yera.toml` and `pyproject.toml` while keeping human-oriented layout. **Why tomlkit (and not tomli + tomli-w, or `tomllib` + a writer)?** Those paths parse TOML into a plain `dict` and write it back with a fresh serialiser. The whole file is re-emitted, so comments, spacing, and section order outside our edits are lost. That is especially bad for `pyproject.toml`, which people hand-edit and share with Ruff, Hatch, and so on. **tomlkit** loads the file into a *document* — a structured representation that still carries the original layout. We only assign into the tables Yera cares about; the rest of the file is left as-is on save. Public functions are the supported mutations. Private helpers load or save that document, ensure nested tables exist, and run a small *mutator* that returns whether anything changed worth writing to disk (so we skip useless rewrites where that matters). ## Symbols def delete_yera_toml — Remove the resolved ``yera.toml`` path; do nothing if it is already absent. def remove_all_models — Remove model entries from ``[models]``. def remove_all_profiles — Clear every profile under ``[profiles.profiles]`` and unset ``default``. def remove_all_providers — Clear every key under ``[providers]``. def remove_from_pyproject_yera — Remove ``[tool.yera].`` when it exists. def remove_from_pyproject_yera_overrides — Remove ``[tool.yera.overrides].`` when it exists. def remove_mcp_server — Drop ``[mcp.servers.]`` and every profile's reference to it. def remove_model_from_universe — Remove one model entry from ``[[models.]]`` matching *model_id* and *connection*. def remove_models_for_connection — Remove all model entries across all types for a specific provider connection. def remove_profile — Drop ``[profiles.profiles.]``. def remove_provider — Drop ``[providers.]`` and all its connections. def remove_provider_connection — Drop ``[providers..connections.]``. def replace_models_for_connection — Replace every configured model for one provider connection atomically. def write_mcp_server — Define or replace one named MCP server connection. def write_model_inference — Update inference fields on one existing model. def write_model_to_universe — Append or replace a model entry in ``[[models.]]`` in ``yera.toml``. def write_models_to_universe — Write multiple model entries to yera.toml in a single file operation. def write_profile — Write or replace ``[profiles.profiles.]`` in ``yera.toml``. def write_profile_default — Set ``[profiles] default`` to *profile_name*. def write_provider_connection — Define or replace ``[providers..connections.]`` with *connection_data*. def write_pyproject_yera_cred_group — Set ``[tool.yera.overrides] cred-group`` to *name*; other ``pyproject.toml`` content stays intact. def write_setting_to_yera_toml — Set ``[settings].`` to *value*; leave every other section of ``yera.toml`` as-is. def write_to_pyproject_yera — Set ``[tool.yera].`` to *value*; all other ``pyproject.toml`` content stays intact. def write_to_pyproject_yera_profile — Set ``[tool.yera.profiles] default`` to *profile_name* in ``pyproject.toml``. # delete_yera_toml ``` delete_yera_toml() → None ``` Remove the resolved `yera.toml` path; do nothing if it is already absent. # remove_all_models ``` remove_all_models( model_type: str | None = None, ) → None ``` Remove model entries from `[models]`. When *model_type* is given, clears only that type's array. When omitted, clears all type arrays entirely. Does not write when there is no `models` table or the target is already empty. ## Parameters model_type type: str | None = None If set, remove only models of this type. If `None`, remove all models across all types. # remove_all_profiles ``` remove_all_profiles() → None ``` Clear every profile under `[profiles.profiles]` and unset `default`. Does not write when there is no `profiles` table or it is already empty. # remove_all_providers ``` remove_all_providers() → None ``` Clear every key under `[providers]`. Does not write when there is no `providers` table or it is already empty. # remove_from_pyproject_yera ``` remove_from_pyproject_yera( key: str, ) → None ``` Remove `[tool.yera].` when it exists. Does not write the file when `[tool]` or `[tool.yera]` is absent, or when *key* is not present under `[tool.yera]`, so the manifest is left unchanged. ## Raises PyprojectTomlNotFoundError No writable `pyproject.toml` for this project. # remove_from_pyproject_yera_overrides ``` remove_from_pyproject_yera_overrides( key: str, ) → None ``` Remove `[tool.yera.overrides].` when it exists. Does not write when `[tool]`, `[tool.yera]`, or `[tool.yera.overrides]` is absent, or when *key* is not present. When the overrides table becomes empty after removal, drops the empty `overrides` table from `[tool.yera]`. ## Raises PyprojectTomlNotFoundError No writable `pyproject.toml` for this project. # remove_mcp_server ``` remove_mcp_server( server_name: str, ) → None ``` Drop `[mcp.servers.]` and every profile's reference to it. A profile left with no MCP servers loses its `mcp` key, matching how profiles are written. Does not write when neither is present. ## Parameters server_name type: str Name of the MCP server connection to remove. # remove_model_from_universe ``` remove_model_from_universe( model_type: str, model_id: str, connection: str, ) → None ``` Remove one model entry from `[[models.]]` matching *model_id* and *connection*. Does not write when no matching entry exists. ## Parameters model_type type: str Model type key, e.g. `"llm"`. model_id type: str Yera-internal dot-delimited model id. connection type: str Connection name the model was discovered under. # remove_models_for_connection ``` remove_models_for_connection( provider_type: str, connection_name: str, ) → None ``` Remove all model entries across all types for a specific provider connection. Iterates every model type array in `[models]` and drops entries where both `provider` matches *provider_type* and `connection` matches *connection_name*. Does not write when nothing matches. ## Parameters provider_type type: str Provider type key, e.g. `"aws"`. connection_name type: str Connection name, e.g. `"work"`. # remove_profile ``` remove_profile( profile_name: str, ) → None ``` Drop `[profiles.profiles.]`. Clears `default` too when it pointed at *profile_name*. Does not write when the profile is absent. ## Parameters profile_name type: str Yera profile name to remove. # remove_provider ``` remove_provider( provider_type: str, ) → None ``` Drop `[providers.]` and all its connections. Does not write when the provider is absent. ## Parameters provider_type type: str Provider type key to remove, e.g. `"aws"`. # remove_provider_connection ``` remove_provider_connection( provider_type: str, connection_name: str, ) → None ``` Drop `[providers..connections.]`. Does not write when the provider or connection is absent. ## Parameters provider_type type: str Provider type key, e.g. `"aws"`. connection_name type: str Connection name to remove, e.g. `"work"`. # replace_models_for_connection ``` replace_models_for_connection( provider_type: str, connection_name: str, models: list[BaseModelConfig], ) → None ``` Replace every configured model for one provider connection atomically. Existing models belonging to other providers or connections are preserved. Passing an empty model list removes all models for the target connection. ## Parameters provider_type type: str Provider whose discovered models are being replaced. connection_name type: str Named provider connection whose models are replaced. models type: list[BaseModelConfig] Complete replacement set returned by model discovery. ## Raises ValueError If a replacement model belongs to a different provider or connection. # write_mcp_server ``` write_mcp_server( server_name: str, server_data: dict[str, TomlValue], ) → None ``` Define or replace one named MCP server connection. ## Parameters server_name type: str Name used to reference the server from profiles. server_data type: dict[str, TomlValue] Validated MCP connection configuration. # write_model_inference ``` write_model_inference( model_type: str, model_id: str, connection: str, inference_data: dict[str, TomlValue], ) → None ``` Update inference fields on one existing model. # write_model_to_universe ``` write_model_to_universe( model: BaseModelConfig, ) → None ``` Append or replace a model entry in `[[models.]]` in `yera.toml`. Derives model type from `model.type`. If an entry with the same `id` and `connection` already exists it is replaced in-place; otherwise the entry is appended. ## Parameters model type: BaseModelConfig A validated model config object to write. # write_models_to_universe ``` write_models_to_universe( models: list[BaseModelConfig], ) → None ``` Write multiple model entries to yera.toml in a single file operation. ## Parameters models type: list[BaseModelConfig] List of validated model config objects to write. # write_profile ``` write_profile( profile: Profile, ) → None ``` Write or replace `[profiles.profiles.]` in `yera.toml`. Serialises the full profile — name, optional description, non-empty provider bindings, and non-empty model defaults — into a tomlkit table and assigns it under `[profiles.profiles]`. Creates the `[profiles]` and `[profiles.profiles]` tables if absent. Empty provider and model-default fields are omitted from the written entry. ## Parameters profile type: Profile Validated profile object to persist. The profile's `name` field is used as the table key. # write_profile_default ``` write_profile_default( profile_name: str, ) → None ``` Set `[profiles] default` to *profile_name*. ## Parameters profile_name type: str Yera profile name to set as default. # write_provider_connection ``` write_provider_connection( provider_type: str, connection_name: str, connection_data: dict[str, TomlValue], ) → None ``` Define or replace `[providers..connections.]` with *connection_data*. Creates the `[providers]`, `[providers.]`, and `[providers..connections]` tables if absent. ## Parameters provider_type type: str Provider type key, e.g. `"aws"`. connection_name type: str Connection name, e.g. `"work"`. connection_data type: dict[str, TomlValue] Connection fields to write, e.g. `{"region": "eu-west-1", "credentials": ["access_key_id"]}`. # write_pyproject_yera_cred_group ``` write_pyproject_yera_cred_group( name: str, ) → None ``` Set `[tool.yera.overrides] cred-group` to *name*; other `pyproject.toml` content stays intact. Creates `[tool]`, `[tool.yera]`, and `[tool.yera.overrides]` when missing. *name* is stripped of leading and trailing whitespace before writing. ## Raises PyprojectTomlNotFoundError No writable `pyproject.toml` for this project. TypeError `tool`, `tool.yera`, or `tool.yera.overrides` exists but is not a table. ValueError *name* is empty or whitespace-only after stripping. # write_setting_to_yera_toml ``` write_setting_to_yera_toml( key: str, value: TomlValue, ) → None ``` Set `[settings].` to *value*; leave every other section of `yera.toml` as-is. # write_to_pyproject_yera ``` write_to_pyproject_yera( key: str, value: TomlValue, ) → None ``` Set `[tool.yera].` to *value*; all other `pyproject.toml` content stays intact. Creates `[tool]` / `[tool.yera]` when missing. ## Raises PyprojectTomlNotFoundError No writable `pyproject.toml` for this project. TypeError `tool` or `tool.yera` exists but is not a table (malformed file). # write_to_pyproject_yera_profile ``` write_to_pyproject_yera_profile( profile_name: str, ) → None ``` Set `[tool.yera.profiles] default` to *profile_name* in `pyproject.toml`. Creates `[tool]`, `[tool.yera]`, and `[tool.yera.profiles]` if absent. ## Parameters profile_name type: str Yera profile name to set as the project-level active profile. ## Raises PyprojectTomlNotFoundError No writable `pyproject.toml` for this project. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/ # yera.creds User-level tool credentials store (`credentials.json`). ## Submodules auth backends defaults exceptions file_protection loaders locking paths policy schema store windows_file_protection write --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/auth/ # yera.creds.auth Credential group resolution, authorisation, and TOFU for tool credentials. ## Symbols def canonical_authorised_root_key — Return a normalised path string for comparing authorised roots. def project_root_authorised_in_roots — Return True when *project_root* is authorised (including ``'*'`` wildcard). def require_resolved_credential_group — Return *resolved* or raise if no credential group is configured. def resolve_active_credential_group — Resolve the active credential group name from ``pyproject.toml``. class ResolvedCredentialGroup — Active credential group name from ``[tool.yera.overrides] cred-group``. # canonical_authorised_root_key ``` canonical_authorised_root_key( path: Path | str, ) → str ``` Return a normalised path string for comparing authorised roots. Resolves `.` / `..`, trailing separators, and symlinks so the same directory stored under different spellings matches. # project_root_authorised_in_roots ``` project_root_authorised_in_roots( project_root: Path | None, authorised_roots: list[str], ) → bool ``` Return True when *project_root* is authorised (including `'*'` wildcard). # require_resolved_credential_group ``` require_resolved_credential_group( resolved: ResolvedCredentialGroup | None, ) → ResolvedCredentialGroup ``` Return *resolved* or raise if no credential group is configured. # resolve_active_credential_group ``` resolve_active_credential_group() → ResolvedCredentialGroup | None ``` Resolve the active credential group name from `pyproject.toml`. Reads non-empty `cred-group` under `[tool.yera.overrides]`. Whitespace-only values are treated as absent. When no `pyproject.toml` is found or no value is set → `None`. # ResolvedCredentialGroup Active credential group name from `[tool.yera.overrides] cred-group`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/backends/ # yera.creds.backends Secret-store backend implementations. ## Submodules memory protected_file --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/backends/memory/ # yera.creds.backends.memory In-memory secret-store backend. ## Symbols class InMemorySecretStore — Store opaque secrets in process memory. # InMemorySecretStore Inherits: `SecretStore` Store opaque secrets in process memory. ## Methods get — Return one stored secret. set — Create or replace one secret. compare_and_set — Conditionally create or replace one secret. delete — Delete one secret. exists — Return whether one secret exists. list_info — List non-sensitive information about matching secrets. # InMemorySecretStore.get ``` get( identity: SecretIdentity, ) → SecretValue ``` Return one stored secret. ## Parameters identity type: SecretIdentity Durable identity of the requested secret. ## Returns type: SecretValue The opaque stored value. ## Raises SecretNotFoundError If the secret does not exist. # InMemorySecretStore.set ``` set( identity: SecretIdentity, value: SecretValue, ) → SecretInfo ``` Create or replace one secret. ## Parameters identity type: SecretIdentity Durable identity of the secret. value type: SecretValue Opaque serialized value to store. ## Returns type: SecretInfo Non-sensitive information about the stored secret. # InMemorySecretStore.compare_and_set ``` compare_and_set( identity: SecretIdentity, expected_updated_at: datetime | None, value: SecretValue, ) → SecretInfo ``` Conditionally create or replace one secret. ## Parameters identity type: SecretIdentity Durable identity of the secret. expected_updated_at type: datetime | None Expected update time, or `None` when the secret is expected not to exist. value type: SecretValue Opaque serialized replacement value. ## Returns type: SecretInfo Non-sensitive information about the stored secret. ## Raises SecretConflictError If current state differs from the expectation. # InMemorySecretStore.delete ``` delete( identity: SecretIdentity, ) → None ``` Delete one secret. ## Parameters identity type: SecretIdentity Durable identity of the secret. ## Raises SecretNotFoundError If the secret does not exist. # InMemorySecretStore.exists ``` exists( identity: SecretIdentity, ) → bool ``` Return whether one secret exists. ## Parameters identity type: SecretIdentity Durable identity to test. ## Returns type: bool Whether the secret exists. # InMemorySecretStore.list_info ``` list_info( namespace: str | None = None, owner_id: str | None = None, ) → tuple[SecretInfo, ...] ``` List non-sensitive information about matching secrets. ## Parameters namespace type: str | None = None Optional namespace filter. owner_id type: str | None = None Optional owning identifier filter. ## Returns type: tuple[SecretInfo, ...] Matching secret information in stable identity order. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/backends/protected_file/ # yera.creds.backends.protected_file Protected file secret-store backend. ## Symbols class ProtectedFileSecretStore — Persist opaque secrets in an atomically replaced protected file. # ProtectedFileSecretStore Inherits: `CredentialStoreBackend` Persist opaque secrets in an atomically replaced protected file. ## Methods get — Return one stored secret. set — Create or replace one secret. compare_and_set — Conditionally create or replace one secret. delete — Delete one secret. exists — Return whether one secret exists. list_info — List non-sensitive information about matching secrets. create_credential_group — Create and persist a credential group. list_credential_groups — List credential groups without exposing secret values. get_credential_group — Return one credential group's non-sensitive metadata. rename_credential_group — Rename a credential group while retaining its stable identity. delete_credential_group — Delete a credential group and every secret it owns. authorise_credential_group — Authorize a project root to use a credential group. update_secrets — Apply multiple secret writes and deletions atomically. export_credential_group — Serialize one credential group and all its owned secrets. # ProtectedFileSecretStore.get ``` get( identity: SecretIdentity, ) → SecretValue ``` Return one stored secret. ## Parameters identity type: SecretIdentity Durable identity of the requested secret. ## Returns type: SecretValue The opaque stored value. ## Raises SecretNotFoundError If the secret does not exist. # ProtectedFileSecretStore.set ``` set( identity: SecretIdentity, value: SecretValue, ) → SecretInfo ``` Create or replace one secret. ## Parameters identity type: SecretIdentity Durable identity of the secret. value type: SecretValue Opaque serialized value to store. ## Returns type: SecretInfo Non-sensitive information about the stored secret. # ProtectedFileSecretStore.compare_and_set ``` compare_and_set( identity: SecretIdentity, expected_updated_at: datetime | None, value: SecretValue, ) → SecretInfo ``` Conditionally create or replace one secret. ## Parameters identity type: SecretIdentity Durable identity of the secret. expected_updated_at type: datetime | None Expected update time, or `None` when absent. value type: SecretValue Opaque serialized replacement value. ## Returns type: SecretInfo Non-sensitive information about the stored secret. ## Raises SecretConflictError If current state differs from the expectation. # ProtectedFileSecretStore.delete ``` delete( identity: SecretIdentity, ) → None ``` Delete one secret. ## Parameters identity type: SecretIdentity Durable identity of the secret. ## Raises SecretNotFoundError If the secret does not exist. # ProtectedFileSecretStore.exists ``` exists( identity: SecretIdentity, ) → bool ``` Return whether one secret exists. ## Parameters identity type: SecretIdentity Durable identity to test. ## Returns type: bool Whether the secret exists. # ProtectedFileSecretStore.list_info ``` list_info( namespace: str | None = None, owner_id: str | None = None, ) → tuple[SecretInfo, ...] ``` List non-sensitive information about matching secrets. ## Parameters namespace type: str | None = None Optional namespace filter. owner_id type: str | None = None Optional owning identifier filter. ## Returns type: tuple[SecretInfo, ...] Matching metadata in stable identity order. # ProtectedFileSecretStore.create_credential_group ``` create_credential_group( name: str, authorised_roots: list[str], ) → CredentialGroupInfo ``` Create and persist a credential group. ## Parameters name type: str User-facing credential-group name. authorised_roots type: list[str] Project roots initially authorized for the group. ## Returns type: CredentialGroupInfo Non-sensitive metadata for the created group. ## Raises CredentialGroupAlreadyExistsError If the name is already in use. CredentialGroupNameError If the name is invalid. # ProtectedFileSecretStore.list_credential_groups ``` list_credential_groups() → tuple[CredentialGroupInfo, ...] ``` List credential groups without exposing secret values. ## Returns type: tuple[CredentialGroupInfo, ...] Credential-group metadata ordered by group name. # ProtectedFileSecretStore.get_credential_group ``` get_credential_group( name: str, ) → CredentialGroupInfo ``` Return one credential group's non-sensitive metadata. ## Parameters name type: str User-facing credential-group name. ## Returns type: CredentialGroupInfo Metadata for the requested group. ## Raises CredentialGroupNotFoundError If the group does not exist. # ProtectedFileSecretStore.rename_credential_group ``` rename_credential_group( old_name: str, new_name: str, ) → CredentialGroupInfo ``` Rename a credential group while retaining its stable identity. ## Parameters old_name type: str Existing user-facing group name. new_name type: str Replacement user-facing group name. ## Returns type: CredentialGroupInfo Metadata for the renamed group. ## Raises CredentialGroupNotFoundError If the source group does not exist. CredentialGroupAlreadyExistsError If the target name is already used. CredentialGroupNameError If the target name is invalid. # ProtectedFileSecretStore.delete_credential_group ``` delete_credential_group( name: str, ) → int ``` Delete a credential group and every secret it owns. ## Parameters name type: str User-facing credential-group name. ## Returns type: int Number of associated secrets deleted with the group. ## Raises CredentialGroupNotFoundError If the group does not exist. # ProtectedFileSecretStore.authorise_credential_group ``` authorise_credential_group( name: str, project_root: Path, ) → CredentialGroupInfo ``` Authorize a project root to use a credential group. ## Parameters name type: str User-facing credential-group name. project_root type: Path Project root to authorize. ## Returns type: CredentialGroupInfo Updated non-sensitive credential-group metadata. ## Raises CredentialGroupNotFoundError If the group does not exist. # ProtectedFileSecretStore.update_secrets ``` update_secrets( values: Mapping[SecretIdentity, SecretValue], delete: Collection[SecretIdentity] = (), ) → tuple[SecretInfo, ...] ``` Apply multiple secret writes and deletions atomically. ## Parameters values type: Mapping[SecretIdentity, SecretValue] Secret values to create or replace. delete type: Collection[SecretIdentity] = () Secret identities to remove before applying writes. ## Returns type: tuple[SecretInfo, ...] Metadata for the created or replaced secrets. # ProtectedFileSecretStore.export_credential_group ``` export_credential_group( name: str, ) → bytes ``` Serialize one credential group and all its owned secrets. ## Parameters name type: str User-facing credential-group name. ## Returns type: bytes A portable version-two credential-store document containing only the requested group and its secrets. ## Raises CredentialGroupNotFoundError If the group does not exist. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/defaults/ # yera.creds.defaults Default secret-store construction. ## Symbols def default_secret_store — Construct the default local secret store. # default_secret_store ``` default_secret_store() → CredentialStoreBackend ``` Construct the default local secret store. ## Returns type: CredentialStoreBackend A protected filesystem-backed secret store using the configured credentials path. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/exceptions/ # yera.creds.exceptions Credential exception hierarchy. ## Symbols class CredentialError — Base for all credential-related errors. class CredentialGroupAlreadyExistsError — Target credential group name already exists during rename. class CredentialGroupNameError — A credential group name failed structural validation. class CredentialGroupNotAuthorisedError — This project root is not in ``authorised_roots`` for the requested credential group. class CredentialGroupNotFoundError — A named credential group has no entry in ``credential_groups``. class CredentialGroupNotSpecifiedError — No active credential group is configured for this project. class CredentialInvalidError — A single credential entry failed schema validation. class CredentialKeyError — A credential key failed structural validation. class CredentialStoreCorruptError — The credentials file cannot be parsed (invalid JSON or wrong top-level type). class CredentialVersionError — The credentials file has an unsupported version number. class SecretAccessDeniedError — The caller is not authorized to access the requested secret. class SecretConflictError — A conditional secret mutation conflicts with current stored state. class SecretNotFoundError — A requested secret does not exist. class SecretStoreBusyError — The secret store could not be locked within the allowed time. class SecretStoreCorruptError — The secret store cannot be parsed or validated. class SecretStoreError — Base for failures raised through the secret-store interface. class SecretStoreUnavailableError — The configured secret store cannot be reached or opened. class SecretStoreUnsafeError — The secret store fails its required security checks. # CredentialError Inherits: `YeraError` Subclasses: `CredentialGroupAlreadyExistsError`, `CredentialGroupNameError`, `CredentialGroupNotAuthorisedError`, `CredentialGroupNotFoundError`, `CredentialGroupNotSpecifiedError`, `CredentialInvalidError`, `CredentialKeyError`, `CredentialStoreCorruptError`, `CredentialVersionError`, `SecretStoreError` Base for all credential-related errors. # CredentialGroupAlreadyExistsError Inherits: `CredentialError` Target credential group name already exists during rename. # CredentialGroupNameError Inherits: `CredentialError` A credential group name failed structural validation. # CredentialGroupNotAuthorisedError Inherits: `CredentialError` This project root is not in `authorised_roots` for the requested credential group. # CredentialGroupNotFoundError Inherits: `CredentialError` A named credential group has no entry in `credential_groups`. # CredentialGroupNotSpecifiedError Inherits: `CredentialError` No active credential group is configured for this project. # CredentialInvalidError Inherits: `CredentialError` A single credential entry failed schema validation. # CredentialKeyError Inherits: `CredentialError` A credential key failed structural validation. # CredentialStoreCorruptError Inherits: `CredentialError` The credentials file cannot be parsed (invalid JSON or wrong top-level type). # CredentialVersionError Inherits: `CredentialError` The credentials file has an unsupported version number. # SecretAccessDeniedError Inherits: `SecretStoreError` The caller is not authorized to access the requested secret. # SecretConflictError Inherits: `SecretStoreError` A conditional secret mutation conflicts with current stored state. # SecretNotFoundError Inherits: `SecretStoreError` A requested secret does not exist. # SecretStoreBusyError Inherits: `SecretStoreError` The secret store could not be locked within the allowed time. # SecretStoreCorruptError Inherits: `SecretStoreError` The secret store cannot be parsed or validated. # SecretStoreError Inherits: `CredentialError` Subclasses: `SecretAccessDeniedError`, `SecretConflictError`, `SecretNotFoundError`, `SecretStoreBusyError`, `SecretStoreCorruptError`, `SecretStoreUnavailableError`, `SecretStoreUnsafeError` Base for failures raised through the secret-store interface. # SecretStoreUnavailableError Inherits: `SecretStoreError` The configured secret store cannot be reached or opened. # SecretStoreUnsafeError Inherits: `SecretStoreError` The secret store fails its required security checks. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/file_protection/ # yera.creds.file_protection Protected filesystem operations for credential storage. ## Symbols def ensure_secret_directory — Create or validate a credential directory private to the current user. def read_secret_file — Read bytes from an existing protected secret file. def write_secret_file — Create a protected secret file containing opaque bytes. # ensure_secret_directory ``` ensure_secret_directory( path: Path, ) → None ``` Create or validate a credential directory private to the current user. ## Parameters path type: Path Directory used to contain protected credential files. ## Raises SecretStoreUnsafeError If the path is not a safe private directory. # read_secret_file ``` read_secret_file( path: Path, ) → bytes ``` Read bytes from an existing protected secret file. ## Parameters path type: Path Protected credential-file path. ## Returns type: bytes The stored opaque bytes. ## Raises FileNotFoundError If the secret file does not exist. SecretStoreUnsafeError If its directory or file is unsafe. # write_secret_file ``` write_secret_file( path: Path, content: bytes, ) → None ``` Create a protected secret file containing opaque bytes. ## Parameters path type: Path Destination credential-file path. content type: bytes Serialized credential-store bytes. ## Raises FileExistsError If the destination already exists. SecretStoreUnsafeError If the containing directory is unsafe. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/loaders/ # yera.creds.loaders Credential key validation and transformation helpers. ## Symbols def flatten_json — Recursively flatten *obj* into dotted keys rooted at *prefix*. def is_leaf — Return ``True`` when *key* is a stored credential leaf. def is_namespace — Return ``True`` when leaves exist under *key* (proper prefix). def leaves_under — Return all leaf entries whose key starts with ``path + '.'``. def raise_if_credential_group_key_prefix_conflict — Raise if *credentials* keys contain a leaf-namespace prefix pair. def raise_if_flat_credential_keys_prefix_conflict — Raise if any key is a proper dotted prefix of another (leaf-namespace conflict). def validate_credential_group_name — Validate a credential group name. def validate_credential_key — Validate a credential key as a dotted path. # flatten_json ``` flatten_json( obj: dict[str, Any], prefix: str, ) → dict[str, str] ``` Recursively flatten *obj* into dotted keys rooted at *prefix*. Returns a flat `{dotted_key: str_value}` mapping. ## Raises CredentialKeyError a flattened key fails structural validation, two source entries produce the same flattened key (duplicate collision), or two flattened keys stand in a prefix relationship (leaf-namespace conflict). ``TypeError`` a leaf value is not a string. # is_leaf ``` is_leaf( key: str, creds: dict[str, dict[str, Any]], ) → bool ``` Return `True` when *key* is a stored credential leaf. # is_namespace ``` is_namespace( key: str, creds: dict[str, dict[str, Any]], ) → bool ``` Return `True` when leaves exist under *key* (proper prefix). # leaves_under ``` leaves_under( path: str, creds: dict[str, dict[str, Any]], ) → dict[str, dict[str, Any]] ``` Return all leaf entries whose key starts with `path + '.'`. # raise_if_credential_group_key_prefix_conflict ``` raise_if_credential_group_key_prefix_conflict( credentials: dict[str, Any], group_name: str, credentials_file: Path, ) → None ``` Raise if *credentials* keys contain a leaf-namespace prefix pair. ## Raises CredentialKeyError includes *group_name* and *credentials_file* in the message. # raise_if_flat_credential_keys_prefix_conflict ``` raise_if_flat_credential_keys_prefix_conflict( keys: Iterable[str], prefix_message: str, ) → None ``` Raise if any key is a proper dotted prefix of another (leaf-namespace conflict). *keys* are dotted credential paths. After sorting, only adjacent pairs need checking: if `K` immediately precedes `K.` lexicographically among sorted keys, every prefix relationship appears as some adjacent pair. ## Raises CredentialKeyError two keys stand in prefix relationship. # validate_credential_group_name ``` validate_credential_group_name( name: str, ) → None ``` Validate a credential group name. A valid credential group name: - Is non-empty and not whitespace-only. - Contains no dots (`.`). - Contains no control characters (U+0000-U+001F). ## Raises CredentialGroupNameError the name fails any structural rule. # validate_credential_key ``` validate_credential_key( key: str, ) → None ``` Validate a credential key as a dotted path. A valid key: - Is non-empty. - When split on `"."`, produces only non-empty segments (no leading dot, trailing dot, or consecutive dots). - Contains no control characters (U+0000-U+001F) in any segment. ## Raises CredentialKeyError the key fails any structural rule. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/locking/ # yera.creds.locking Cross-process locking for protected credential stores. ## Symbols class SecretStoreLock — Coordinate access to one credential store across processes. # SecretStoreLock Coordinate access to one credential store across processes. ## Methods __enter__ — Acquire the store lock. __exit__ — Release the store lock. # SecretStoreLock.__enter__ ``` __enter__() → Self ``` Acquire the store lock. ## Returns type: Self The acquired lock. ## Raises SecretStoreBusyError If the lock cannot be acquired in time. SecretStoreUnsafeError If the lock path is unsafe. # SecretStoreLock.__exit__ ``` __exit__( exception_type: type[BaseException] | None, exception: BaseException | None, traceback: TracebackType | None, ) → None ``` Release the store lock. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/paths/ # yera.creds.paths Resolution of the `credentials.json` filesystem path. ## Symbols def credentials_path — Return the path to the tool credentials JSON file. # credentials_path ``` credentials_path() → Path ``` Return the path to the tool credentials JSON file. If `YERA_CREDENTIALS_PATH` is set, that path is used (it takes precedence over `YERA_HOME`). Otherwise the path is `yera_home_dir() / "credentials.json"`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/policy/ # yera.creds.policy Policy operations for controlled secret access. ## Symbols def require_authorized_credential_group — Return a group's stable owner ID after project authorization. def resolve_authorized_tool_secrets — Authorize a project and resolve its declared ordinary credentials. def resolve_tool_secrets — Resolve declared ordinary credentials for one authorized tool group. # require_authorized_credential_group ``` require_authorized_credential_group( groups: Mapping[str, CredentialGroupRecord], group_name: str, project_root: Path, ) → str ``` Return a group's stable owner ID after project authorization. ## Parameters groups type: Mapping[str, CredentialGroupRecord] Credential groups keyed by mutable display name. group_name type: str Configured credential-group name. project_root type: Path Project requesting access. ## Returns type: str Stable owner ID used to resolve the group's ordinary secrets. ## Raises CredentialGroupNotFoundError If the named group does not exist. SecretAccessDeniedError If the project is not authorized. # resolve_authorized_tool_secrets ``` resolve_authorized_tool_secrets( store: SecretStore, groups: Mapping[str, CredentialGroupRecord], group_name: str, project_root: Path, names: list[str], ) → dict[str, SecretValue] ``` Authorize a project and resolve its declared ordinary credentials. ## Parameters store type: SecretStore Secret backend containing opaque values. groups type: Mapping[str, CredentialGroupRecord] Credential groups keyed by mutable display name. group_name type: str Configured credential-group name. project_root type: Path Project requesting access. names type: list[str] Exact names or explicit `.*` namespaces declared by the tool. ## Returns type: dict[str, SecretValue] Requested ordinary credential values keyed by name. ## Raises CredentialGroupNotFoundError If the named group does not exist. SecretAccessDeniedError If the project is not authorized. SecretNotFoundError If a declared credential is absent. # resolve_tool_secrets ``` resolve_tool_secrets( store: SecretStore, owner_id: str, names: list[str], ) → dict[str, SecretValue] ``` Resolve declared ordinary credentials for one authorized tool group. ## Parameters store type: SecretStore Secret backend containing opaque values. owner_id type: str Stable identity of the authorized credential group. names type: list[str] Exact credential names declared by the tool. ## Returns type: dict[str, SecretValue] Requested values keyed by their declared names. ## Raises SecretNotFoundError If any declared ordinary credential is absent. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/schema/ # yera.creds.schema Pydantic schemas for the credential store. ## Symbols class CredentialGroupRecord — Persisted metadata for one named credential group. class SecretRecord — Persisted opaque value and metadata for one secret. class SecretStoreDocument — Version-two protected credential-store document. # CredentialGroupRecord Inherits: `BaseModel` Persisted metadata for one named credential group. ## Attributes id type: str Stable owner identity retained when the group is renamed. authorised_roots type: list[str] Project roots authorized to use the group. # SecretRecord Inherits: `BaseModel` Persisted opaque value and metadata for one secret. ## Attributes identity type: SecretIdentity Durable identity of the secret. value type: bytes Opaque serialized secret bytes. created_at type: AwareDatetime Time at which the secret was first stored. updated_at type: AwareDatetime Time at which the secret was last replaced. # SecretStoreDocument Inherits: `BaseModel` Version-two protected credential-store document. ## Attributes version type: Literal[2] Exact document-format version. credential_groups type: dict[str, CredentialGroupRecord] Named groups containing only safe metadata. secrets type: list[SecretRecord] Individually identified opaque secret records. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/store/ # yera.creds.store Secret storage contracts and durable identities. ## Symbols class CredentialGroupInfo — Non-sensitive information about one credential group. class CredentialStoreBackend — Storage boundary for credential groups and their opaque secrets. class SecretIdentity — Durable identity of one stored secret. class SecretInfo — Non-sensitive information about one stored secret. class SecretStore — Storage boundary for individual opaque secrets. class SecretStoreCapabilities — Security and lifecycle capabilities exposed by a secret backend. class SecretValue — Opaque serialized secret value. # CredentialGroupInfo Non-sensitive information about one credential group. ## Attributes name type: str Mutable user-facing group name. id type: str Stable owner identity retained when the group is renamed. authorised_roots type: tuple[str, ...] Project roots authorized to use the group. # CredentialStoreBackend Inherits: `SecretStore` Subclasses: `ProtectedFileSecretStore` Storage boundary for credential groups and their opaque secrets. ## Methods create_credential_group — Create and persist a credential group. get_credential_group — Return one credential group's metadata. list_credential_groups — List credential groups without exposing secret values. rename_credential_group — Rename a credential group without changing its stable identity. delete_credential_group — Delete a credential group and its owned secrets. authorise_credential_group — Authorize a project root to use a credential group. update_secrets — Apply multiple secret writes and deletions atomically. export_credential_group — Serialize one credential group and all its owned secrets. # CredentialStoreBackend.create_credential_group ``` create_credential_group( name: str, authorised_roots: list[str], ) → CredentialGroupInfo ``` Create and persist a credential group. ## Parameters name type: str User-facing credential-group name. authorised_roots type: list[str] Project roots initially authorized for the group. ## Returns type: CredentialGroupInfo Non-sensitive metadata for the created group. # CredentialStoreBackend.get_credential_group ``` get_credential_group( name: str, ) → CredentialGroupInfo ``` Return one credential group's metadata. ## Parameters name type: str User-facing credential-group name. ## Returns type: CredentialGroupInfo Non-sensitive metadata for the requested group. # CredentialStoreBackend.list_credential_groups ``` list_credential_groups() → tuple[CredentialGroupInfo, ...] ``` List credential groups without exposing secret values. ## Returns type: tuple[CredentialGroupInfo, ...] Credential-group metadata ordered by name. # CredentialStoreBackend.rename_credential_group ``` rename_credential_group( old_name: str, new_name: str, ) → CredentialGroupInfo ``` Rename a credential group without changing its stable identity. ## Parameters old_name type: str Existing user-facing group name. new_name type: str Replacement user-facing group name. ## Returns type: CredentialGroupInfo Metadata for the renamed group. # CredentialStoreBackend.delete_credential_group ``` delete_credential_group( name: str, ) → int ``` Delete a credential group and its owned secrets. ## Parameters name type: str User-facing credential-group name. ## Returns type: int Number of associated secrets deleted. # CredentialStoreBackend.authorise_credential_group ``` authorise_credential_group( name: str, project_root: Path, ) → CredentialGroupInfo ``` Authorize a project root to use a credential group. ## Parameters name type: str User-facing credential-group name. project_root type: Path Project root to authorize. ## Returns type: CredentialGroupInfo Updated non-sensitive group metadata. # CredentialStoreBackend.update_secrets ``` update_secrets( values: Mapping[SecretIdentity, SecretValue], delete: Collection[SecretIdentity] = (), ) → tuple[SecretInfo, ...] ``` Apply multiple secret writes and deletions atomically. ## Parameters values type: Mapping[SecretIdentity, SecretValue] Secret values to create or replace. delete type: Collection[SecretIdentity] = () Secret identities to remove before applying writes. ## Returns type: tuple[SecretInfo, ...] Metadata for the created or replaced secrets. # CredentialStoreBackend.export_credential_group ``` export_credential_group( name: str, ) → bytes ``` Serialize one credential group and all its owned secrets. ## Parameters name type: str User-facing credential-group name. ## Returns type: bytes A portable version-two credential-store document containing only the requested group and its secrets. # SecretIdentity Durable identity of one stored secret. ## Attributes namespace type: str Secret category kept separate from other consumers. owner_id type: str Stable identifier of the owning group or connection. name type: str Secret name within the owner. account_id type: str | None Optional stable account identity. # SecretInfo Non-sensitive information about one stored secret. ## Attributes identity type: SecretIdentity Durable identity of the stored secret. created_at type: datetime Time at which the secret was first stored. updated_at type: datetime Time at which the secret was last replaced. # SecretStore Inherits: `ABC` Subclasses: `CredentialStoreBackend`, `InMemorySecretStore` Storage boundary for individual opaque secrets. ## Methods get — Return one secret value. set — Create or replace one secret. compare_and_set — Replace one secret when its current state matches expectations. delete — Delete one secret. exists — Return whether one secret exists. list_info — List non-sensitive information about matching secrets. # SecretStore.get ``` get( identity: SecretIdentity, ) → SecretValue ``` Return one secret value. ## Parameters identity type: SecretIdentity Durable identity of the requested secret. ## Returns type: SecretValue The opaque serialized secret value. # SecretStore.set ``` set( identity: SecretIdentity, value: SecretValue, ) → SecretInfo ``` Create or replace one secret. ## Parameters identity type: SecretIdentity Durable identity of the secret. value type: SecretValue Opaque serialized value to store. ## Returns type: SecretInfo Non-sensitive information about the stored secret. # SecretStore.compare_and_set ``` compare_and_set( identity: SecretIdentity, expected_updated_at: datetime | None, value: SecretValue, ) → SecretInfo ``` Replace one secret when its current state matches expectations. ## Parameters identity type: SecretIdentity Durable identity of the secret. expected_updated_at type: datetime | None Expected update time, or `None` when the secret is expected not to exist. value type: SecretValue Opaque serialized replacement value. ## Returns type: SecretInfo Non-sensitive information about the stored secret. # SecretStore.delete ``` delete( identity: SecretIdentity, ) → None ``` Delete one secret. ## Parameters identity type: SecretIdentity Durable identity of the secret to delete. # SecretStore.exists ``` exists( identity: SecretIdentity, ) → bool ``` Return whether one secret exists. ## Parameters identity type: SecretIdentity Durable identity to test. ## Returns type: bool Whether the secret exists. # SecretStore.list_info ``` list_info( namespace: str | None = None, owner_id: str | None = None, ) → tuple[SecretInfo, ...] ``` List non-sensitive information about matching secrets. ## Parameters namespace type: str | None = None Optional namespace filter. owner_id type: str | None = None Optional owning identifier filter. ## Returns type: tuple[SecretInfo, ...] Matching secret information without values. # SecretStoreCapabilities Security and lifecycle capabilities exposed by a secret backend. ## Attributes protected_at_rest type: bool Whether the backend restricts stored data from unrelated local users. encrypted_at_rest type: bool Whether secret values are encrypted while persisted. requires_unlock type: bool Whether the backend requires an unlock operation. supports_atomic_update type: bool Whether mutations replace values atomically. # SecretValue Opaque serialized secret value. ## Methods __repr__ — Return a redacted developer representation. __str__ — Return a redacted user-facing representation. # SecretValue.__repr__ ``` __repr__() → str ``` Return a redacted developer representation. # SecretValue.__str__ ``` __str__() → str ``` Return a redacted user-facing representation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/windows_file_protection/ # yera.creds.windows_file_protection Windows ACL protection for credential-store paths. ## Symbols def protect_windows_path — Apply a protected ACL to a credential-store path. def windows_path_is_private — Return whether a path has Yera's protected Windows ACL. def windows_path_is_reparse_point — Return whether a path is backed by a Windows reparse point. # protect_windows_path ``` protect_windows_path( path: Path, ) → None ``` Apply a protected ACL to a credential-store path. ## Parameters path type: Path Existing file or directory to protect. ## Raises SecretStoreUnavailableError If Windows ACL support is unavailable. # windows_path_is_private ``` windows_path_is_private( path: Path, ) → bool ``` Return whether a path has Yera's protected Windows ACL. ## Parameters path type: Path Existing file or directory to inspect. ## Returns type: bool Whether the owner and every allowed trustee are trusted. ## Raises SecretStoreUnavailableError If Windows ACL support is unavailable. # windows_path_is_reparse_point ``` windows_path_is_reparse_point( path: Path, ) → bool ``` Return whether a path is backed by a Windows reparse point. ## Parameters path type: Path Existing filesystem path to inspect. ## Returns type: bool Whether Windows marks the path as a reparse point. --- Source: https://yera-labs.io/docs/yera/reference/implementation/creds/write/ # yera.creds.write Atomic filesystem-writing utilities. --- Source: https://yera-labs.io/docs/yera/reference/implementation/dsl/ # yera.dsl The DSL surface for writing Yera apps. Three concerns, three modules: - `functions` — prompting, input widgets, output blocks, layout, and lifecycle helpers. The building blocks an app function calls into directly. - `struct` — base class for structured-generation specs. Subclass `Struct` to declare the shape of a value the LLM should produce. - `workspace` — an app's memory: chat history and programmatic state shared across the app's model contexts. ## Submodules control forms functions struct tree workspace --- Source: https://yera-labs.io/docs/yera/reference/implementation/dsl/control/ # yera.dsl.control Module containing Yera DSL constructs for control flow using LLMs. ## Symbols class Condition — Represents a boolean condition with instruction. def condition — Use the active LLM to evaluate a boolean condition. class Option — Represents a single option in a selection. def option — Create an Option instance. def select — Use the active LLM to choose between a set of options. # Condition Inherits: `Struct` Represents a boolean condition with instruction. ## Attributes condition type: bool Boolean indicating whether the condition holds. # condition ``` condition( instruction: str, on_wire: bool = False, **kwargs, ) → bool ``` Use the active LLM to evaluate a boolean condition. ## Parameters instruction type: str Instruction text describing what the condition checks. on_wire type: bool = False Whether the field should be included in LLM context (default: False). **kwargs type: object Additional keyword arguments passed to the model fill method. ## Returns type: bool Boolean value representing whether the condition holds. # Option Represents a single option in a selection. ## Attributes label type: str The label shown for the option. description type: str | None Optional detailed description of the option. # option ``` option( label: str, description: str | None = None, ) → Option ``` Create an Option instance. ## Parameters label type: str The visible label for the option. description type: str | None = None Optional descriptive text. ## Returns type: Option An Option instance with given label and description. # select ``` select( *options, instruction: str | None = None, name: str = 'Selection', on_wire: bool = False, **kwargs, ) → str ``` Use the active LLM to choose between a set of options. ## Parameters *options type: str | Option = () One or more option labels or Option instances. instruction type: str | None = None Instruction text to describe the purpose of this selection. name type: str = 'Selection' Name for the generated class (default: "Selection"). on_wire type: bool = False Whether the field should be included in the LLM context (default: False). **kwargs type: object Additional keyword arguments passed to the model fill method. ## Returns type: str The selected option ## Raises ValueError If fewer than two options are provided or labels are not unique. --- Source: https://yera-labs.io/docs/yera/reference/implementation/dsl/forms/ # yera.dsl.forms Present structs as forms and collect validated submissions. ## Symbols def present_form — Collect a validated instance of a model through a form. # present_form ``` present_form( model_type: type[ModelT], label: str | None = None, ) → ModelT ``` Collect a validated instance of a model through a form. Rejected submissions are echoed with their errors and the form is presented again, pre-filled with the submitted values and secrets masked, until a submission validates. ## Parameters model_type type: type[ModelT] Model or struct class whose fields the form presents. label type: str | None = None Optional question shown above the form. ## Returns type: ModelT The validated instance built from the accepted submission. --- Source: https://yera-labs.io/docs/yera/reference/implementation/dsl/functions/ # yera.dsl.functions Prompting, input, output, layout, and lifecycle functions. The building blocks an app function uses to interact with the LLM, present output, and collect input from the user. **Prompting** - `chat`: send a prompt and get a text response - `sys_prompt`: append a line to the active system prompt **Input widgets** - `text_input`: free-form text - `buttons`: pick one of a set of options - `date_picker`: pick a date - `slider`: pick a number in a range - `tree_selector`: select leaves from a nested tree **Output blocks** - `markdown`: render markdown content - `table`: render tabular data - `spinner`: show a spinner while work runs - `result` - `image`: render image-file bytes **Layout** - `section` — group related output blocks **Lifecycle** - `session_title`: set the title associated with the current session - `exit`: end the app run - `quit`: end the app run as a user-initiated quit ## Symbols def bar_chart — Render a bar chart. def buttons — Present the user with a set of buttons and return their selection. def chat — Yield user prompts until one starts with ``stop_str``. def confirm — Present the user with a binary choice and return True/False. def date_picker — Present the user with a date picker. def exit — End the current app run. def gen — Generate a response from the active LLM with optional instruction and visibility control. def image — Render an image from image-file bytes. def insert — Insert a prompt into the active LLM context. def line_chart — Render a line chart. def markdown — Render a markdown block. def quit — End the current app run as a user-initiated quit. def response — Send a prompt to the active LLM and return its text response. def section — Group output blocks into a mutable, collapsible section. def session_title — Set the title associated with the current session. def slider — Present the user with a slider over a numeric range. def spinner — Show a configurable spinner while a block of work runs. def sys_prompt — Append a line to the active LLM context's system prompt. def table — Render a table. def text_input — Prompt the user for free-form text input. def tree_selector — Present a nested tree and return the selected leaf values. # bar_chart ``` bar_chart( data: object, x: str | None = None, y: str | Sequence[str] | None = None, colour: str | Sequence[str] | None = None, horizontal: bool = False, stack: bool = True, ) → None ``` Render a bar chart. ## Parameters data type: object Chart data; typically a pandas DataFrame. x type: str | None = None Column name to use for the x-axis. y type: str | Sequence[str] | None = None Column name (or names) to plot on the y-axis. colour type: str | Sequence[str] | None = None Column name (or names) used to colour the bars. horizontal type: bool = False Orient bars horizontally rather than vertically. stack type: bool = True Stack multiple series rather than grouping side-by-side. ## Examples ```python import pandas as pd df = pd.DataFrame({"quarter": ["Q1", "Q2", "Q3", "Q4"], "revenue": [120, 145, 98, 167]}) bar_chart(df, x="quarter", y="revenue") ``` Grouped by colour: ```python df = pd.DataFrame({ "quarter": ["Q1", "Q2", "Q1", "Q2"], "revenue": [120, 145, 98, 167], "region": ["North", "North", "South", "South"], }) bar_chart(df, x="quarter", y="revenue", colour="region", stack=False) ``` # buttons ``` buttons( options: list[str], label: str | None = None, ) → str ``` Present the user with a set of buttons and return their selection. ## Parameters options type: list[str] Labels for the buttons to display. label type: str | None = None Optional prompt shown above the buttons. ## Returns type: str The label of the button the user clicked. # chat ``` chat( stop_str: str = '/quit', ) → Generator[str] ``` Yield user prompts until one starts with `stop_str`. Repeatedly prompts the user for text input, yielding each prompt. When the user submits a prompt starting with `stop_str`, the run quits and iteration stops. ## Parameters stop_str type: str = '/quit' Prefix that, when matched, ends the chat loop. Default = "/quit" # confirm ``` confirm( label: str | None = None, true_option: str = 'Yes', false_option: str = 'No', ) → bool ``` Present the user with a binary choice and return True/False. ## Parameters label type: str | None = None optional prompt shown above the buttons. true_option type: str = 'Yes' the button option representing true. false_option type: str = 'No' the button option representing false. ## Returns type: bool boolean value representing whether the user chose the true or false option. # date_picker ``` date_picker( label: str, default_date: date | str | None = None, ) → date ``` Present the user with a date picker. ## Parameters label type: str Prompt shown alongside the picker. default_date type: date | str | None = None Optional initial date, as a `date` or ISO-format string. ## Returns type: date The date the user chose. # exit ``` exit( exit_code: int, reason: str, return_value: object, error_cause: ErrorCause | None = None, ) → None ``` End the current app run. ## Parameters exit_code type: int Process-style exit code; `0` for success, non-zero for failure. reason type: str Human-readable summary of why the run ended. return_value type: object Value to return to the caller, or `None`. error_cause type: ErrorCause | None = None Optional structured cause metadata for failure exits. See `ErrorCause`. # gen ``` gen( on_wire: bool = True, instruction: str | None = None, **kwargs, ) → str ``` Generate a response from the active LLM with optional instruction and visibility control. ## Parameters on_wire type: bool = True Whether to include the response back in the LLM context. instruction type: str | None = None Optional system instruction to guide generation (e.g., for structured outputs). **kwargs type: object Additional keyword arguments passed directly to the underlying LLM (e.g., `temperature`, `max_tokens`, etc.). ## Returns type: str The generated text response from the LLM. # image ``` image( content: bytes, media_type: ImageMediaType = 'image/png', alt: str | None = None, ) → None ``` Render an image from image-file bytes. The image is fitted responsively to the available display width while preserving its intrinsic aspect ratio. PNG, JPEG, WebP, GIF, and SVG images are supported. Rendering depends on the active output environment. ## Parameters content type: bytes Raw contents of a PNG, JPEG, WebP, GIF, or SVG image file. media_type type: ImageMediaType = 'image/png' MIME type identifying the supplied image format. alt type: str | None = None Optional accessible description of the image. # insert ``` insert( prompt: str, ) → None ``` Insert a prompt into the active LLM context. Unlike `response`, this does **not** generate a response; it merely appends the given prompt to the conversation history. ## Parameters prompt type: str The user message to insert into the LLM context. # line_chart ``` line_chart( data: object, x: str | None = None, y: str | Sequence[str] | None = None, colour: str | Sequence[str] | None = None, ) → None ``` Render a line chart. ## Parameters data type: object Chart data; typically a pandas DataFrame. x type: str | None = None Column name to use for the x-axis. y type: str | Sequence[str] | None = None Column name (or names) to plot on the y-axis. colour type: str | Sequence[str] | None = None Column name (or names) used to colour the lines. ## Examples ```python import pandas as pd df = pd.DataFrame({"time": [1, 2, 3], "value": [4, 5, 6]}) line_chart(df, x="time", y="value") ``` # markdown ``` markdown( content: str, ) → None ``` Render a markdown block. Can be called directly to emit a single block, or used as a stream handle to append further chunks over time. ## Parameters content type: str the markdown content to display # quit ``` quit() → None ``` End the current app run as a user-initiated quit. Distinct from `exit`: signals that the user chose to stop rather than the app completing or failing. # response ``` response( prompt: str, **kwargs, ) → str ``` Send a prompt to the active LLM and return its text response. Tokens will simultaneously be pushed onto the event stream for display in your UI or printed to stdout. ## Parameters prompt type: str The user-message prompt to send. **kwargs type: str | int | float | bool Additional options forwarded to the underlying LLM (e.g. provider-specific generation parameters). ## Returns type: str The LLM's text response. # section ``` section( title: str, summary: str | None = None, auto_collapse: bool = True, glyph: str = 'thread', colour: NamedColour | None = None, ) → Section ``` Group output blocks into a mutable, collapsible section. Sections may contain ordinary output blocks or nested sections. While the context is open, its title, glyph, and colour may be changed through the returned section object. The `success()` and `error()` methods apply standard completion appearances without closing the section. In the web UI, the section may collapse automatically when its context exits. ## Parameters title type: str Heading shown in the section header. summary type: str | None = None Optional summary shown for the completed section. auto_collapse type: bool = True Whether the section collapses when it completes. glyph type: str = 'thread' Name of the glyph shown in the section header. colour type: NamedColour | None = None Optional named colour applied to the section heading. ## Returns type: Section A `Section` context manager. ## Examples ```python with section("Loading data", glyph="spinner") as current: load_data() current.success("Data loaded") ``` # session_title ``` session_title( title: str, ) → None ``` Set the title associated with the current session. Session-aware hosts may persist and display the title. In runtimes without sessions, the emitted metadata update has no persistent effect. ## Parameters title type: str Title to associate with the current session. # slider ``` slider( min_value: float, max_value: float, label: str, default_value: float | None = None, ) → float ``` Present the user with a slider over a numeric range. ## Parameters min_value type: float Lower bound of the slider. max_value type: float Upper bound of the slider. label type: str Prompt shown alongside the slider. default_value type: float | None = None Optional initial position. Defaults to `min_value` if not provided. ## Raises InputValueError If the submitted value is outside the slider range. ## Returns type: float The value the user selected. # spinner ``` spinner( message: str = 'Working', glyph: str = 'run', colour: NamedColour = 'orange', end_message: str = 'Done', end_glyph: str = 'check', end_colour: NamedColour = 'green', ) → SpinnerStream ``` Show a configurable spinner while a block of work runs. The spinner may change its message, glyph, and colour while active. On successful exit it resolves to the configured completion appearance; on exceptional exit it uses the fixed failure appearance. ## Parameters message type: str = 'Working' Initial message shown alongside the spinner. glyph type: str = 'run' Initial registered glyph name. colour type: NamedColour = 'orange' Initial named colour. end_message type: str = 'Done' Message shown after successful completion. end_glyph type: str = 'check' Registered glyph shown after successful completion. end_colour type: NamedColour = 'green' Named colour shown after successful completion. ## Returns type: SpinnerStream A `SpinnerStream` context manager. # sys_prompt ``` sys_prompt( prompt: str, ) → None ``` Append a line to the active LLM context's system prompt. ## Parameters prompt type: str Text to add to the system prompt for subsequent `chat` and `struct` calls in the current LLM context. # table ``` table( data: object = None, border: bool | Literal['horizontal'] = True, ) → TableStream ``` Render a table. ## Parameters data type: object = None Table data. Accepts pandas DataFrames, dicts of column lists, lists of dicts, lists of lists, or any iterable that can be converted to rows. Pass `None` for an empty table. border type: bool | Literal['horizontal'] = True `True` for full borders, `False` for none, or `"horizontal"` for horizontal lines only. ## Returns type: TableStream A `TableStream` handle whose `add_rows` method appends rows to the same table. # text_input ``` text_input( message: str | None = None, ) → str ``` Prompt the user for free-form text input. ## Parameters message type: str | None = None Optional label shown alongside the input field. ## Returns type: str The text the user submitted. # tree_selector ``` tree_selector( tree: TreeSelectorSource, label: str | None = None, min_selections: int = 1, max_selections: int | None = None, ) → list[str] ``` Present a nested tree and return the selected leaf values. ## Parameters tree type: TreeSelectorSource Nested option mapping or an object implementing `__yera_tree__()`. label type: str | None = None Optional prompt shown above the tree. min_selections type: int = 1 Minimum number of leaves that must be selected. max_selections type: int | None = None Optional maximum number of leaves that may be selected. ## Raises TypeError If the source cannot provide a valid tree mapping. ValueError If the supplied tree is malformed. InputValueError If the submitted selection violates its cardinality, contains duplicates, or includes a value outside the requested tree. ## Returns type: list[str] The canonical values of the selected leaves, in submitted order. ## Submodules input_echo --- Source: https://yera-labs.io/docs/yera/reference/implementation/dsl/struct/ # yera.dsl.struct The base class for structured-generation specs. Subclass `Struct` to define the shape of a value you want the LLM to produce, then call `Struct.fill` to generate an instance from a prompt. ## Symbols class Struct — Base class for structured-generation specs. # Struct Inherits: `BaseModel` Subclasses: `Condition` Base class for structured-generation specs. Subclass `Struct` to declare the shape of a value the LLM should produce, then call `fill` on the subclass to generate a populated instance from a prompt. Unknown fields are rejected at construction time: structs are intended to be fixed in structure, separating *data* (the struct) from *behaviour* (defined elsewhere). Passing fields not declared on the subclass raises a `ValidationError`. ## Examples ```python class Person(Struct): name: str age: int occupation: str bio = "Dr. John Smith is a 36-year-old data scientist." Person.fill(bio) ``` ``` Person(name='John Smith', age=36, occupation='data scientist') ``` ## Methods __init_subclass__ — Initialise subclass with an expects result field populated. expects_result — Return whether this struct expects an LLM result. get_tool_name — Return the tool name (class name) used when calling the LLM. get_call_id — Return the stored tool call ID, or raise if unset. set_call_id — Set the tool call ID for this struct instance. fill — Generate an instance of this struct from a prompt. form — Ask the user to fill in this struct as a form. __hash__ — Hash by field values, recursively freezing containers. model_json_schema — Return the JSON schema for this struct with extra strictness applied. # Struct.__init_subclass__ ``` __init_subclass__( expects_result: bool = False, **kwargs, ) → None ``` Initialise subclass with an expects result field populated. # Struct.expects_result ``` expects_result() → bool ``` Return whether this struct expects an LLM result. # Struct.get_tool_name ``` get_tool_name() → str ``` Return the tool name (class name) used when calling the LLM. # Struct.get_call_id ``` get_call_id() → str ``` Return the stored tool call ID, or raise if unset. ## Returns type: str The call ID string assigned via `set_call_id`. ## Raises ValueError If no call ID has been set (`__call_id__` is None). # Struct.set_call_id ``` set_call_id( call_id: str, ) → None ``` Set the tool call ID for this struct instance. ## Parameters call_id type: str String identifier assigned by the LLM tool-calling API. # Struct.fill ``` fill( instruction: str | None = None, on_wire: bool = False, **kwargs, ) → Self ``` Generate an instance of this struct from a prompt. Sends the prompt to the active LLM and parses its response into an instance of the calling subclass. ## Parameters instruction type: str | None = None extra prompt instruction to inform struct generation. on_wire type: bool = False whether the llm text output from this fill is included back in the context. **kwargs type: str | int | float | bool Additional options forwarded to the underlying LLM (e.g. provider-specific generation parameters). ## Returns type: Self An instance of the calling subclass, populated from the LLM's response. # Struct.form ``` form( label: str | None = None, ) → Self ``` Ask the user to fill in this struct as a form. Each field is presented with a widget suited to its type. Submissions that fail validation are shown again with their errors until one is valid. ## Parameters label type: str | None = None Optional question shown above the form. ## Returns type: Self An instance of the calling subclass built from the accepted submission. ## Examples ```python class Deploy(Struct): service: str replicas: int = 1 Deploy.form("Deploy which service?") ``` # Struct.__hash__ ``` __hash__() → int ``` Hash by field values, recursively freezing containers. Allows `Struct` instances to be used as members in hashable containers and as `dict` keys. Mutating fields after hashing will make the instance unfindable in the collection; treat hashed structs as immutable. # Struct.model_json_schema ``` model_json_schema( by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, schema_generator: type[GenerateJsonSchema] = _StrictSchema, mode: JsonSchemaMode = 'validation', union_format: Literal['any_of', 'primitive_type_array'] = 'any_of', ) → dict ``` Return the JSON schema for this struct with extra strictness applied. Overridden to ensure all nested objects have `additionalProperties: false`. ## Returns type: dict A JSON schema dict with `additionalProperties: false` for all objects. --- Source: https://yera-labs.io/docs/yera/reference/implementation/dsl/tree/ # yera.dsl.tree Public tree-source types used by the tree selector DSL. ## Symbols class SupportsTreeSelector — An object that can provide options for a tree selector. # SupportsTreeSelector Inherits: `Protocol` An object that can provide options for a tree selector. ## Methods __yera_tree__ — Return a tree-selector-compatible nested mapping. # SupportsTreeSelector.__yera_tree__ ``` __yera_tree__() → TreeSelectorMapping ``` Return a tree-selector-compatible nested mapping. --- Source: https://yera-labs.io/docs/yera/reference/implementation/dsl/workspace/ # yera.dsl.workspace An app's memory: chat history and programmatic state. ## Symbols class Workspace — An app's memory: chat history and programmatic state. # Workspace An app's memory: chat history and programmatic state. ``` Each app has a single workspace, shared across any nested model contexts the app contains. The workspace holds both the LLM's conversation history — what [`chat`](/docs/yera/reference/api/chat/) and [`Struct.fill`](/docs/yera/reference/api/struct/#fill) see and append to — and a dict-style variable store the app's Python code can read and write. The variable store is for Python-side state the app threads through its own logic. The LLM does not see these variables by default; future versions will allow apps to opt into reading workspace variables as part of their context. Sub-apps do not share their parent's workspace by default. The module-level ``workspace`` singleton is the entry point; apps do not construct ``Workspace`` instances directly. ``` Example: ```python workspace["customer_name"] = "Alice" ... name = workspace["customer_name"] ``` ## Methods get — Get a value from workspace, returning default if key doesn't exist. set — Set a value in workspace. __getitem__ — Get a value from workspace, raising KeyError if key doesn't exist. __setitem__ — Set a value in workspace. __contains__ — Check if a key exists in workspace. get_messages — Get the messages in the workspace. # Workspace.get ``` get( key: str, default: object = None, ) → object ``` Get a value from workspace, returning default if key doesn't exist. ## Parameters key type: str The workspace key to retrieve default type: object = None Value to return if key doesn't exist (default: None) ## Returns type: object The value associated with key, or default if key doesn't exist # Workspace.set ``` set( key: str, value: object, ) → None ``` Set a value in workspace. ## Parameters key type: str The workspace key to set value type: object The value to store # Workspace.__getitem__ ``` __getitem__( key: str, ) → object ``` Get a value from workspace, raising KeyError if key doesn't exist. ## Parameters key type: str The workspace key to retrieve ## Returns type: object The value associated with key ## Raises KeyError If the key doesn't exist in workspace # Workspace.__setitem__ ``` __setitem__( key: str, value: object, ) → None ``` Set a value in workspace. ## Parameters key type: str The workspace key to set value type: object The value to store # Workspace.__contains__ ``` __contains__( key: str, ) → bool ``` Check if a key exists in workspace. ## Parameters key type: str The workspace key to check ## Returns type: bool True if key exists, False otherwise # Workspace.get_messages ``` get_messages() → list[Message] ``` Get the messages in the workspace. ## Returns type: list[Message] A copy of the workspace's message history. Mutating the returned list does not affect the conversation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/exceptions/ # yera.exceptions Base exception hierarchy for user-facing Yera errors. Raise a subtype from anywhere in the call stack; the CLI launcher catches `YeraError`, prints it to stderr, and exits with code 1. Never catch these inside command bodies for display purposes. ## Symbols class YeraError — Base for all user-facing Yera errors. # YeraError Inherits: `Exception` Subclasses: `ToolDecoratorError`, `MCPError`, `ConfigError`, `CredentialError` Base for all user-facing Yera errors. --- Source: https://yera-labs.io/docs/yera/reference/implementation/locations/ # yera.locations Shared filesystem location primitives for config, credentials, and CLI. ## Symbols def discover_pyproject — Find the nearest pyproject.toml walking up from CWD, stopping at .git. def resolve_project_root — Return the directory containing the nearest pyproject.toml. def yera_home_dir — Return the Yera user data directory. # discover_pyproject ``` discover_pyproject( require_tool_yera: bool = False, ) → Path | None ``` Find the nearest pyproject.toml walking up from CWD, stopping at .git. If require_tool_yera=True, only return files that contain [tool.yera]. Returns None when no qualifying file is found. # resolve_project_root ``` resolve_project_root() → Path | None ``` Return the directory containing the nearest pyproject.toml. Uses require_tool_yera=False — accepts any pyproject.toml. Used by credential authorisation to establish the authoritative project root, independently of whether the project has configured Yera yet. # yera_home_dir ``` yera_home_dir() → Path ``` Return the Yera user data directory. Default: ~/.yera/ Override: YERA_HOME environment variable. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/ # yera.models Submodule for discovering models from config and using them in Yera programs. ## Submodules atlas context context_factory data_classes gemini_lookup interfaces reasoning_lookup workspace --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/atlas/ # yera.models.atlas Submodule for Yera's model atlases infrastructure. ## Submodules base lazy_loading llm --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/atlas/base/ # yera.models.atlas.base Navigable tree of model context factories. Defines `BaseAtlas`, the abstract base for model atlases. Atlases are built from the active Yera profile at config-load time and made available to user code through proxy singletons such as `llm`. They are to be used for exploring available models and then setting them as the active context to be used within apps. ## Symbols class BaseAtlas — A navigable tree of model context factories. # BaseAtlas Inherits: `PathTree[TFactory]`, `ABC`, `Generic[TContext, TFactory]` Subclasses: `LLMAtlas` A navigable tree of model context factories. Each leaf is a callable that returns a model context, ready for use in a `with` block. Each interior node is another atlas, holding further sub-atlases and leaves. Yera exposes one atlas per type of model: LLMs, TTS, STT, and so on. Atlases are built from the active Yera profile and are not constructed by user code directly; users access them through proxy singletons such as `llm`. Two access styles are supported: - **Attribute access**, preferred for interactive use (Jupyter, REPL): `atlas.openai.gpt_4o`. Dashes in configured model names become underscores in attribute form (`"gpt-4o"` → `gpt_4o`). - **Dot-path indexing**, preferred for scripts: `atlas["openai.gpt-4o"]`. The dashed form from configuration is accepted here directly. Atlases render as a tree when printed, so they are self-describing in interactive sessions: ## Examples ```python print(atlas) ``` ``` ┌─[model-type] ├─ Default: provider1.model2 │ ├── provider1/ │ ├── model1 │ └── model2 └── provider2/ └── model1 ``` ## Methods none — Return a no-op model context for this atlas type. __yera_tree__ — Return this atlas as tree-selector-compatible options. __str__ — Render the atlas as a tree, showing children and the default. __repr__ — Return a tree view of the atlas as a string. __len__ — Number of children on this node. # BaseAtlas.none ``` none() → TContext ``` Return a no-op model context for this atlas type. ## Returns type: TContext A model context representing the absence of a model. # BaseAtlas.__yera_tree__ ``` __yera_tree__() → TreeSelectorMapping ``` Return this atlas as tree-selector-compatible options. ## Returns type: TreeSelectorMapping Nested atlas labels whose leaves contain their original configured IDs. # BaseAtlas.__str__ ``` __str__() → str ``` Render the atlas as a tree, showing children and the default. The same rendering is used for `__repr__`, so atlases display informatively in REPLs and notebooks. # BaseAtlas.__repr__ ``` __repr__() → str ``` Return a tree view of the atlas as a string. # BaseAtlas.__len__ ``` __len__() → int ``` Number of children on this node. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/atlas/lazy_loading/ # yera.models.atlas.lazy_loading Lazy access to the configured LLM atlas. Exposes `llm`, the entry point for resolving LLM providers and models from the active profile. The atlas is built lazily on first access so that importing this module stays cheap; subsequent accesses reuse the same atlas instance. ## Symbols def invalidate_model_atlases — Discard cached model atlases so they rebuild from current configuration. # invalidate_model_atlases ``` invalidate_model_atlases() → None ``` Discard cached model atlases so they rebuild from current configuration. Existing model contexts are unaffected. The next access through a lazy atlas proxy reconstructs its atlas from the active Yera configuration. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/atlas/llm/ # yera.models.atlas.llm LLM atlas: configured LLM models, organised by provider. ## Symbols class LLMAtlas — Atlas of configured LLM models. # LLMAtlas Inherits: `BaseAtlas[LLMContext, LLMContextFactory]` Atlas of configured LLM models. Specialisation of `BaseAtlas` whose leaves are LLM context factories. Accessed via the `llm` singleton: ## Examples ```python import yera as yr ... with yr.llm.openai.gpt_4o(): # LLM calls in here use gpt-4o ... ``` See `BaseAtlas` for the access patterns and tree-view behaviour shared with other atlas types. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/context/ # yera.models.context Module for model contexts. A model context represents the currently-active model of a given type. When a context is active DSL functions that relate to that model type will invoke the active model. ## Submodules base llm --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/context/base/ # yera.models.context.base Module containing the base class for all model contexts. ## Symbols class BaseModelContext — The abstract base class for all model context classes. # BaseModelContext Inherits: `ABC` Subclasses: `LLMContext` The abstract base class for all model context classes. Implementations must implement a method that gets the current value in a context var. This is used to manage a stack of model contexts. ## Methods __enter__ — Enter the model context and make it the active one. __exit__ — Exit the model context and return to the previous context value. # BaseModelContext.__enter__ ``` __enter__() → None ``` Enter the model context and make it the active one. # BaseModelContext.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) ``` Exit the model context and return to the previous context value. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/context/llm/ # yera.models.context.llm Module containing the LLM context infrastructure. Consists of - the context var that contains the current llm context. - the llm context class itself. - the llm_context function gets the active llm context. ## Symbols class EmptyResponse — A stream produced no response tokens. class EmptyStructResponse — A struct stream produced no response tokens. def has_active_llm — Check whether there is an active llm. def llm_context — Get the current active LLM context. class LLMContext — Manages the currently-active LLM instance and its execution context. # EmptyResponse Inherits: `RuntimeError` Subclasses: `EmptyStructResponse` A stream produced no response tokens. # EmptyStructResponse Inherits: `EmptyResponse` A struct stream produced no response tokens. # has_active_llm ``` has_active_llm() → bool ``` Check whether there is an active llm. ## Returns type: bool true if there's an llm false if not # llm_context ``` llm_context() → LLMContext ``` Get the current active LLM context. ## Returns type: LLMContext the active context. # LLMContext Inherits: `BaseModelContext` Manages the currently-active LLM instance and its execution context. An LLM context encapsulates the interface to an LLM provider and provides access to the app workspace where message history and variables are stored. It acts as a context manager for proper initialization and cleanup of the LLM interface during execution. Attributes: interface: The LLM provider interface for sending prompts and receiving responses. app_meta: Metadata about the app context this LLM is executing within. ## Methods add_sys_line — Add a system message to the workspace and emit an event. add_user_line — Add a user message to the workspace and emit an event. add_assistant_line — Add an assistant message to the workspace. add_tool_call_line — Record a tool call message in the workspace. add_tool_result_line — Record a tool result message in the workspace. insert — Insert string content as a user message. gen — Generate an LLM prose response (not structured gen). struct_gen — Send a prompt to the LLM and return a structured response. insert_result — Insert a tool result into the active conversation. __enter__ — Enter the context manager and initialize the LLM interface. __exit__ — Exit the context manager and clean up the LLM interface. # LLMContext.add_sys_line ``` add_sys_line( content: str, ) → None ``` Add a system message to the workspace and emit an event. ## Parameters content type: str The system message content. # LLMContext.add_user_line ``` add_user_line( content: str, ) → None ``` Add a user message to the workspace and emit an event. ## Parameters content type: str The user message content. # LLMContext.add_assistant_line ``` add_assistant_line( content: str, thinking: str | None = None, on_wire: bool = True, provider_data: list[dict[str, object]] | None = None, ) → None ``` Add an assistant message to the workspace. ## Parameters content type: str The assistant message content. thinking type: str | None = None The assistant's thinking trace content (optional). on_wire type: bool = True whether the assistant line should be included in the model context. provider_data type: list[dict[str, object]] | None = None Opaque provider state required for later requests. # LLMContext.add_tool_call_line ``` add_tool_call_line( content: str, tool_id: str, call_id: str, tool_schema: dict, provider_data: list[dict[str, object]] | None = None, ) → None ``` Record a tool call message in the workspace. ## Parameters content type: str JSON string containing the tool arguments. tool_id type: str Name of the invoked tool. call_id type: str Unique identifier for this invocation. tool_schema type: dict JSON schema describing the tool input. provider_data type: list[dict[str, object]] | None = None Opaque provider state required for later requests. # LLMContext.add_tool_result_line ``` add_tool_result_line( content: str, tool_id: str, call_id: str, tool_schema: dict, ) → None ``` Record a tool result message in the workspace. ## Parameters content type: str JSON string of the tool's result/output. tool_id type: str Name of the invoked tool (model class name). call_id type: str Unique ID matching the original tool call. tool_schema type: dict Full JSON schema used for validation (same as in add_tool_call_line). # LLMContext.insert ``` insert( content: str, ) → None ``` Insert string content as a user message. # LLMContext.gen ``` gen( instruction: str | None = None, on_wire: bool = True, **kwargs, ) → str ``` Generate an LLM prose response (not structured gen). ## Parameters instruction type: str | None = None additional instruction to condition the LLM's generation. on_wire type: bool = True whether the generated response is to be kept in the model context. **kwargs type: str | int | float | bool keyword args to be passed down to the LLM invocation. ## Returns type: str the generated LLM response. # LLMContext.struct_gen ``` struct_gen( instruction: str | None = None, on_wire: bool = False, **kwargs, ) → TStruct ``` Send a prompt to the LLM and return a structured response. Adds the user prompt to the workspace, requests a structured response from the LLM interface, parses the JSON response, and records it in the workspace. ## Parameters cls type: type[TStruct] The Pydantic model class to parse the structured response into. instruction type: str | None = None additional instruction to condition the LLM's generation. on_wire type: bool = False whether the generated response is to be kept in the model context. **kwargs type: str | float | int Additional arguments to pass to the LLM interface. ## Returns type: TStruct An instance of cls populated with the LLM response data. # LLMContext.insert_result ``` insert_result( result: object, ) → None ``` Insert a tool result into the active conversation. Structured values are converted to transport-safe JSON using Yera's serialization infrastructure. String results remain plain text so they can be inserted without JSON quoting. ## Parameters result type: object Tool result to add to the model context. ## Raises TypeError If the result contains a value unsupported by Yera's typing infrastructure. ValueError If a supported value cannot be serialized. # LLMContext.__enter__ ``` __enter__() ``` Enter the context manager and initialize the LLM interface. Captures the current app metadata, sets up the workspace, and initializes the LLM interface. ## Returns This context instance. # LLMContext.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) ``` Exit the context manager and clean up the LLM interface. ## Parameters exc_type type: type[BaseException] | None The exception type if an error occurred, else None. exc_val type: BaseException | None The exception value if an error occurred, else None. exc_tb type: TracebackType | None The exception traceback if an error occurred, else None. ## Submodules markdown spinner struct system_prompt thinking --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/context_factory/ # yera.models.context_factory Module containing the model context factory classes. Model context factories are responsible for creating model contexts for different model types. ## Submodules base llm --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/context_factory/base/ # yera.models.context_factory.base Module containing the base class for all module factories. ## Symbols class BaseModelContextFactory — The base model context factory class. # BaseModelContextFactory Inherits: `ABC`, `Generic[C, N]` Subclasses: `LLMContextFactory` The base model context factory class. Model context factories build model contexts based on the information in a model config object and a provider connection config object. Inheritors must implement **call** which will return a model context of some model type. This will also allow keyword arguments that override the model's inference and other parameters. ## Methods __call__ — The factory call method that builds model context objects. # BaseModelContextFactory.__call__ ``` __call__( **kwargs, ) → BaseModelContext ``` The factory call method that builds model context objects. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/context_factory/llm/ # yera.models.context_factory.llm Module for the LLM implementation of BaseModelContextFactory. ## Symbols class LLMContextFactory — Context factory class for LLM context objects. # LLMContextFactory Inherits: `BaseModelContextFactory[LLMConfig, BaseConnection]` Context factory class for LLM context objects. ## Methods __call__ — Build an LLM context instance for the configured llm and connection. # LLMContextFactory.__call__ ``` __call__( **kwargs, ) → LLMContext ``` Build an LLM context instance for the configured llm and connection. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/data_classes/ # yera.models.data_classes Class representing structured LLM conversation messages. ## Symbols class Message — A single turn in an LLM conversation, optionally including thinking traces and tool metadata. class ToolData — Metadata associated with a tool call or its result. # Message Inherits: `BaseModel` A single turn in an LLM conversation, optionally including thinking traces and tool metadata. ## Attributes role type: Literal['user', 'system', 'assistant', 'tool_call', 'tool_result'] The speaker role. content type: str The text content of the message. thinking type: str | None The thinking trace leading up to the content (if any) tool_data type: ToolData | None data required for tool calls and results on_wire type: bool whether a message is to be included back into the model context. ## Methods user — Create a user-role message. system — Create a system-role message. assistant — Create an assistant-role message. tool_call — Create a tool call message with metadata. tool_result — Create a tool result message with metadata. # Message.user ``` user( content: str, ) → Message ``` Create a user-role message. ## Parameters content type: str The text content of the user message. ## Returns type: Message A Message instance with role set to 'user'. # Message.system ``` system( content: str, ) → Message ``` Create a system-role message. ## Parameters content type: str The text content of the system prompt. ## Returns type: Message A Message instance with role set to 'system'. # Message.assistant ``` assistant( content: str, thinking: str | None = None, on_wire: bool = True, provider_data: list[dict[str, object]] | None = None, ) → Message ``` Create an assistant-role message. ## Parameters content type: str The text generated by the assistant. thinking type: str | None = None Optional “thinking” trace produced while the assistant was formulating its response. Stored for later inspection if provided. on_wire type: bool = True whether this line should be kept in the LLM context. provider_data type: list[dict[str, object]] | None = None Opaque provider state required for later requests. ## Returns type: Message A `Message` instance with `role` set to `"assistant"`, containing the supplied content and optional thinking data. # Message.tool_call ``` tool_call( content: str, tool_id: str, call_id: str, tool_schema: dict, provider_data: list[dict[str, object]] | None = None, ) → Message ``` Create a tool call message with metadata. ## Parameters content type: str JSON-formatted tool invocation payload. tool_id type: str Name of the invoked tool. call_id type: str Unique identifier for this invocation. tool_schema type: dict JSON schema describing the tool input. provider_data type: list[dict[str, object]] | None = None Opaque provider state required for later requests. ## Returns type: Message A tool-call message containing its invocation metadata. # Message.tool_result ``` tool_result( content: str, tool_id: str, call_id: str, tool_schema: dict, ) → Message ``` Create a tool result message with metadata. ## Parameters content type: str JSON-formatted tool execution result. tool_id type: str Name of the tool invoked (must match original call). call_id type: str Unique ID matching the original tool call. tool_schema type: dict Same schema as used in `tool_call`. ## Returns type: Message A `Message` instance with `role` set to `"tool_result"`, containing the result content and tool metadata. # ToolData Inherits: `BaseModel` Metadata associated with a tool call or its result. ## Attributes tool_id type: str Name of the invoked tool (usually the class name). call_id type: str Unique identifier for this specific tool invocation. tool_schema type: dict JSON schema describing expected input/output structure. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/gemini_lookup/ # yera.models.gemini_lookup Capability lookup for Gemini models. ## Symbols class GeminiCapabilitySpec — Capabilities that cannot be determined from Gemini model metadata. def look_up_gemini_capabilities — Look up capabilities unavailable from the Gemini catalogue. # GeminiCapabilitySpec Capabilities that cannot be determined from Gemini model metadata. # look_up_gemini_capabilities ``` look_up_gemini_capabilities( model_id: str, ) → GeminiCapabilitySpec ``` Look up capabilities unavailable from the Gemini catalogue. ## Parameters model_id type: str The provider-side Gemini model identifier. ## Returns type: GeminiCapabilitySpec The matching capability specification, or conservative defaults. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/ # yera.models.interfaces Module containing all model interfaces classes. Model interface classes are the means by which Yera's internals connect to model providers. Different models types are to be implementations of different model interface base classes. An instance of a model interface is to represent interation with one speciicif model via one specific provider. Information is to be specified via model config and connection config objects. ## Submodules llms --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/ # yera.models.interfaces.llms Module containing all LLM interface classes. LLM interfaces represent the interaction surface with a given model provider's models. ## Submodules anthropic aws_bedrock azure_openai base gemini llama_cpp mistral no_llm ollama_interface open_ai openrouter registry utils --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/anthropic/ # yera.models.interfaces.llms.anthropic Module containing the interface to Anthropic LLMs. ## Symbols class AnthropicLLM — Interface to Anthropic LLMs via the Anthropic SDK. # AnthropicLLM Inherits: `BaseLLMInterface` Interface to Anthropic LLMs via the Anthropic SDK. This class provides a wrapper around the Anthropic API client, handling configuration, model selection, and streaming interactions with Claude models. It supports both standard chat completions and structured output generation for models that support it (Claude 4.5+). ## Attributes model_id type: str The identifier of the Claude model to use. connection type: AnthropicConnection Connection configuration for the Anthropic API. client type: Anthropic Lazy-initialised Anthropic API client instance. capabilities type: AnthropicLLMCapabilities object defining the capabilities of the LLM. inference type: AnthropicLLMInference object defining the inference params of the LLM. ## Methods start — Initialize the Anthropic API client. stop — Shut down and clear the Anthropic API client. chat — Stream a chat completion response from Anthropic. make_struct — Stream a structured output response conforming to a schema. with_instruction — Prepend or insert an instruction into the conversation history. # AnthropicLLM.start ``` start() → None ``` Initialize the Anthropic API client. Creates and stores an Anthropic client instance using the configured connection settings. This method must be called before making any API requests via the client property. # AnthropicLLM.stop ``` stop() → None ``` Shut down and clear the Anthropic API client. Releases the Anthropic client instance by setting it to None. After calling this method, start() must be called again before further API requests can be made. # AnthropicLLM.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **anthropic_kw, ) → Iterator[LLMToken] ``` Stream a chat completion response from Anthropic. Thinking content is streamed only when the model thinks and `display` is `"summarized"`. Under adaptive thinking the model may skip thinking entirely. ## Parameters messages type: list[Message] The workspace conversation history. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (medium) **anthropic_kw type: str | int | float | bool Per-call overrides passed to the Messages API, taking precedence over configured inference parameters. # AnthropicLLM.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **anthropic_kw, ) → Iterator[LLMToken] ``` Stream a structured output response conforming to a schema. The response is constrained by the schema through the API's structured outputs support. Thinking, when the model thinks, is unconstrained and arrives as thinking tokens ahead of the JSON. ## Parameters messages type: list[Message] The workspace conversation history. cls type: type[TStruct] A pydantic model class defining the output structure. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (off) **anthropic_kw type: str | float | int | bool Per-call overrides passed to the Messages API, taking precedence over configured inference parameters. ## Raises ValueError If the model does not support structured outputs. # AnthropicLLM.with_instruction ``` with_instruction( messages: list[Message], instruction: str | None, ) → list[Message] ``` Prepend or insert an instruction into the conversation history. ## Parameters messages type: list[Message] The existing conversation history. instruction type: str | None The extra instruction to inject. ## Returns type: list[Message] A new list of messages with the instruction incorporated. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/aws_bedrock/ # yera.models.interfaces.llms.aws_bedrock Module containing the interface to AWS bedrock LLMs. ## Symbols class AwsBedrockLLM — Interface to AWS Bedrock LLM models. # AwsBedrockLLM Inherits: `BaseLLMInterface` Interface to AWS Bedrock LLM models. This class provides a wrapper around the AWS Bedrock runtime client, enabling interactions with various LLM models available through Bedrock (AWS Bedrock Claude, Qwen, OpenAI, DeepSeek, Google Gemini, and others). It supports both standard chat completions and structured output generation for models that support it. The class automatically detects whether the selected model natively supports structured outputs or requires a tool-use fallback. ## Attributes config type: LLMConfig Configuration settings for the LLM including model_id and inference parameters. connection type: AWSConnection AWS connection configuration including credentials and region information. native_struct type: bool Whether the selected model supports native structured output generation. client type: BaseClient Lazy-initialized AWS Bedrock runtime client instance. ## Methods start — Initialise the AWS Bedrock API client. stop — Shut down and clear the AWS Bedrock API client. chat — Stream a chat response through the configured AWS transport. make_struct — Stream a structured response through the configured AWS transport. # AwsBedrockLLM.start ``` start() → None ``` Initialise the AWS Bedrock API client. Creates and stores an AWS Bedrock client instance using the configured connection settings. This method must be called before making any API requests via the client property. # AwsBedrockLLM.stop ``` stop() → None ``` Shut down and clear the AWS Bedrock API client. Releases the AWS Bedrock client instance by setting it to None. After calling this method, start() must be called again before further API requests can be made. # AwsBedrockLLM.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a chat response through the configured AWS transport. Responses models use Bedrock Runtime's OpenAI-compatible endpoint. Other Bedrock models use the Converse API. ## Parameters messages type: list[Message] Workspace conversation history. reasoning_level type: ReasoningLevel | None = None Per-call reasoning override. **overrides type: str | int | float | bool Per-call inference overrides. # AwsBedrockLLM.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a structured response through the configured AWS transport. Responses models use OpenAI-compatible strict JSON Schema. Converse models use Bedrock's native structured-output configuration. ## Parameters messages type: list[Message] Workspace conversation history. cls type: type[TStruct] Struct class defining the required output. reasoning_level type: ReasoningLevel | None = None Per-call reasoning override. **overrides type: str | int | float | bool Per-call inference overrides. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/azure_openai/ # yera.models.interfaces.llms.azure_openai Module containing the interface to Azure OpenAI LLMs. ## Symbols class AzureOpenAILLM — Interface to Azure OpenAI llms. # AzureOpenAILLM Inherits: `OpenAILLM` Interface to Azure OpenAI llms. Specialisation of OpenAILLM configured to work with Azure's OpenAI service. Handles Azure-specific authentication and endpoint configuration, whilst inheriting all standard chat and structured output functionality from the OpenAI interface. ## Attributes config type: LLMConfig Configuration settings for the llm including model_id and inference parameters. connection type: AzureConnection Azure connection configuration including API key, endpoint, and deployment information. client type: AzureOpenAI Lazy-initialised Azure OpenAI client instance. ## Methods start — Initialise the Azure OpenAI client. # AzureOpenAILLM.start ``` start() → None ``` Initialise the Azure OpenAI client. Creates and stores an Azure OpenAI client instance using the configured Azure connection settings (API key, endpoint, deployment). This method must be called before making any API requests via the client property. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/base/ # yera.models.interfaces.llms.base Base interface for LLM implementations. This module defines the abstract BaseLLMInterface that all llm provider implementations must inherit from. It establishes the contract for: - Streaming chat completions (chat method) - Generating structured outputs conforming to a schema (make_struct method) - Managing llm client lifecycle (start/stop methods) Concrete implementations (e.g., AnthropicLLM, OpenAILLM, AwsBedrockLLM) provide provider-specific implementations of these abstract methods whilst handling their respective API clients and configuration. ## Symbols class BaseLLMInterface — Abstract base interface for llm implementations. class LLMToken — Class representing a token in an LLM response. class RateLimitError — A provider rate-limit response that may succeed after waiting. # BaseLLMInterface Inherits: `ABC` Subclasses: `MistralLLM`, `AwsBedrockLLM`, `NoLLM`, `AnthropicLLM`, `OllamaLLM`, `OpenAILLM`, `OpenRouterLLM`, `LlamaCppLLM`, `GeminiLLM` Abstract base interface for llm implementations. Defines the contract that all concrete llm provider implementations must satisfy. Subclasses handle provider-specific client initialisation, authentication, and API interaction whilst conforming to the streaming chat and structured output methods defined here. ## Methods chat — Stream a chat completion response. make_struct — Stream a structured output response conforming to a provided schema. make_request_struct — Generate a tool-like request structure with an initial `call_id` token. start — Initialise the llm client. stop — Shut down and clear the llm client. with_instruction — Prepend or insert an instruction into the conversation history. # BaseLLMInterface.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **kwargs, ) → Iterator[LLMToken] ``` Stream a chat completion response. Abstract method that must be implemented by concrete llm providers. Sends a conversation to the llm and streams the response as text tokens. ## Parameters messages type: list[Message] List of Message objects representing the conversation history. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (medium) **kwargs type: str | int | float | bool Provider-specific keyword arguments to customise llm behaviour (e.g., temperature, top_p, max_tokens). # BaseLLMInterface.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **kwargs, ) → Iterator[LLMToken] ``` Stream a structured output response conforming to a provided schema. Abstract method that must be implemented by concrete llm providers. Generates a response that strictly conforms to the structure defined by the provided schema class. ## Parameters messages type: list[Message] List of Message objects representing the conversation history. cls type: type[TStruct] A pydantic model class defining the output structure. The provider will transform this into the format required by its respective API. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (off) **kwargs type: str | float | int | bool Provider-specific keyword arguments to customise llm behaviour. # BaseLLMInterface.make_request_struct ``` make_request_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **kwargs, ) → Iterator[LLMToken] ``` Generate a tool-like request structure with an initial `call_id` token. Prepares a unique identifier for the tool call and streams structured output tokens. This method is intended for tools that require a `tool_call` → `tool_result` interaction pattern, where the `call_id` must be sent first to associate results. ## Parameters messages type: list[Message] Conversation history. cls type: type[TStruct] Struct subclass defining the tool's input/output schema. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (off) **kwargs type: str | float | int | bool Per-call LLM overrides (e.g., temperature, max_tokens). # BaseLLMInterface.start ``` start() → None ``` Initialise the llm client. Lifecycle method called before making API requests. Concrete implementations override this to instantiate and configure their provider-specific client. Default implementation does nothing. # BaseLLMInterface.stop ``` stop() → None ``` Shut down and clear the llm client. Lifecycle method called when finished with the llm. Concrete implementations override this to release resources and clean up the provider-specific client. Default implementation does nothing. # BaseLLMInterface.with_instruction ``` with_instruction( messages: list[Message], instruction: str | None, ) → list[Message] ``` Prepend or insert an instruction into the conversation history. ## Parameters messages type: list[Message] The existing conversation history. instruction type: str | None The extra instruction to inject. ## Returns type: list[Message] A new list of messages with the instruction incorporated. # LLMToken Class representing a token in an LLM response. Can be either "thinking" from a reasoning (CoT) trace, or "response" as in a normal response to the user. ## Attributes kind type: Literal['response', 'thinking', 'call_id'] a string that defines this as a thinking or response token. content type: str the content of the token. # RateLimitError Inherits: `RuntimeError` A provider rate-limit response that may succeed after waiting. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/gemini/ # yera.models.interfaces.llms.gemini Yera LLM interface for the Gemini Developer API. ## Symbols class GeminiLLM — LLM interface for models invoked through the Gemini Developer API. # GeminiLLM Inherits: `BaseLLMInterface` LLM interface for models invoked through the Gemini Developer API. ## Methods start — Initialise the Gemini client. stop — Close and clear the Gemini client. chat — Stream a chat response from Gemini. make_struct — Stream JSON conforming to a strict schema from Gemini. make_request_struct — Stream a forced structured function call from Gemini. # GeminiLLM.start ``` start() → None ``` Initialise the Gemini client. # GeminiLLM.stop ``` stop() → None ``` Close and clear the Gemini client. # GeminiLLM.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a chat response from Gemini. # GeminiLLM.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream JSON conforming to a strict schema from Gemini. # GeminiLLM.make_request_struct ``` make_request_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a forced structured function call from Gemini. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/llama_cpp/ # yera.models.interfaces.llms.llama_cpp Interface to local llms via llama.cpp. This module provides the LlamaCppLLM class for running large language models locally using the llama.cpp inference engine. Models are specified via a file path in the configuration. The interface supports optional GPU acceleration via the n_gpu_layers parameter, and provides both streaming chat completions and structured output generation using JSON schema constraints. ## Symbols class LlamaCppLLM — Interface to local llms via llama.cpp inference engine. # LlamaCppLLM Inherits: `BaseLLMInterface` Interface to local llms via llama.cpp inference engine. Provides a wrapper around the llama.cpp library for running quantised language models locally. The model file path is specified directly in the configuration. Supports optional GPU acceleration via the n_gpu_layers parameter, and provides both streaming chat completions and structured output generation with JSON schema constraints. The model is lazily initialised on start() and must be explicitly shut down via stop(). All API methods require the model to be started first. ## Attributes config type: LLMConfig Configuration settings for the llm including model path and inference parameters. connection type: LlamaCppConnection Connection configuration for llama.cpp. model type: Llama Lazy-initialised llama.cpp model instance. ## Methods start — Initialise the llama.cpp model. stop — Shut down and release the llama.cpp model. chat — Stream a chat completion response from the local llm. make_struct — Stream a structured output response conforming to a provided schema. make_request_struct — Generate a tool-like request structure with an initial `call_id` token. # LlamaCppLLM.start ``` start() → None ``` Initialise the llama.cpp model. Loads the quantised model from disk and initialises the llama.cpp inference engine. GPU acceleration is enabled by default (n_gpu_layers=-1) unless overridden in configuration. Must be called before any chat or structured output requests. ## Raises ValueError If the model is already running. # LlamaCppLLM.stop ``` stop() → None ``` Shut down and release the llama.cpp model. Safe to call once per start(). After returning, the interface may be restarted via start(). # LlamaCppLLM.chat ``` chat( messages: list[Message], temperature: float = 0.2, top_p: float = 0.95, top_k: int = 40, min_p: float = 0.05, typical_p: float = 1.0, stop: str | list[str] | None = None, seed: int | None = None, max_tokens: int | None = None, presence_penalty: float = 0.0, frequency_penalty: float = 0.0, repeat_penalty: float = 1.0, **llama_cpp_kw, ) → Iterator[LLMToken] ``` Stream a chat completion response from the local llm. Sends a conversation to the llama.cpp model and streams the response as text tokens. Supports fine-grained control over sampling behaviour through temperature, top-k, top-p, and other sampling parameters. ## Parameters messages type: list[Message] List of Message objects representing the conversation history. temperature type: float = 0.2 Sampling temperature controlling randomness (0.0-2.0). Defaults to 0.2. top_p type: float = 0.95 Nucleus sampling parameter (0.0-1.0). Defaults to 0.95. top_k type: int = 40 Top-k sampling limit. Defaults to 40. min_p type: float = 0.05 Minimum probability constraint (0.0-1.0). Defaults to 0.05. typical_p type: float = 1.0 Typical probability constraint (0.0-1.0). Defaults to 1.0. stop type: str | list[str] | None = None Stop sequence(s) to terminate generation. Defaults to None. seed type: int | None = None Random seed for reproducibility. Defaults to None. max_tokens type: int | None = None Maximum tokens to generate. Defaults to None. presence_penalty type: float = 0.0 Presence penalty for token repetition. Defaults to 0.0. frequency_penalty type: float = 0.0 Frequency penalty for token repetition. Defaults to 0.0. repeat_penalty type: float = 1.0 Repeat penalty multiplier. Defaults to 1.0. **llama_cpp_kw type: str | float | int | bool | None Additional keyword arguments passed to llama.cpp. ## Raises ValueError If the model has not been started. # LlamaCppLLM.make_struct ``` make_struct( messages: list[Message], temperature: float = 0.2, top_p: float = 0.95, top_k: int = 40, min_p: float = 0.05, typical_p: float = 1.0, seed: int | None = None, max_tokens: int | None = None, presence_penalty: float = 0.0, frequency_penalty: float = 0.0, repeat_penalty: float = 1.0, **llama_cpp_kw, ) → Iterator[LLMToken] ``` Stream a structured output response conforming to a provided schema. Generates a response that strictly conforms to the structure defined by the provided Pydantic model class. Uses JSON schema constraints to enforce structural compliance. Supports the same sampling parameters as chat(). ## Parameters messages type: list[Message] List of Message objects representing the conversation history. cls type: type[TStruct] A Pydantic model class defining the desired output structure. temperature type: float = 0.2 Sampling temperature controlling randomness (0.0-2.0). Defaults to 0.2. top_p type: float = 0.95 Nucleus sampling parameter (0.0-1.0). Defaults to 0.95. top_k type: int = 40 Top-k sampling limit. Defaults to 40. min_p type: float = 0.05 Minimum probability constraint (0.0-1.0). Defaults to 0.05. typical_p type: float = 1.0 Typical probability constraint (0.0-1.0). Defaults to 1.0. seed type: int | None = None Random seed for reproducibility. Defaults to None. max_tokens type: int | None = None Maximum tokens to generate. Defaults to None. presence_penalty type: float = 0.0 Presence penalty for token repetition. Defaults to 0.0. frequency_penalty type: float = 0.0 Frequency penalty for token repetition. Defaults to 0.0. repeat_penalty type: float = 1.0 Repeat penalty multiplier. Defaults to 1.0. **llama_cpp_kw type: str | float | int | bool | None Additional keyword arguments passed to llama.cpp. ## Raises ValueError If the model has not been started. # LlamaCppLLM.make_request_struct ``` make_request_struct( messages: list[Message], temperature: float = 0.2, top_p: float = 0.95, top_k: int = 40, min_p: float = 0.05, typical_p: float = 1.0, seed: int | None = None, max_tokens: int | None = None, presence_penalty: float = 0.0, frequency_penalty: float = 0.0, repeat_penalty: float = 1.0, **llama_cpp_kw, ) → Iterator[LLMToken] ``` Generate a tool-like request structure with an initial `call_id` token. Prepares a unique identifier for the tool call and streams structured output tokens. This method is intended for tools that require a `tool_call` → `tool_result` interaction pattern, where the `call_id` must be sent first to associate results. ## Parameters messages type: list[Message] Conversation history. cls type: type[TStruct] Struct subclass defining the tool's input/output schema. temperature type: float = 0.2 Sampling temperature controlling randomness (0.0-2.0). Defaults to 0.2. top_p type: float = 0.95 Nucleus sampling parameter (0.0-1.0). Defaults to 0.95. top_k type: int = 40 Top-k sampling limit. Defaults to 40. min_p type: float = 0.05 Minimum probability constraint (0.0-1.0). Defaults to 0.05. typical_p type: float = 1.0 Typical probability constraint (0.0-1.0). Defaults to 1.0. seed type: int | None = None Random seed for reproducibility. Defaults to None. max_tokens type: int | None = None Maximum tokens to generate. Defaults to None. presence_penalty type: float = 0.0 Presence penalty for token repetition. Defaults to 0.0. frequency_penalty type: float = 0.0 Frequency penalty for token repetition. Defaults to 0.0. repeat_penalty type: float = 1.0 Repeat penalty multiplier. Defaults to 1.0. **llama_cpp_kw type: str | float | int | bool | None Additional keyword arguments passed to llama.cpp. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/mistral/ # yera.models.interfaces.llms.mistral Interface to Mistral llms. This module provides the MistralLLM class for interacting with Mistral's language models. It supports both standard streaming chat completions and structured output generation via Mistral's native `json_schema` response format, which is available across Mistral's current chat completion models (unlike OpenAI, there is no per-model date cutoff to detect). ## Symbols class MistralLLM — Interface to Mistral llms. # MistralLLM Inherits: `BaseLLMInterface` Interface to Mistral llms. Provides a wrapper around the Mistral API client. Structured output uses Mistral's native `json_schema` response format directly, since Mistral does not require the model-version-based fallback that OpenAI/Anthropic need for their older models. The client is lazily initialised on start() and must be explicitly shut down via stop(). ## Attributes model_id type: str The identifier of the Mistral model to use. connection type: MistralConnection Connection configuration including API key. client type: Mistral Lazy-initialised Mistral API client instance. ## Methods start — Initialise the Mistral API client. stop — Shut down and clear the Mistral API client. chat — Stream a chat completion response from Mistral. make_struct — Stream a structured output response conforming to a schema. # MistralLLM.start ``` start() → None ``` Initialise the Mistral API client. Creates and stores a Mistral client instance using the configured connection settings (API key). This method must be called before making any API requests via the client property. # MistralLLM.stop ``` stop() → None ``` Shut down and clear the Mistral API client. Releases the Mistral client instance by setting it to None. After calling this method, start() must be called again before further API requests can be made. # MistralLLM.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a chat completion response from Mistral. Thinking is only produced when reasoning_effort is set to "high" on a model that supports it. ## Parameters messages type: list[Message] The workspace conversation history. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (medium) **overrides type: str | float | int | bool Per-call inference parameters. # MistralLLM.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a structured output response conforming to a schema. ## Parameters messages type: list[Message] The workspace conversation history. cls type: type[TStruct] A pydantic model class defining the output structure. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (off) **overrides type: str | float | int | bool Per-call inference parameters. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/no_llm/ # yera.models.interfaces.llms.no_llm No-op LLM implementation that raises errors when called. ## Symbols class NoLLM — An LLM interface that raises errors when used. # NoLLM Inherits: `BaseLLMInterface` An LLM interface that raises errors when used. This is used as a placeholder when no LLM is configured in the current context. Any attempt to use it will raise a RuntimeError. ## Methods chat — Raise an error indicating no LLM is available. make_struct — Raise an error indicating no LLM is available. # NoLLM.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **kwargs, ) → Iterator[LLMToken] ``` Raise an error indicating no LLM is available. ## Parameters messages type: list[Message] The messages to send (unused). reasoning_level type: ReasoningLevel | None = None Set the reasoning effort (unused). **kwargs type: str | int | float | bool Additional arguments (unused). ## Returns type: Iterator[LLMToken] An iterator of LLMToken objects (never returned). ## Raises RuntimeError Always raised to indicate no LLM is configured. # NoLLM.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **kwargs, ) → Iterator[LLMToken] ``` Raise an error indicating no LLM is available. ## Parameters messages type: list[Message] The messages to send (unused). cls type: type[TStruct] The struct type to create (unused). reasoning_level type: ReasoningLevel | None = None Set the reasoning effort (unused). **kwargs type: str | float | int | bool Additional arguments (unused). ## Returns type: Iterator[LLMToken] An iterator of LLMToken objects (never returned). ## Raises RuntimeError Always raised to indicate no LLM is configured. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/ollama_interface/ # yera.models.interfaces.llms.ollama_interface Interface to local and remote llms via Ollama. This module provides the OllamaLLM class for interacting with llms running on an Ollama server. Ollama can run models locally or connect to a remote instance. The interface supports both streaming chat completions and structured output generation using JSON schema constraints. The Ollama server must be running and accessible at the configured endpoint before any llm requests can be made. ## Symbols class OllamaLLM — Interface to local and remote llms via Ollama. # OllamaLLM Inherits: `BaseLLMInterface` Interface to local and remote llms via Ollama. Provides a wrapper around the Ollama client for interacting with language models running on an Ollama server. Supports both local models (on the same machine) and remote Ollama instances via HTTP. Validates server connectivity on start() and provides both streaming chat completions and structured output generation using JSON schema constraints. The client is lazily initialised on start() and validates that the Ollama server is accessible before allowing API requests. ## Attributes model_id type: str The identifier of the model to use on the Ollama server. connection type: OllamaConnection Connection configuration specifying the Ollama server URL. client type: Client Lazy-initialised Ollama client instance. ## Methods start — Initialise the Ollama client and validate server connectivity. stop — Shut down and clear the Ollama client. chat — Stream a chat completion response from Ollama. make_struct — Stream a structured output response conforming to a provided schema. make_request_struct — Generate a tool-like request structure with an initial `call_id` token. # OllamaLLM.start ``` start() → None ``` Initialise the Ollama client and validate server connectivity. Creates an Ollama client instance pointing to the configured server URL and verifies that the Ollama server is running and accessible. Must be called before making any API requests. ## Raises ConnectionError If the Ollama server is not running or not accessible at the configured URL. # OllamaLLM.stop ``` stop() → None ``` Shut down and clear the Ollama client. Releases the Ollama client instance by setting it to None. After calling this method, start() must be called again before further API requests can be made. # OllamaLLM.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **ollama_kw, ) → Iterator[LLMToken] ``` Stream a chat completion response from Ollama. Sends a conversation to the Ollama model and streams the response as text tokens. Supports models with thinking/reasoning capabilities (e.g., deepseek-r1) which are yielded wrapped in markers. ## Parameters messages type: list[Message] List of Message objects representing the conversation history. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (medium) **ollama_kw type: str | float | int | bool Additional keyword arguments passed to the Ollama API. ## Raises ValueError If the model is not found on the Ollama server. Pull the model with: ollama pull ConnectionError If the Ollama server is not accessible. # OllamaLLM.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **ollama_kw, ) → Iterator[LLMToken] ``` Stream a structured output response conforming to a provided schema. Generates a response that strictly conforms to the structure defined by the provided Pydantic model class. Uses Ollama's native format parameter with a JSON schema to enforce structural compliance. ## Parameters messages type: list[Message] List of Message objects representing the conversation history. cls type: type[TStruct] A Pydantic model class defining the desired output structure. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (off) **ollama_kw type: str | float | int | bool Additional keyword arguments passed to the Ollama API. ## Raises ValueError If the model is not found on the Ollama server. Pull the model with: ollama pull ConnectionError If the Ollama server is not accessible. # OllamaLLM.make_request_struct ``` make_request_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **ollama_kw, ) → Iterator[LLMToken] ``` Generate a tool-like request structure with an initial `call_id` token. Prepares a unique identifier for the tool call and streams structured output tokens. This method is intended for tools that require a `tool_call` → `tool_result` interaction pattern, where the `call_id` must be sent first to associate results. ## Parameters messages type: list[Message] Conversation history. cls type: type[TStruct] Struct subclass defining the tool's input/output schema. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (off) **ollama_kw type: str | float | int | bool Per-call LLM overrides (e.g., temperature, num_predict). --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/open_ai/ # yera.models.interfaces.llms.open_ai Yera LLM interface for OpenAI models. ## Symbols class OpenAILLM — LLM interface implementation for OpenAI LLMs. # OpenAILLM Inherits: `BaseLLMInterface` Subclasses: `AzureOpenAILLM` LLM interface implementation for OpenAI LLMs. ## Methods start — Initialise the OpenAI API client. stop — Shut down and clear the OpenAI API client. chat — Stream a chat response from OpenAI. make_struct — Stream a structured response conforming to a schema. make_request_struct — Generate a tool-like request structure with an initial `call_id` token. # OpenAILLM.start ``` start() → None ``` Initialise the OpenAI API client. Creates and stores an OpenAI client instance using the configured connection settings (API key, organisation, etc.). This method must be called before making any API requests via the client property. # OpenAILLM.stop ``` stop() → None ``` Shut down and clear the OpenAI API client. Releases the OpenAI client instance by setting it to None. After calling this method, start() must be called again before further API requests can be made. # OpenAILLM.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a chat response from OpenAI. Thinking is only produced when effort and summary are both set on a model that reasons. ## Parameters messages type: list[Message] The workspace conversation history. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (medium) **overrides type: str | float | int | bool Per-call inference parameters. # OpenAILLM.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a structured response conforming to a schema. ## Parameters messages type: list[Message] The workspace conversation history. cls type: type[TStruct] A pydantic model class defining the output structure. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (off) **overrides type: str | float | int | bool Per-call inference parameters. # OpenAILLM.make_request_struct ``` make_request_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Generate a tool-like request structure with an initial `call_id` token. Prepares a unique identifier for the tool call and streams structured output tokens. This method is intended for tools that require a `tool_call` → `tool_result` interaction pattern, where the `call_id` must be sent first to associate results. ## Parameters messages type: list[Message] Conversation history. cls type: type[TStruct] Struct subclass defining the tool's input/output schema. reasoning_level type: ReasoningLevel | None = None Set the reasoning effort level overriding the default (off) **overrides type: str | float | int | bool Per-call LLM overrides (e.g., temperature, num_predict). --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/openrouter/ # yera.models.interfaces.llms.openrouter Yera LLM interface for models invoked through OpenRouter. ## Symbols class OpenRouterLLM — LLM interface for models invoked through OpenRouter. # OpenRouterLLM Inherits: `BaseLLMInterface` LLM interface for models invoked through OpenRouter. ## Methods start — Initialise the OpenRouter client. stop — Clear the OpenRouter client. chat — Stream a chat response through OpenRouter. make_struct — Stream JSON conforming to a strict schema through OpenRouter. make_request_struct — Stream a forced structured tool call through OpenRouter. # OpenRouterLLM.start ``` start() → None ``` Initialise the OpenRouter client. # OpenRouterLLM.stop ``` stop() → None ``` Clear the OpenRouter client. # OpenRouterLLM.chat ``` chat( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a chat response through OpenRouter. # OpenRouterLLM.make_struct ``` make_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream JSON conforming to a strict schema through OpenRouter. # OpenRouterLLM.make_request_struct ``` make_request_struct( messages: list[Message], reasoning_level: ReasoningLevel | None = None, **overrides, ) → Iterator[LLMToken] ``` Stream a forced structured tool call through OpenRouter. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/registry/ # yera.models.interfaces.llms.registry Module for lazy/optional loading of llm provider interfaces. ## Symbols def get_interface — Get an interface class by name, loading it lazily. # get_interface ``` get_interface( name: str, ) → type[BaseLLMInterface] ``` Get an interface class by name, loading it lazily. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/interfaces/llms/utils/ # yera.models.interfaces.llms.utils Utility functions for parsing model reasoning output with delimiters. ## Symbols class ThinkingParser — A parser for model output that separates thinking and response content. # ThinkingParser A parser for model output that separates thinking and response content. ## Attributes _start The delimiter marking the start of thinking content. _end The delimiter marking the end of thinking content. _active Whether the parser is currently in a thinking block. _starts_thinking Whether the first block should be considered thinking. ## Methods parse_stream — Convert a stream of raw text chunks into classified tokens. # ThinkingParser.parse_stream ``` parse_stream( stream: Iterator[str], ) → Iterator[LLMToken] ``` Convert a stream of raw text chunks into classified tokens. ## Parameters stream type: Iterator[str] Chunks of model output, of any size. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/reasoning_lookup/ # yera.models.reasoning_lookup Reasoning capability lookup for LLM models by provider and model ID. Provides pattern-based matching to determine reasoning support, default levels, and budgets for different models across providers like Anthropic, OpenAI, Mistral, and AWS Bedrock. ## Symbols def look_up_reasoning_spec — Look up the reasoning specification for a given provider/author/model. class ReasoningSpec — Specification of reasoning capabilities for a model. # look_up_reasoning_spec ``` look_up_reasoning_spec( provider: str, author: str, model_id: str, ) → ReasoningSpec ``` Look up the reasoning specification for a given provider/author/model. ## Parameters provider type: str The LLM provider (e.g., "anthropic", "openai", "aws"). author type: str The model author or vendor (e.g., "anthropic", "amazon"). model_id type: str The exact model identifier to match against patterns. ## Returns type: ReasoningSpec The matching reasoning spec, or a default `none` spec if no match found. # ReasoningSpec Specification of reasoning capabilities for a model. --- Source: https://yera-labs.io/docs/yera/reference/implementation/models/workspace/ # yera.models.workspace Workspace module for managing conversation state and message history. This module provides the Workspace class which serves as a container for managing message sequences and variables in an app execution context. ## Symbols class Workspace — Manages message history and variable state for app execution. # Workspace Manages message history and variable state for app execution. The Workspace maintains a list of messages exchanged during app execution and provides a dictionary for storing arbitrary variables and context needed during execution. It provides convenience methods for adding messages of different roles (user, system, assistant). ## Attributes messages type: list[Message] A list of Message objects representing the conversation history. variables type: dict A dictionary for storing execution context and variables. ## Methods wire_messages — Get messages in the workspace not tagged as control flow. add_user_message — Add a user message to the workspace. add_sys_message — Add a system message to the workspace. add_assistant_message — Add a user message to the workspace. add_tool_call_message — Add a tool-call message to the workspace. add_tool_result_message — Add a tool result message to the workspace. # Workspace.wire_messages ``` wire_messages() → list[Message] ``` Get messages in the workspace not tagged as control flow. # Workspace.add_user_message ``` add_user_message( content: str, ) → None ``` Add a user message to the workspace. # Workspace.add_sys_message ``` add_sys_message( content: str, ) → None ``` Add a system message to the workspace. # Workspace.add_assistant_message ``` add_assistant_message( content: str, thinking: str | None = None, on_wire: bool = True, provider_data: list[dict[str, object]] | None = None, ) → None ``` Add a user message to the workspace. # Workspace.add_tool_call_message ``` add_tool_call_message( content: str, tool_id: str, call_id: str, tool_schema: dict, provider_data: list[dict[str, object]] | None = None, ) → None ``` Add a tool-call message to the workspace. # Workspace.add_tool_result_message ``` add_tool_result_message( content: str, tool_id: str, call_id: str, tool_schema: dict, ) → None ``` Add a tool result message to the workspace. --- Source: https://yera-labs.io/docs/yera/reference/implementation/opaque/ # yera.opaque Submodule for the opaque decorator. The opaque decorator and its inheritors mark functions as opaque to the SIGL compiler. When marked these will be treated as nodes in their own right in the computational graph and trigger prebuilt functions. ## Submodules base decorator function opaque_function --- Source: https://yera-labs.io/docs/yera/reference/implementation/opaque/base/ # yera.opaque.base Base class for opaque callables. ## Symbols class OpaqueCallable — Base class for callables that should appear as single opaque nodes in the graph. # OpaqueCallable Inherits: `ABC`, `Generic[P, R]` Subclasses: `OpaqueFunction` Base class for callables that should appear as single opaque nodes in the graph. ## Methods __call__ — Execute the opaque callable with the given arguments. __repr__ — Return a string representation of the opaque callable. # OpaqueCallable.__call__ ``` __call__( *args, **kwargs, ) → R ``` Execute the opaque callable with the given arguments. # OpaqueCallable.__repr__ ``` __repr__() → str ``` Return a string representation of the opaque callable. --- Source: https://yera-labs.io/docs/yera/reference/implementation/opaque/decorator/ # yera.opaque.decorator Decorator to mark functions as opaque. ## Symbols def opaque — Decorator to mark a function as opaque to the tracer. # opaque ``` opaque( func: Callable[P, R], ) → OpaqueFunction[P, R] ``` Decorator to mark a function as opaque to the tracer. --- Source: https://yera-labs.io/docs/yera/reference/implementation/opaque/function/ # yera.opaque.function Function introspection and configuration extraction for opaque callables. ## Symbols def extract_function_config — Extract a FunctionConfig from a callable via introspection. class FunctionConfig — Extracted configuration for a Python function, used to reconstruct or analyse it. class ParameterInfo — Metadata describing a single function parameter. class ParameterKind — Enumeration of supported parameter kinds, mirroring inspect.Parameter.kind. # extract_function_config ``` extract_function_config( func: Callable, ) → FunctionConfig ``` Extract a FunctionConfig from a callable via introspection. # FunctionConfig Inherits: `BaseModel` Extracted configuration for a Python function, used to reconstruct or analyse it. # ParameterInfo Inherits: `BaseModel` Metadata describing a single function parameter. ## Methods validate_default_for_kind — Validate parameter defaults and warn about mutable defaults. # ParameterInfo.validate_default_for_kind ``` validate_default_for_kind( v: object, info: ValidationInfo, ) → object ``` Validate parameter defaults and warn about mutable defaults. # ParameterKind Inherits: `str`, `Enum` Enumeration of supported parameter kinds, mirroring inspect.Parameter.kind. --- Source: https://yera-labs.io/docs/yera/reference/implementation/opaque/opaque_function/ # yera.opaque.opaque_function Opaque function wrapper and decorator. ## Symbols class OpaqueFunction — Wrapper for functions marked with @yk.opaque decorator. # OpaqueFunction Inherits: `OpaqueCallable[P, R]` Wrapper for functions marked with @yk.opaque decorator. ## Methods __call__ — Invoke the wrapped function with the given arguments. # OpaqueFunction.__call__ ``` __call__( *args, **kwargs, ) → R ``` Invoke the wrapped function with the given arguments. --- Source: https://yera-labs.io/docs/yera/reference/implementation/providers/ # yera.providers Common infra for authenticating and accessing model providers. To be used in model discovery (setup) and model invocation (yera runtime itself). ## Submodules anthropic_common aws_common azure_common gemini_common mistral_common openai_common openrouter_common --- Source: https://yera-labs.io/docs/yera/reference/implementation/providers/anthropic_common/ # yera.providers.anthropic_common Common infra for accessing Anthropic services. ## Symbols def get_anthropic_client — Build an anthropic client object from an anthropic connection object. # get_anthropic_client ``` get_anthropic_client( connection: AnthropicConnection, ) → Anthropic ``` Build an anthropic client object from an anthropic connection object. This will try to get the api key from the connection's specified location and then use it to build a client. --- Source: https://yera-labs.io/docs/yera/reference/implementation/providers/aws_common/ # yera.providers.aws_common Shared AWS credential and logging helpers. ## Symbols def build_bedrock_openai_client — Build an OpenAI-compatible client for Amazon Bedrock Runtime. def build_bedrock_runtime_client — Build a Bedrock runtime client from an AWSConnection config. def build_boto3_session — Build a boto3 Session pinned to a specific profile and region. def suppress_aws_logging — Silence chatty INFO/DEBUG logs from the AWS SDK chain. # build_bedrock_openai_client ``` build_bedrock_openai_client( connection: AWSConnection, ) → OpenAI ``` Build an OpenAI-compatible client for Amazon Bedrock Runtime. ## Parameters connection type: AWSConnection The AWS connection supplying the profile and region. ## Returns type: OpenAI An OpenAI client using the regional Bedrock Runtime endpoint. # build_bedrock_runtime_client ``` build_bedrock_runtime_client( connection: AWSConnection, ) → BaseClient ``` Build a Bedrock runtime client from an AWSConnection config. ## Parameters connection type: AWSConnection The AWS connection config supplying the profile and region used to construct the underlying boto3 session. ## Returns type: BaseClient A boto3 `BaseClient` targeting the `bedrock-runtime` service, pinned to the connection's region and credential profile. # build_boto3_session ``` build_boto3_session( profile: str | None, region: str, ) → boto3.Session ``` Build a boto3 Session pinned to a specific profile and region. Profile-level role assumption (`source_profile` + `role_arn` in ~/.aws/config) is handled by boto3. # suppress_aws_logging ``` suppress_aws_logging() → None ``` Silence chatty INFO/DEBUG logs from the AWS SDK chain. --- Source: https://yera-labs.io/docs/yera/reference/implementation/providers/azure_common/ # yera.providers.azure_common Shared Azure credential and logging helpers. Centralises credential construction so setup, discovery, and runtime all acquire tokens against the same tenant. Azure OpenAI supports AAD bearer tokens natively, so Yera never stores an API key for this provider. ## Symbols def build_azure_credential — Build a DefaultAzureCredential pinned to a specific tenant. def build_azure_openai_client — Build an AzureOpenAI client authenticated via AAD bearer token. def suppress_azure_logging — Silence chatty INFO-level logs from the Azure SDK chain. # build_azure_credential ``` build_azure_credential( tenant_id: str, ) → DefaultAzureCredential ``` Build a DefaultAzureCredential pinned to a specific tenant. `additionally_allowed_tenants` ensures the credential chain can acquire tokens for `tenant_id` even when the active Azure CLI context points elsewhere — which is the common failure mode for users with multiple Azure identities. ## Parameters tenant_id type: str The AAD tenant UUID this credential should target. ## Returns type: DefaultAzureCredential A DefaultAzureCredential that will try managed identity, workload identity, env vars, Azure CLI, and developer tools in order — all constrained to the given tenant. # build_azure_openai_client ``` build_azure_openai_client( connection: AzureConnection, ) → AzureOpenAI ``` Build an AzureOpenAI client authenticated via AAD bearer token. Constructs a tenant-pinned credential, wraps it in a token provider scoped to the Cognitive Services data plane, and passes it to the AzureOpenAI client. No API key is involved — authentication is handled entirely through the AAD credential chain. ## Parameters connection type: AzureConnection The Azure connection config supplying the tenant ID, endpoint URL, and API version. ## Returns type: AzureOpenAI An `AzureOpenAI` client configured for the connection's endpoint and API version, with AAD token-based authentication. # suppress_azure_logging ``` suppress_azure_logging() → None ``` Silence chatty INFO-level logs from the Azure SDK chain. DefaultAzureCredential logs every credential method it tries — and, when unauthenticated, every one it fails — on azure.identity, at WARNING. The token library (msal) and the HTTP pipeline add more. Raising the threshold to ERROR keeps genuine failures visible while dropping the per-attempt noise. Call before any operation that touches azure.* modules. --- Source: https://yera-labs.io/docs/yera/reference/implementation/providers/gemini_common/ # yera.providers.gemini_common Common infrastructure for accessing Gemini services. ## Symbols def get_gemini_client — Build a Gemini client from a configured connection. # get_gemini_client ``` get_gemini_client( connection: GeminiConnection, ) → genai.Client ``` Build a Gemini client from a configured connection. ## Parameters connection type: GeminiConnection Gemini connection containing the API-key location. ## Returns type: genai.Client A client configured for the Gemini Developer API. ## Raises ValueError If the configured environment variable is empty or absent. --- Source: https://yera-labs.io/docs/yera/reference/implementation/providers/mistral_common/ # yera.providers.mistral_common Common infra for accessing Mistral services. ## Symbols def get_mistral_client — Build a mistral client object from a mistral connection object. # get_mistral_client ``` get_mistral_client( connection: MistralConnection, ) → Mistral ``` Build a mistral client object from a mistral connection object. This will try to get the api key from the connection's specified location and then use it to build a client. --- Source: https://yera-labs.io/docs/yera/reference/implementation/providers/openai_common/ # yera.providers.openai_common Common infra for accessing OpenAI services. ## Symbols def get_openai_client — Build an openai client object from an openai connection object. # get_openai_client ``` get_openai_client( connection: OpenAIConnection, ) → OpenAI ``` Build an openai client object from an openai connection object. This will try to get the api key from the connection's specified location and then use it to build a client. --- Source: https://yera-labs.io/docs/yera/reference/implementation/providers/openrouter_common/ # yera.providers.openrouter_common Common infrastructure for accessing OpenRouter services. ## Symbols def get_openrouter_client — Build an OpenRouter client from a configured connection. # get_openrouter_client ``` get_openrouter_client( connection: OpenRouterConnection, ) → OpenRouter ``` Build an OpenRouter client from a configured connection. ## Parameters connection type: OpenRouterConnection the openrouter connection object to build from. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/ # yera.runtime Yera runtime infrastructure. Contains the parts for executing an app, handling the event stream and rendering the events. ## Submodules bar_chart blocks exceptions form_widgets glyphs handlers image input_echo line_chart markdown matplotlib models publisher replay_executor result router runtime section spinner stream struct system_prompt table thinking --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/ # yera.runtime.blocks Chat-specific block construction helpers for the Yera library. ## Symbols def reset_all_factories — Reset all block factory counters to 0. # reset_all_factories ``` reset_all_factories() → None ``` Reset all block factory counters to 0. ## Submodules bar_chart base buttons date_picker exit form image input_echo input_request line_chart markdown result section slider spinner startup struct system_prompt table thinking tree_selector --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/bar_chart/ # yera.runtime.blocks.bar_chart Bar chart block implementation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/base/ # yera.runtime.blocks.base Base classes for block construction. ## Submodules base chart --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/base/base/ # yera.runtime.blocks.base.base Base classes for block construction. ## Symbols def block_counters — Scope block-id numbering to one execution context. def block_scope — Push a block onto the ambient stack for the duration of its scope. def create_event — Create an event with automatic layout context detection. def get_parent_block_id — Return the innermost enclosing block, ignoring the block itself. # block_counters ``` block_counters() → Generator[None] ``` Scope block-id numbering to one execution context. Block ids are minted per block type and must be unique within a session: `oob()` addresses DOM nodes by block_id, so a collision lets one session's swaps land on another's nodes. Entering this scope starts numbering from one and discards it on exit. The scope is a `ContextVar`, so it follows the context rather than the session. A session running entirely in one task or thread is isolated; work handed to a bare `threading.Thread` starts with no scope and mints ids from one again. Copy the context (via `contextvars.copy_context` or an executor that does so) when emitting blocks from a worker. # block_scope ``` block_scope( block_id: str, ) → Generator[None] ``` Push a block onto the ambient stack for the duration of its scope. Events created inside the scope are stamped with this block as their parent, so nesting is expressed on the wire rather than inferred from arrival order. ## Parameters block_id type: str The block whose scope is being entered. # create_event ``` create_event( block_type: str, block_id: str, data: BlockData, chunk_id: int, parent_block_id: object | str = _UNSET, ) → OutputEvent ``` Create an event with automatic layout context detection. # get_parent_block_id ``` get_parent_block_id( exclude_block_id: str | None = None, ) → str | None ``` Return the innermost enclosing block, ignoring the block itself. ## Parameters exclude_block_id type: str | None = None A block to skip — its own events must not be stamped as children of itself. ## Returns type: str | None The enclosing block_id, or None at top level. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/base/chart/ # yera.runtime.blocks.base.chart Base chart block factory for shared chart functionality. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/buttons/ # yera.runtime.blocks.buttons Buttons block implementation. ## Symbols def request_input_buttons — Request a selection from a set of buttons. # request_input_buttons ``` request_input_buttons( options: list[str], label: str | None = None, ) → str ``` Request a selection from a set of buttons. ## Parameters options type: list[str] Values offered for selection. label type: str | None = None Optional prompt shown above the buttons. ## Returns type: str Block ID identifying the input request. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/date_picker/ # yera.runtime.blocks.date_picker Date picker block implementation. ## Symbols def request_input_date_picker — Request a calendar date. # request_input_date_picker ``` request_input_date_picker( label: str, default_date: date | str | None = None, ) → str ``` Request a calendar date. ## Parameters label type: str Prompt shown alongside the picker. default_date type: date | str | None = None Optional initial date. ## Returns type: str Block ID identifying the input request. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/exit/ # yera.runtime.blocks.exit Exit block implementation. ## Symbols def quit_event — Push a success exit event for a user-initiated quit. def unsupported_block_event — Push an exit event for an unsupported await_user block (e.g. form). # quit_event ``` quit_event() → None ``` Push a success exit event for a user-initiated quit. # unsupported_block_event ``` unsupported_block_event( block_type: str, ) → None ``` Push an exit event for an unsupported await_user block (e.g. form). Block factories use this when is_restricted_stream() is True, then raise UnsupportedAwaitUserBlockError. Uses exit_event() so the event has the correct app_instance from the current context. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/form/ # yera.runtime.blocks.form Form request and form echo block implementations. ## Symbols def request_input_form — Request one typed form submission for a model's fields. # request_input_form ``` request_input_form( model_type: type[BaseModel], label: str | None = None, values: dict[str, JsonValue] | None = None, errors: dict[str, list[str]] | None = None, ) → str ``` Request one typed form submission for a model's fields. ## Parameters model_type type: type[BaseModel] Model or struct class whose fields the form presents. label type: str | None = None Optional question shown above the form. values type: dict[str, JsonValue] | None = None JSON values pre-filling the form, keyed by field name. errors type: dict[str, list[str]] | None = None Validation messages from a rejected submission, keyed by dotted field path. ## Returns type: str Block ID identifying the input request. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/image/ # yera.runtime.blocks.image Image block implementation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/input_echo/ # yera.runtime.blocks.input_echo Input echo block implementation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/input_request/ # yera.runtime.blocks.input_request Input request implementation. ## Symbols def request_input_text — Request free-text input. # request_input_text ``` request_input_text( message: str | None = None, ) → str ``` Request free-text input. ## Parameters message type: str | None = None Optional prompt shown to the user. ## Returns type: str Block ID identifying the input request. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/line_chart/ # yera.runtime.blocks.line_chart Line chart block implementation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/markdown/ # yera.runtime.blocks.markdown Markdown block implementation. ## Symbols class MarkdownStream — Stream handle for creating multiple chunks of the same markdown block. # MarkdownStream Inherits: `_StreamHandle` Stream handle for creating multiple chunks of the same markdown block. ## Methods __enter__ — __exit__ — append — Append a new chunk to this markdown block. new_line — Append a new line to this markdown block. # MarkdownStream.__enter__ ``` __enter__() ``` # MarkdownStream.__exit__ ``` __exit__( exc_type: type[BaseException], exc_value: BaseException | None, traceback: TracebackType, ) ``` # MarkdownStream.append ``` append( content: str, ) → None ``` Append a new chunk to this markdown block. # MarkdownStream.new_line ``` new_line( content: str, ) → None ``` Append a new line to this markdown block. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/result/ # yera.runtime.blocks.result Result block implementation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/section/ # yera.runtime.blocks.section Collapsible section block implementation. ## Symbols class Section — Mutable context manager that groups related output blocks. # Section Inherits: `_StreamHandle` Mutable context manager that groups related output blocks. A section establishes itself as the parent of blocks emitted within its context. Its title, glyph, and colour can be updated while it is open. Calling `success()` or `error()` applies the corresponding standard appearance without closing the context. Section objects are created through `yera.section` rather than instantiated directly. ## Methods __enter__ — Open the section scope and emit its structural metadata. __exit__ — Close the section after all nested blocks have finished. update — Update the section's current visual state. success — Apply the standard successful section appearance. error — Apply the standard erroneous section appearance. # Section.__enter__ ``` __enter__() → Section ``` Open the section scope and emit its structural metadata. # Section.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) → bool ``` Close the section after all nested blocks have finished. # Section.update ``` update( title: str | None = None, glyph: str | None = None, colour: NamedColour | Literal['default'] | None = None, ) → None ``` Update the section's current visual state. Every update emits a complete section snapshot while retaining properties that were not supplied. Passing `"default"` as the colour restores the section's default neutral appearance. ## Parameters title type: str | None = None Replacement title, or `None` to retain the current title. glyph type: str | None = None Replacement registered glyph, or `None` to retain the current glyph. colour type: NamedColour | Literal['default'] | None = None Replacement named colour, `"default"` to restore the neutral appearance, or `None` to retain the current colour. ## Raises RuntimeError If the section is not currently open. ValueError If the requested glyph is not registered. # Section.success ``` success( title: str | None = None, ) → None ``` Apply the standard successful section appearance. The section remains open and may continue receiving child output. If no title is supplied, its current title is preserved. ## Parameters title type: str | None = None Optional replacement title. # Section.error ``` error( title: str | None = None, ) → None ``` Apply the standard erroneous section appearance. The section remains open and may continue receiving child output. If no title is supplied, its current title is preserved. ## Parameters title type: str | None = None Optional replacement title. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/slider/ # yera.runtime.blocks.slider Slider block implementation. ## Symbols def request_input_slider — Request a numeric value from a bounded slider. # request_input_slider ``` request_input_slider( min_value: float, max_value: float, label: str, default_value: float | None = None, ) → str ``` Request a numeric value from a bounded slider. ## Parameters min_value type: float Lower bound of the slider. max_value type: float Upper bound of the slider. label type: str Prompt shown alongside the slider. default_value type: float | None = None Optional initial value. ## Returns type: str Block ID identifying the input request. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/spinner/ # yera.runtime.blocks.spinner Spinner block implementation. ## Symbols class SpinnerStream — Stream handle for creating multiple chunks of the same spinner block. # SpinnerStream Inherits: `_StreamHandle` Stream handle for creating multiple chunks of the same spinner block. ## Methods __enter__ — __exit__ — update — Update any supplied part of the spinner's active state. fail — Resolve the spinner with a failed terminal appearance. # SpinnerStream.__enter__ ``` __enter__() ``` # SpinnerStream.__exit__ ``` __exit__( exc_type: type[BaseException], exc_value: BaseException | None, traceback: TracebackType, ) ``` # SpinnerStream.update ``` update( message: str | None = None, glyph: str | None = None, colour: NamedColour | None = None, ) → None ``` Update any supplied part of the spinner's active state. ## Parameters message type: str | None = None Replacement message, or `None` to retain the current one. glyph type: str | None = None Replacement glyph, or `None` to retain the current one. colour type: NamedColour | None = None Replacement colour, or `None` to retain the current one. # SpinnerStream.fail ``` fail( message: str = 'Failed', ) → None ``` Resolve the spinner with a failed terminal appearance. Calling this method does not raise an exception or end the surrounding block immediately. The failed state is emitted when the spinner context exits, allowing callers to handle expected failures without exception-based control flow. ## Parameters message type: str = 'Failed' Message shown in the failed terminal state. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/startup/ # yera.runtime.blocks.startup Session metadata block implementation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/struct/ # yera.runtime.blocks.struct Module implementing struct gen streaming functionality for Yera runtime blocks. ## Symbols class StructStream — # StructStream Inherits: `_StreamHandle` ## Methods __enter__ — __exit__ — emit_schema — append — # StructStream.__enter__ ``` __enter__() ``` # StructStream.__exit__ ``` __exit__( exc_type: type[BaseException], exc_value: BaseException | None, traceback: TracebackType, ) ``` # StructStream.emit_schema ``` emit_schema() → None ``` # StructStream.append ``` append( content: str, ) → None ``` --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/system_prompt/ # yera.runtime.blocks.system_prompt System prompt block implementation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/table/ # yera.runtime.blocks.table Table block implementation. ## Symbols class TableStream — Stream handle for a table block that supports incremental row additions. # TableStream Inherits: `_StreamHandle` Stream handle for a table block that supports incremental row additions. Returned by `yr.table()` to enable `add_rows()` functionality. Maintains table metadata (columns, border, block_id) and streams incremental row updates to the frontend. The frontend accumulates these rows to build the complete table state. ## Methods add_rows — Add rows to the table, matching Streamlit's element.add_rows() behavior. __enter__ — __exit__ — # TableStream.add_rows ``` add_rows( data: object, ) → None ``` Add rows to the table, matching Streamlit's element.add_rows() behavior. The first call to an empty table fixes the column schema from the incoming data; later calls align to it. Supports: - list of lists: each inner list is a row - list of dicts: each dict becomes a row (keys should match existing columns) - pandas DataFrame: adds all rows - single list: treated as a single row # TableStream.__enter__ ``` __enter__() ``` # TableStream.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType, ) ``` --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/thinking/ # yera.runtime.blocks.thinking Module providing runtime block and stream implementation for the “thinking” events. ## Symbols class ThinkingStream — # ThinkingStream Inherits: `_StreamHandle` ## Methods __enter__ — __exit__ — append — # ThinkingStream.__enter__ ``` __enter__() ``` # ThinkingStream.__exit__ ``` __exit__( exc_type: type[BaseException], exc_value: BaseException | None, traceback: TracebackType, ) ``` # ThinkingStream.append ``` append( content: str, ) → None ``` --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/blocks/tree_selector/ # yera.runtime.blocks.tree_selector Tree selector block implementation. ## Symbols def request_input_tree_selector — Request selections from the leaves of a nested tree. # request_input_tree_selector ``` request_input_tree_selector( tree: Mapping[str, object], label: str | None = None, min_selections: int = 1, max_selections: int | None = None, ) → str ``` Request selections from the leaves of a nested tree. ## Parameters tree type: Mapping[str, object] Normalized nested branches and canonical leaf values. label type: str | None = None Optional prompt shown above the tree. min_selections type: int = 1 Minimum number of leaves that must be selected. max_selections type: int | None = None Optional maximum number of leaves that may be selected. ## Returns type: str Block ID identifying the input request. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/exceptions/ # yera.runtime.exceptions Event-related exceptions. ## Symbols class InputProtocolError — Base error for an invalid input protocol transition. class InputRequestMismatchError — Raised when a response targets a different input request. class InputTypeMismatchError — Raised when a response carries the wrong typed input data. class InputValueError — Raised when submitted input is invalid for its request. class UnsupportedAwaitUserBlockError — Raised when the built-in stream handler encounters an await_user block other than text input. # InputProtocolError Inherits: `Exception` Subclasses: `InputRequestMismatchError`, `InputTypeMismatchError`, `InputValueError` Base error for an invalid input protocol transition. # InputRequestMismatchError Inherits: `InputProtocolError` Raised when a response targets a different input request. # InputTypeMismatchError Inherits: `InputProtocolError` Raised when a response carries the wrong typed input data. # InputValueError Inherits: `InputProtocolError` Raised when submitted input is invalid for its request. # UnsupportedAwaitUserBlockError Inherits: `Exception` Raised when the built-in stream handler encounters an await_user block other than text input. The built-in stream handler (used when the app is invoked directly, not via the stream server) only supports input_request. For buttons, slider, date picker forms, etc., run the app using the dev server (web UI) via the `yera` CLI. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/form_widgets/ # yera.runtime.form_widgets Map JSON Schema nodes onto form input widgets. ## Symbols def field_label — Return the label shown for a form field. def form_schema — Describe a model's fields for form rendering. def inline_refs — Replace local ``$ref`` pointers with the definitions they name. def redact_secrets — Mask every secret value in a submitted form. def repeat_item_label — Return the noun for one row of a repeated field. def struct_variants — Return the struct members of a union field. def unwrap_optional — Return the value schema of an optional field. def variant_constant — Return the constant a struct union member fixes for a field. def variant_discriminator — Return the constant field shared by every member of a struct union. def widget_for — Choose the input widget presenting one schema property. # field_label ``` field_label( node: Mapping[str, JsonValue], path: str, ) → str ``` Return the label shown for a form field. ## Parameters node type: Mapping[str, JsonValue] The field's schema node. path type: str Dotted path of the field within the form. ## Returns type: str The node's explicit title, or the last path segment with underscores replaced by spaces. # form_schema ``` form_schema( model_type: type[BaseModel], ) → dict[str, JsonValue] ``` Describe a model's fields for form rendering. ## Parameters model_type type: type[BaseModel] Pydantic model or struct class declaring the form fields. ## Returns type: dict[str, JsonValue] The model's JSON Schema with references inlined, keeping only the titles declared explicitly on its fields. ## Raises ValueError If the model's fields refer back to the model itself. # inline_refs ``` inline_refs( schema: Mapping[str, JsonValue], ) → dict[str, JsonValue] ``` Replace local `$ref` pointers with the definitions they name. ## Parameters schema type: Mapping[str, JsonValue] A JSON Schema whose references point into its `$defs`. ## Returns type: dict[str, JsonValue] A copy of the schema without `$defs` in which every reference is replaced by its definition. Keys beside a reference take precedence, and a definition's type `title` is not copied onto the field. ## Raises ValueError If a definition refers back to itself. # redact_secrets ``` redact_secrets( values: Mapping[str, JsonValue], schema: Mapping[str, JsonValue], ) → dict[str, JsonValue] ``` Mask every secret value in a submitted form. ## Parameters values type: Mapping[str, JsonValue] Submitted JSON values keyed by field name. schema type: Mapping[str, JsonValue] Inlined form schema describing those values. ## Returns type: dict[str, JsonValue] A copy of the values in which every write-only field holds the mask. # repeat_item_label ``` repeat_item_label( node: Mapping[str, JsonValue], ) → str ``` Return the noun for one row of a repeated field. ## Parameters node type: Mapping[str, JsonValue] A list field's schema node. ## Returns type: str The field's `ui.item_label`, or `"row"` when it sets none. # struct_variants ``` struct_variants( node: Mapping[str, JsonValue], ) → list[Mapping[str, JsonValue]] ``` Return the struct members of a union field. ## Parameters node type: Mapping[str, JsonValue] An inlined schema node declaring `oneOf` or `anyOf` members. ## Returns type: list[Mapping[str, JsonValue]] The members that describe structs, in declaration order. # unwrap_optional ``` unwrap_optional( node: Mapping[str, JsonValue], ) → Mapping[str, JsonValue] | None ``` Return the value schema of an optional field. ## Parameters node type: Mapping[str, JsonValue] A resolved JSON Schema property node. ## Returns type: Mapping[str, JsonValue] | None The non-null member of a `T | None` union, or `None` when the node is not an optional single type. # variant_constant ``` variant_constant( member: Mapping[str, JsonValue], key: str, ) → JsonValue ``` Return the constant a struct union member fixes for a field. ## Parameters member type: Mapping[str, JsonValue] One struct member of a union field. key type: str The discriminating field name. ## Returns type: JsonValue The member's constant for that field, or `None` when it has none. # variant_discriminator ``` variant_discriminator( members: list[Mapping[str, JsonValue]], ) → str | None ``` Return the constant field shared by every member of a struct union. ## Parameters members type: list[Mapping[str, JsonValue]] Struct members of a union field. ## Returns type: str | None The alphabetically first field that every member fixes to a constant, or `None` when the members share none. # widget_for ``` widget_for( node: Mapping[str, JsonValue], ) → Widget ``` Choose the input widget presenting one schema property. ## Parameters node type: Mapping[str, JsonValue] A resolved JSON Schema property node. ## Returns type: Widget The widget kind used to present the property. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/glyphs/ # yera.runtime.glyphs Named SVG glyphs used by HTMX renderers. ## Symbols def glyph — Render a named Yera glyph as SVG markup. def validate_glyph — Validate and return a registered Yera glyph name. # glyph ``` glyph( name: str, ) → str ``` Render a named Yera glyph as SVG markup. ## Parameters name type: str Registered glyph name. ## Returns type: str SVG markup for the requested glyph. ## Raises ValueError If the glyph name is not registered. # validate_glyph ``` validate_glyph( name: str, ) → str ``` Validate and return a registered Yera glyph name. ## Parameters name type: str Glyph name to validate. ## Returns type: str The validated glyph name. ## Raises ValueError If the glyph name is not registered. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/ # yera.runtime.handlers Submodule containing event handlers for the Yera runtime. These are responsible for displaying the event, receiving input etc. Generally, there are three different types - Kitty handlers that can display media such as images in the terminal - Ordinary ANSI terminal - Jupyter runtimes ## Submodules base fallback form form_echo image markdown registry result segment tree_selector --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/base/ # yera.runtime.handlers.base Abstract base class for Yera event handlers. ## Symbols class BaseHandler — Abstract base for all Yera event handlers. # BaseHandler Inherits: `ABC` Subclasses: `FallbackHandler`, `ANSIFormEchoHandler`, `JupyterFormEchoHandler`, `ANSITreeSelectorHandler`, `JupyterTreeSelectorHandler`, `ANSIResultHandler`, `ANSIImageHandler`, `JupyterImageHandler`, `BaseMarkdownHandler`, `ANSIFormHandler`, `JupyterFormHandler` Abstract base for all Yera event handlers. Each handler is responsible for processing events of a single block type. Handlers are used as context managers so that stateful implementations (e.g. a streaming markdown handler managing a live display) can acquire and release resources around a block. The default `__enter__` and `__exit__` are no-ops; override them only when setup or teardown is required. ## Methods bind_parent — Attach the handler owning this block's parent, if any. __enter__ — Enter the handler context. No-op by default. __exit__ — Exit the handler context. No-op by default. push — Handle an event. # BaseHandler.bind_parent ``` bind_parent( parent: BaseHandler | None, ) → None ``` Attach the handler owning this block's parent, if any. Called by the router once, before `__enter__`. `None` at top level or when the parent block has already closed. ## Parameters parent type: BaseHandler | None The enclosing block's handler. # BaseHandler.__enter__ ``` __enter__() → Self ``` Enter the handler context. No-op by default. # BaseHandler.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) → None ``` Exit the handler context. No-op by default. # BaseHandler.push ``` push( event: OutputEvent, ) → None ``` Handle an event. Called once per event in the block, in order. Stateful handlers accumulate state across repeated calls within a single context manager scope. ## Parameters event type: OutputEvent The output event to handle. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/fallback/ # yera.runtime.handlers.fallback Fallback handler: pretty-prints unrecognised event blocks as JSON. ## Symbols class FallbackHandler — Renders unregistered block types by printing their JSON payload to the console. # FallbackHandler Inherits: `BaseHandler` Renders unregistered block types by printing their JSON payload to the console. ## Methods push — Print the block type warning and JSON-serialised event data to the console. # FallbackHandler.push ``` push( event: OutputEvent, ) → None ``` Print the block type warning and JSON-serialised event data to the console. ## Parameters event type: OutputEvent The unrecognised output event to render. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/form/ # yera.runtime.handlers.form HTMX handlers for form requests. ## Submodules ansi htmx jupyter --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/form/ansi/ # yera.runtime.handlers.form.ansi ANSI form handler: asks each field of a form at the terminal. ## Symbols class ANSIFormHandler — Asks for each field of a form at the terminal and submits the answers. # ANSIFormHandler Inherits: `BaseHandler` Asks for each field of a form at the terminal and submits the answers. ## Methods push — Ask the form's questions and submit the answers. # ANSIFormHandler.push ``` push( event: OutputEvent, ) → None ``` Ask the form's questions and submit the answers. ## Parameters event type: OutputEvent An output event carrying `FormData`. ## Raises TypeError If the event data is not `FormData`. ValueError If the user cancels a question. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/form/htmx/ # yera.runtime.handlers.form.htmx HTMX form handler: presents a struct form inside the shared composer. ## Symbols class HTMXFormHandler — Render a form request as fields inside the shared input composer. # HTMXFormHandler Inherits: `BaseHTMXHandler` Render a form request as fields inside the shared input composer. ## Methods push — Render the form request. # HTMXFormHandler.push ``` push( event: OutputEvent, ) → None ``` Render the form request. ## Parameters event type: OutputEvent An output event carrying `FormData`. ## Raises TypeError If the event data is not `FormData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/form/jupyter/ # yera.runtime.handlers.form.jupyter Jupyter form handler (stopgap): asks each field of a form via stdin. ## Symbols class JupyterFormHandler — Asks for each field of a form via the notebook's stdin and submits the answers. # JupyterFormHandler Inherits: `BaseHandler` Asks for each field of a form via the notebook's stdin and submits the answers. ## Methods push — Ask the form's questions and submit the answers. # JupyterFormHandler.push ``` push( event: OutputEvent, ) → None ``` Ask the form's questions and submit the answers. ## Parameters event type: OutputEvent An output event carrying `FormData`. ## Raises TypeError If the event data is not `FormData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/form_echo/ # yera.runtime.handlers.form_echo HTMX handlers for form echoes. ## Submodules ansi htmx jupyter --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/form_echo/ansi/ # yera.runtime.handlers.form_echo.ansi ANSI form echo handler: prints one form submission at the terminal. ## Symbols class ANSIFormEchoHandler — Prints a form submission's outcome and its visible answers. # ANSIFormEchoHandler Inherits: `BaseHandler` Prints a form submission's outcome and its visible answers. ## Methods push — Print the form echo. # ANSIFormEchoHandler.push ``` push( event: OutputEvent, ) → None ``` Print the form echo. ## Parameters event type: OutputEvent An output event carrying `FormEchoData`. ## Raises TypeError If the event data is not `FormEchoData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/form_echo/htmx/ # yera.runtime.handlers.form_echo.htmx HTMX form echo handler: records one form submission in the transcript. ## Symbols class HTMXFormEchoHandler — Render a form submission as a collapsible, read-only transcript card. # HTMXFormEchoHandler Inherits: `BaseHTMXHandler` Render a form submission as a collapsible, read-only transcript card. ## Methods push — Render the form echo. # HTMXFormEchoHandler.push ``` push( event: OutputEvent, ) → None ``` Render the form echo. ## Parameters event type: OutputEvent An output event carrying `FormEchoData`. ## Raises TypeError If the event data is not `FormEchoData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/form_echo/jupyter/ # yera.runtime.handlers.form_echo.jupyter Jupyter form echo handler: displays one form submission as a chat bubble. ## Symbols class JupyterFormEchoHandler — Displays a form submission's outcome and its visible answers. # JupyterFormEchoHandler Inherits: `BaseHandler` Displays a form submission's outcome and its visible answers. ## Methods push — Display the form echo. # JupyterFormEchoHandler.push ``` push( event: OutputEvent, ) → None ``` Display the form echo. ## Parameters event type: OutputEvent An output event carrying `FormEchoData`. ## Raises TypeError If the event data is not `FormEchoData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/image/ # yera.runtime.handlers.image Image output handlers. ## Submodules ansi htmx jupyter kitty --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/image/ansi/ # yera.runtime.handlers.image.ansi ANSI handler for image output. ## Symbols class ANSIImageHandler — Render a concise image placeholder in unsupported terminals. # ANSIImageHandler Inherits: `BaseHandler` Subclasses: `KittyImageHandler` Render a concise image placeholder in unsupported terminals. ## Methods push — Render an image event as a textual placeholder. # ANSIImageHandler.push ``` push( event: OutputEvent, ) → None ``` Render an image event as a textual placeholder. ## Parameters event type: OutputEvent Output event carrying encoded image data. ## Raises TypeError If the event does not carry image data. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/image/htmx/ # yera.runtime.handlers.image.htmx HTMX handler for image output. ## Symbols class HTMXImageHandler — Render encoded image data as a responsive HTML image. # HTMXImageHandler Inherits: `BaseHTMXHandler` Render encoded image data as a responsive HTML image. ## Methods push — Render an image event. # HTMXImageHandler.push ``` push( event: OutputEvent, ) → None ``` Render an image event. ## Parameters event type: OutputEvent Output event carrying encoded image data. ## Raises TypeError If the event does not carry image data. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/image/jupyter/ # yera.runtime.handlers.image.jupyter Jupyter handler for image output. ## Symbols class JupyterImageHandler — Render encoded image data in a Jupyter notebook. # JupyterImageHandler Inherits: `BaseHandler` Render encoded image data in a Jupyter notebook. ## Methods push — Render an image event. # JupyterImageHandler.push ``` push( event: OutputEvent, ) → None ``` Render an image event. ## Parameters event type: OutputEvent Output event carrying encoded image data. ## Raises TypeError If the event does not carry image data. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/image/kitty/ # yera.runtime.handlers.image.kitty Kitty handler for image output. ## Symbols class KittyImageHandler — Render raster images through the Kitty graphics protocol. # KittyImageHandler Inherits: `ANSIImageHandler` Render raster images through the Kitty graphics protocol. ## Methods push — Render an image event in a Kitty terminal. # KittyImageHandler.push ``` push( event: OutputEvent, ) → None ``` Render an image event in a Kitty terminal. Supported raster formats are converted to PNG before being sent through the Kitty graphics protocol. SVG images and invalid raster content use a textual fallback. ## Parameters event type: OutputEvent Output event carrying encoded image data. ## Raises TypeError If the event does not carry image data. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/markdown/ # yera.runtime.handlers.markdown Submodule containing the markdown handlers for the different env types + their base class. ## Submodules ansi base htmx jupyter kitty --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/markdown/ansi/ # yera.runtime.handlers.markdown.ansi ANSI markdown handler: Rich rendering with LaTeX rendered as Unicode text. For terminals that support ANSI escapes (colour, cursor movement) but not the Kitty graphics protocol. Inherits all text/code/live rendering from the TTY handler; the only differences are LaTeX (converted to Unicode via pylatexenc instead of rasterised) and images (shown as a styled reference line, since there is no way to paint pixels). ## Symbols class ANSIMarkdownHandler — Markdown handler for ANSI terminals without graphics support. # ANSIMarkdownHandler Inherits: `KittyMarkdownHandler` Markdown handler for ANSI terminals without graphics support. Renders markdown and code via Rich (inherited from `TTYMarkdownHandler`) and converts display LaTeX to Unicode with pylatexenc. The converter is built lazily on first use and reused. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/markdown/base/ # yera.runtime.handlers.markdown.base Abstract base class for streaming markdown event handlers. ## Symbols class BaseMarkdownHandler — Abstract base for streaming markdown block handlers. # BaseMarkdownHandler Inherits: `BaseHandler` Subclasses: `KittyMarkdownHandler`, `JupyterMarkdownHandler` Abstract base for streaming markdown block handlers. Manages buffer state and commit logic for streaming markdown content, delegating environment-specific rendering to subclasses via abstract primitive methods. Handles code blocks and display math detection in addition to plain markdown. Subclasses must implement `_render_markdown`, `_render_code`, `_render_latex`, `_push_buffer_to_live`, `_clear_live`, and `_print_blank_line`. ## Methods __enter__ — Enter the block context and emit an opening blank line. __exit__ — Flush remaining buffer, emit a closing blank line, and reset state. push — Append a markdown chunk and flush any completed blocks. # BaseMarkdownHandler.__enter__ ``` __enter__() → Self ``` Enter the block context and emit an opening blank line. # BaseMarkdownHandler.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) → None ``` Flush remaining buffer, emit a closing blank line, and reset state. # BaseMarkdownHandler.push ``` push( event: OutputEvent, ) → None ``` Append a markdown chunk and flush any completed blocks. ## Parameters event type: OutputEvent A markdown output event whose data carries the next chunk. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/markdown/htmx/ # yera.runtime.handlers.markdown.htmx Streaming markdown handler for the HTMX target. ## Symbols class HTMXMarkdownHandler — Render a streaming Markdown block through incremental morph swaps. # HTMXMarkdownHandler Inherits: `BaseHTMXHandler` Render a streaming Markdown block through incremental morph swaps. Settled Markdown prefixes are committed as immutable segments while the live tail is repeatedly rendered and replaced. A trailing table is rendered through the shared Markdown renderer as soon as its header and delimiter are complete, while an unfinished final row is withheld until more input arrives. This keeps streaming output stable without giving tables, mathematics, or other inline Markdown a separate rendering path. ## Methods __exit__ — Flush the tail unthrottled and unconditionally. push — Append a chunk; publish at most one swap every ``_MIN_FRAME_S``. # HTMXMarkdownHandler.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) ``` Flush the tail unthrottled and unconditionally. The last chunk's swap may have been coalesced away, and `render_streaming_markdown` holds back an in-progress table row that only a full render releases. # HTMXMarkdownHandler.push ``` push( event: OutputEvent, ) → None ``` Append a chunk; publish at most one swap every `_MIN_FRAME_S`. ## Parameters event type: OutputEvent An output event carrying `MarkdownData`. ## Raises TypeError If the event data is not `MarkdownData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/markdown/jupyter/ # yera.runtime.handlers.markdown.jupyter Jupyter markdown handler: native frontend rendering for streaming markdown. ## Symbols class JupyterMarkdownHandler — Streaming markdown handler that renders through the Jupyter frontend. # JupyterMarkdownHandler Inherits: `BaseMarkdownHandler` Streaming markdown handler that renders through the Jupyter frontend. Unlike the TTY handler, nothing is rasterised kernel-side: markdown, code highlighting, LaTeX (MathJax) and images are all handed to the notebook frontend. In-progress content streams into a single updating display handle; finished blocks are committed as permanent outputs above it. Code blocks are accumulated and emitted as one display per fenced block (rather than per line, as the terminal does), so a streamed code block renders as a single highlighted box instead of a stack of separate ones. ## Methods __exit__ — Flush via the base, then commit code left over by an unterminated block. # JupyterMarkdownHandler.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) → None ``` Flush via the base, then commit code left over by an unterminated block. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/markdown/kitty/ # yera.runtime.handlers.markdown.kitty TTY markdown handler: Rich rendering with Kitty graphics protocol for LaTeX. ## Symbols class KittyMarkdownHandler — Markdown handler for TTY terminals supporting Rich and the Kitty graphics protocol. # KittyMarkdownHandler Inherits: `BaseMarkdownHandler` Subclasses: `ANSIMarkdownHandler` Markdown handler for TTY terminals supporting Rich and the Kitty graphics protocol. Renders markdown and code blocks using Rich, displays in-progress content via a transient `Live` display, and rasterises LaTeX expressions to PNG via Matplotlib before emitting them using the Kitty terminal graphics protocol. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/registry/ # yera.runtime.handlers.registry Handler registry and render-environment detection for the Yera event rendering. ## Symbols def detect_render_env — Detect the rendering environment for the current process. class EventHandlerRegistry — Maps block-type names to factories that construct their handlers. class RenderEnv — Supported rendering environments for console output. # detect_render_env ``` detect_render_env() → RenderEnv ``` Detect the rendering environment for the current process. Checks, in order: YERA_RENDERER env-var override, Jupyter kernel, Kitty-protocol terminal, then falls back to plain ANSI. ## Returns type: RenderEnv The detected RenderEnv. # EventHandlerRegistry Maps block-type names to factories that construct their handlers. ## Methods create — Construct a fresh handler for a single block. build — Build a registry for the given target, auto-detecting if unspecified. # EventHandlerRegistry.create ``` create( block_type: str, ) → BaseHandler ``` Construct a fresh handler for a single block. A handler's lifetime is one block: the router constructs it when the block opens and discards it when the block ends. Handlers therefore hold per-block state directly rather than resetting it in `__enter__`. ## Parameters block_type type: str The event block type to look up. ## Returns type: BaseHandler A new handler, or a new fallback handler if unregistered. # EventHandlerRegistry.build ``` build( env: RenderEnv | None = None, console: Console | None = None, web_render: WebRenderContext | None = None, ) → EventHandlerRegistry ``` Build a registry for the given target, auto-detecting if unspecified. ## Parameters env type: RenderEnv | None = None Force a target. Defaults to auto-detection (env var override, then Jupyter, then Kitty, then ANSI). console type: Console | None = None The rich console object to use when printing to screen etc. web_render type: WebRenderContext | None = None The render context to use when handling events -> HTMX. # RenderEnv Inherits: `Enum` Supported rendering environments for console output. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/result/ # yera.runtime.handlers.result Handlers and rendering support for result blocks. ## Submodules ansi htmx result_render --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/result/ansi/ # yera.runtime.handlers.result.ansi Render completed result blocks in ANSI terminals. ## Symbols class ANSIResultHandler — Render completed successful and failed results in ANSI terminals. # ANSIResultHandler Inherits: `BaseHandler` Render completed successful and failed results in ANSI terminals. Successful values are displayed as syntax-highlighted JSON so their serialized types and nested structure remain visible. Failed results show the exception type and message, with the captured traceback when one is available. ## Methods push — Render a completed result event. # ANSIResultHandler.push ``` push( event: OutputEvent, ) → None ``` Render a completed result event. ## Parameters event type: OutputEvent Output event containing successful or failed result data. ## Raises TypeError If the event does not contain supported result data. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/result/htmx/ # yera.runtime.handlers.result.htmx HTMX handler for completed result disclosures. ## Symbols class HTMXResultHandler — Render a completed result as a configurable one-shot disclosure. # HTMXResultHandler Inherits: `BaseHTMXHandler` Render a completed result as a configurable one-shot disclosure. ## Methods push — Render a successful or error result event. # HTMXResultHandler.push ``` push( event: OutputEvent, ) → None ``` Render a successful or error result event. ## Parameters event type: OutputEvent Output event carrying a result data variant. ## Raises TypeError If the event does not carry result data. ValueError If the configured glyph is not registered. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/result/result_render/ # yera.runtime.handlers.result.result_render Render persisted result values through the shared typed-data grammar. ## Symbols class ResultRenderer — Adapt a completed persisted result to the shared typed-data renderer. # ResultRenderer Adapt a completed persisted result to the shared typed-data renderer. ## Methods body — Render the result's structured body. raw — Render the result's syntax-highlighted raw JSON view. # ResultRenderer.body ``` body() → str ``` Render the result's structured body. # ResultRenderer.raw ``` raw() → str ``` Render the result's syntax-highlighted raw JSON view. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/segment/ # yera.runtime.handlers.segment Split a streaming markdown buffer into a settled prefix and a live tail. ## Symbols def harvest_refdefs — Extract link reference definitions from committed markdown. def split_settled — Split a streaming buffer into a committable prefix and a live tail. # harvest_refdefs ``` harvest_refdefs( text: str, ) → list[str] ``` Extract link reference definitions from committed markdown. Definitions emit no HTML but bind names used later, so replaying them into each subsequent segment costs nothing and keeps a `[foo]` in segment 3 resolvable against a definition committed in segment 0. ## Parameters text type: str A settled markdown region. ## Returns type: list[str] The refdef source lines, stripped, in document order. # split_settled ``` split_settled( buffer: str, ) → tuple[str, str] ``` Split a streaming buffer into a committable prefix and a live tail. The prefix is the largest region ending at a blank line that renders identically in isolation as it would in the whole document. Blank lines inside fences, display math, lists, or indented code are not split points: a later chunk can still change how the text above them renders. Deciding a blank line closed a block needs the next line, complete — a partial `2` is not an ordered-list marker but `2.` is, so classifying a line still arriving would split a list in two. A buffer whose lookahead is absent or unterminated therefore commits nothing. ## Parameters buffer type: str Markdown accumulated so far. May end mid-line. ## Returns type: str A `(settled, live)` pair concatenating back to `buffer`. `settled` is `""` when nothing can be committed yet. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/tree_selector/ # yera.runtime.handlers.tree_selector Tree selector event handlers. ## Submodules ansi htmx jupyter --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/tree_selector/ansi/ # yera.runtime.handlers.tree_selector.ansi ANSI tree selector handler. ## Symbols class ANSITreeSelectorHandler — Render an interactive multi-select tree in an ANSI terminal. # ANSITreeSelectorHandler Inherits: `BaseHandler` Render an interactive multi-select tree in an ANSI terminal. ## Methods push — Display the tree and submit the selected leaf values. # ANSITreeSelectorHandler.push ``` push( event: OutputEvent, ) → None ``` Display the tree and submit the selected leaf values. ## Parameters event type: OutputEvent An output event carrying `TreeSelectorData`. ## Raises TypeError If the event data is not `TreeSelectorData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/tree_selector/htmx/ # yera.runtime.handlers.tree_selector.htmx HTMX tree selector handler. ## Symbols class HTMXTreeSelectorHandler — Render a nested multi-select tree in the shared input composer. # HTMXTreeSelectorHandler Inherits: `BaseHTMXHandler` Render a nested multi-select tree in the shared input composer. ## Methods push — Render the tree selection request. # HTMXTreeSelectorHandler.push ``` push( event: OutputEvent, ) → None ``` Render the tree selection request. ## Parameters event type: OutputEvent An output event carrying `TreeSelectorData`. ## Raises TypeError If the event data is not `TreeSelectorData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/handlers/tree_selector/jupyter/ # yera.runtime.handlers.tree_selector.jupyter Jupyter tree selector handler. ## Symbols class JupyterTreeSelectorHandler — Render a numbered tree and collect multiple selections in Jupyter. # JupyterTreeSelectorHandler Inherits: `BaseHandler` Render a numbered tree and collect multiple selections in Jupyter. ## Methods push — Display the tree and submit validated selected leaf values. # JupyterTreeSelectorHandler.push ``` push( event: OutputEvent, ) → None ``` Display the tree and submit validated selected leaf values. ## Parameters event type: OutputEvent An output event carrying `TreeSelectorData`. ## Raises TypeError If the event data is not `TreeSelectorData`. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/matplotlib/ # yera.runtime.matplotlib Infrastructure for integrating Yera with the matplotlib backend. ## Submodules backend main theme --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/matplotlib/backend/ # yera.runtime.matplotlib.backend Render Matplotlib figures through Yera image events. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/matplotlib/main/ # yera.runtime.matplotlib.main Activate Yera's Matplotlib backend inside an app process. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/matplotlib/theme/ # yera.runtime.matplotlib.theme Define Yera's Matplotlib presentation theme. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/models/ # yera.runtime.models Data models for events blocks. ## Submodules block_data event_class in_event input_data input_spec out_event --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/models/block_data/ # yera.runtime.models.block_data Block data models for events blocks. ## Symbols class BarChartData — Bar chart block data. class BlockEndData — Control event marking the structural end of a block. class ButtonsData — Button group block data with options and optional label. class DatePickerData — Date picker block data with value and label. class ErrorResultData — Serialized data for an error result block. class ErrorResultDetails — Normalized details captured from an exception. class FailureExitEventData — Exit event data for failed app execution (exit_code != 0). class FormData — A form request presenting a struct's fields for one typed submission. class FormEchoData — The outcome of one form submission, recorded in the transcript. class ImageData — Describe encoded image content carried by an output event. class InputEchoData — An accepted input response that terminally commits its request. class InputRequestBlockData — Data shared by blocks that request a single input value. class InputRequestData — Input request block data for awaiting user text input. class LineChartData — Line chart block data. class MarkdownData — Markdown content block data. class SectionData — Structural and visual state for a collapsible section. class SessionMetaData — A partial session metadata update emitted by a runtime or host. class SliderData — Slider block data with range, initial value, and label. class SpinnerData — Spinner block data with status and optional message. class StructData — Struct data for structured generation responses. class SuccessExitEventData — Exit event data for successful app completion (exit_code 0). class SuccessResultData — Serialized data for a successful result block. class SystemPromptData — System prompt block data. class TableData — Table block data with columns, rows, and border style. class ThinkingData — Thinking content block data. class TreeSelectorData — Tree selector request containing nested selectable leaves. # BarChartData Inherits: `BaseModel` Bar chart block data. # BlockEndData Inherits: `BaseModel` Control event marking the structural end of a block. Distinct from semantic completion (e.g. `SpinnerData.status="complete"`, which means *render a tick*). This means *no further events will arrive for this block_id*. It is consumed by the router to close the block's handler context and is never dispatched to a handler's `push`. # ButtonsData Inherits: `InputRequestBlockData` Button group block data with options and optional label. # DatePickerData Inherits: `InputRequestBlockData` Date picker block data with value and label. # ErrorResultData Inherits: `BaseModel` Serialized data for an error result block. # ErrorResultDetails Inherits: `BaseModel` Normalized details captured from an exception. # FailureExitEventData Inherits: `BaseModel` Exit event data for failed app execution (exit_code != 0). # FormData Inherits: `InputRequestBlockData` A form request presenting a struct's fields for one typed submission. ## Attributes response type: InputValueSpec Transport contract accepting one JSON object; the struct, not the form schema, validates its contents. form_schema type: dict[str, JsonValue] Inlined form schema used to render the form and to redact secrets from stored submissions. label type: str | None Optional question shown above the form. values type: dict[str, JsonValue] Current JSON values keyed by field name, pre-filling the form. errors type: dict[str, list[str]] Validation messages keyed by dotted field path, from a previously rejected submission. # FormEchoData Inherits: `BaseModel` The outcome of one form submission, recorded in the transcript. ## Attributes request_id type: str Block ID of the form request the submission answered. status type: Literal['accepted', 'rejected'] Whether validation accepted or rejected the submission. label type: str | None The request's question, repeated alongside the answers. form_schema type: dict[str, JsonValue] Form schema describing the submitted fields. values type: dict[str, JsonValue] Submitted JSON values with secrets masked. errors type: dict[str, list[str]] Validation messages keyed by dotted field path when rejected. # ImageData Inherits: `BaseModel` Describe encoded image content carried by an output event. ## Attributes data_type type: Literal['image'] Discriminator identifying image block data. content type: str Base64-encoded image-file content. media_type type: ImageMediaType MIME type identifying the encoded image format. alt type: str | None Optional accessible description of the image. # InputEchoData Inherits: `BaseModel` An accepted input response that terminally commits its request. # InputRequestBlockData Inherits: `BaseModel` Subclasses: `ButtonsData`, `DatePickerData`, `FormData`, `InputRequestData`, `SliderData`, `TreeSelectorData` Data shared by blocks that request a single input value. # InputRequestData Inherits: `InputRequestBlockData` Input request block data for awaiting user text input. # LineChartData Inherits: `BaseModel` Line chart block data. # MarkdownData Inherits: `BaseModel` Markdown content block data. # SectionData Inherits: `BaseModel` Structural and visual state for a collapsible section. Section data is emitted as a complete snapshot whenever the section heading changes. Consumers can therefore render each event independently without reconstructing previous updates. ## Attributes title type: str Heading shown for the section. summary type: str | None Optional preview shown when the completed section is collapsed. auto_collapse type: bool Whether the section collapses automatically on completion. glyph type: str Registered glyph shown beside the title. colour type: NamedColour | None Optional named colour applied to the section heading. # SessionMetaData Inherits: `BaseModel` A partial session metadata update emitted by a runtime or host. # SliderData Inherits: `InputRequestBlockData` Slider block data with range, initial value, and label. # SpinnerData Inherits: `BaseModel` Spinner block data with status and optional message. # StructData Inherits: `BaseModel` Struct data for structured generation responses. # SuccessExitEventData Inherits: `BaseModel` Exit event data for successful app completion (exit_code 0). # SuccessResultData Inherits: `BaseModel` Serialized data for a successful result block. # SystemPromptData Inherits: `BaseModel` System prompt block data. # TableData Inherits: `BaseModel` Table block data with columns, rows, and border style. # ThinkingData Inherits: `BaseModel` Thinking content block data. # TreeSelectorData Inherits: `InputRequestBlockData` Tree selector request containing nested selectable leaves. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/models/event_class/ # yera.runtime.models.event_class Shared event semantic taxonomy and block-type classification. ## Symbols def event_class_for — Return the shared semantic class for a built-in block type. # event_class_for ``` event_class_for( block_type: str, ) → EventClass ``` Return the shared semantic class for a built-in block type. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/models/in_event/ # yera.runtime.models.in_event Input event model. ## Symbols class InputEvent — Input event received from the input stream. # InputEvent Inherits: `BaseModel` Input event received from the input stream. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/models/input_data/ # yera.runtime.models.input_data Serialized values submitted in response to input requests. ## Symbols class ButtonsInputData — A submitted button selection. class DatePickerInputData — A submitted calendar date. class FormInputData — A submitted form object, before validation against its struct. class SerializedInputData — A serialized value submitted for an input request. class SliderInputData — A submitted numeric slider value. class TextInputData — A submitted free-text value. class TreeSelectorInputData — A submitted collection of tree leaf values. # ButtonsInputData Inherits: `SerializedInputData` A submitted button selection. # DatePickerInputData Inherits: `SerializedInputData` A submitted calendar date. # FormInputData Inherits: `SerializedInputData` A submitted form object, before validation against its struct. # SerializedInputData Inherits: `BaseModel` Subclasses: `ButtonsInputData`, `DatePickerInputData`, `FormInputData`, `SliderInputData`, `TextInputData`, `TreeSelectorInputData` A serialized value submitted for an input request. ## Methods deserialise — Deserialize the payload into its declared Python value type. # SerializedInputData.deserialise ``` deserialise() → object ``` Deserialize the payload into its declared Python value type. ## Returns type: object The Python value represented by the serialized payload. ## Raises ValueError If the payload does not represent the declared type. # SliderInputData Inherits: `SerializedInputData` A submitted numeric slider value. # TextInputData Inherits: `SerializedInputData` A submitted free-text value. # TreeSelectorInputData Inherits: `SerializedInputData` A submitted collection of tree leaf values. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/models/input_spec/ # yera.runtime.models.input_spec Models describing values accepted by input requests. ## Symbols class InputValueSpec — The serialized value accepted by an input request. # InputValueSpec Inherits: `BaseModel` The serialized value accepted by an input request. ## Methods from_type — Build a value specification from a supported declared type. # InputValueSpec.from_type ``` from_type( type_hint: type, data_type: str, ) → Self ``` Build a value specification from a supported declared type. ## Parameters type_hint type: type The declared response type. data_type type: str Discriminator for the submitted input envelope. ## Returns type: Self Its display name and serialization schema. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/models/out_event/ # yera.runtime.models.out_event Event model for events block events. ## Symbols class OutputEvent — Outbound event from Yera. # OutputEvent Inherits: `BaseModel` Outbound event from Yera. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/publisher/ # yera.runtime.publisher Provides publisher abstractions for streaming str (HTMX chunk) content. ## Symbols class BasePublisher — Abstract base class for all publisher implementations. class Publisher — An asynchronous publisher that queues fragments for consumption via an async iterator. class ReplayPublisher — A Publisher-shaped sink that collects fragments synchronously for replay. class WebRenderContext — The web-transport context handlers render against. # BasePublisher Inherits: `ABC` Subclasses: `Publisher`, `ReplayPublisher` Abstract base class for all publisher implementations. ## Methods push — Pushes a chunk of data to the sink. push_eof — Signals that the end of the stream has been reached. push_pause — Signals a temporary pause in the data stream. # BasePublisher.push ``` push( chunk: str, ) → None ``` Pushes a chunk of data to the sink. ## Parameters chunk type: str The string fragment to be published. # BasePublisher.push_eof ``` push_eof() → None ``` Signals that the end of the stream has been reached. # BasePublisher.push_pause ``` push_pause() → None ``` Signals a temporary pause in the data stream. # Publisher Inherits: `BasePublisher` An asynchronous publisher that queues fragments for consumption via an async iterator. ## Methods push — Thread-safely pushes a chunk into the async queue. push_eof — Thread-safely pushes the EOF sentinel into the async queue. push_pause — Thread-safely pushes the PAUSE sentinel into the async queue. stream — Yields fragments until EOF, leaving EOF in place for later readers. # Publisher.push ``` push( chunk: str, ) → None ``` Thread-safely pushes a chunk into the async queue. ## Parameters chunk type: str The string fragment to publish. # Publisher.push_eof ``` push_eof() → None ``` Thread-safely pushes the EOF sentinel into the async queue. # Publisher.push_pause ``` push_pause() → None ``` Thread-safely pushes the PAUSE sentinel into the async queue. # Publisher.stream ``` stream() → AsyncIterator[str | object] ``` Yields fragments until EOF, leaving EOF in place for later readers. # ReplayPublisher Inherits: `BasePublisher` A Publisher-shaped sink that collects fragments synchronously for replay. ## Methods push — Appends a chunk to the internal collection. push_eof — No-op: replay collects a bounded list, no EOF sentinel. push_pause — No-op: replay supplies its own close after the collected frames. # ReplayPublisher.push ``` push( chunk: str, ) → None ``` Appends a chunk to the internal collection. ## Parameters chunk type: str The string fragment to collect. # ReplayPublisher.push_eof ``` push_eof() → None ``` No-op: replay collects a bounded list, no EOF sentinel. # ReplayPublisher.push_pause ``` push_pause() → None ``` No-op: replay supplies its own close after the collected frames. # WebRenderContext The web-transport context handlers render against. ## Attributes publisher type: BasePublisher The publisher instance used to push content. input_url type: str The URL associated with the current prompt. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/replay_executor/ # yera.runtime.replay_executor Provides the ReplayExecutor for replaying session events. ## Symbols class ReplayExecutor — Executor that replays stored events for a specific session. # ReplayExecutor Inherits: `PyRuntimeExecutor` Executor that replays stored events for a specific session. ## Methods start — Starts the event replay process in a separate spawn process. stop — Stop the app process if it is running and clean up resources. make_factory_fn — ... # ReplayExecutor.start ``` start() → None ``` Starts the event replay process in a separate spawn process. # ReplayExecutor.stop ``` stop() → None ``` Stop the app process if it is running and clean up resources. # ReplayExecutor.make_factory_fn ``` make_factory_fn( session_sources: str | dict[str, str], session_store_root: Path | None = None, ) → Callable[[AppFunctionWrapper, tuple, dict, str], PyRuntimeExecutor] ``` ... ## Parameters session_sources type: str | dict[str, str] Either a single source session_id to replay for ANY live session that gets launched (the common case — one server, one canned transcript), or a dict mapping live session_id -> source session_id for servers that multiplex several concurrent sessions against different transcripts. session_store_root type: Path | None = None directory to use as storage location for session store. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/router/ # yera.runtime.router The event router dispatches event stream output events to handlers. Handlers are responsible for rendering events and taking input. ## Symbols class EventRouter — Dispatch event blocks from an iterator of events to their registered handlers. # EventRouter Dispatch event blocks from an iterator of events to their registered handlers. ## Methods process_stream — Route events to handlers until a lifecycle or prompt event arrives. # EventRouter.process_stream ``` process_stream( events: Iterator[OutputEvent], ) → OutputEvent ``` Route events to handlers until a lifecycle or prompt event arrives. ## Parameters events type: Iterator[OutputEvent] An iterator of output events. ## Returns type: OutputEvent The lifecycle or prompt event that ended the stream. ## Raises StreamEndedError If the iterator ends without one. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/runtime/ # yera.runtime.runtime App runtime execution and stream handling. ## Symbols class PyRuntimeExecutor — Execute an app in a separate process using an EventStream. def stream_handler — Build and run an event stream with auto-detected handlers. # PyRuntimeExecutor Subclasses: `ReplayExecutor` Execute an app in a separate process using an EventStream. ## Methods start — Start the app execution in a new process with an internally created EventStream. stop — Stop the app process if it is running and clean up resources. is_running — Check if the executor process is running. producer_alive — Return whether the child process is still capable of producing events. __enter__ — Start execution with a fresh EventStream and return self. __exit__ — Ensure the subprocess is terminated when leaving the context. # PyRuntimeExecutor.start ``` start() → None ``` Start the app execution in a new process with an internally created EventStream. # PyRuntimeExecutor.stop ``` stop() → None ``` Stop the app process if it is running and clean up resources. # PyRuntimeExecutor.is_running ``` is_running() → bool ``` Check if the executor process is running. ## Returns type: bool True if process is alive and stream is available # PyRuntimeExecutor.producer_alive ``` producer_alive() → bool ``` Return whether the child process is still capable of producing events. ## Returns type: bool True if the process exists and has not exited. # PyRuntimeExecutor.__enter__ ``` __enter__() ``` Start execution with a fresh EventStream and return self. # PyRuntimeExecutor.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) ``` Ensure the subprocess is terminated when leaving the context. # stream_handler ``` stream_handler( console: Console | None = None, producer_alive: Callable[[], bool] | None = None, ) → OutputEvent ``` Build and run an event stream with auto-detected handlers. ## Parameters console type: Console | None = None the console instance to use in ANSI printouts. producer_alive type: Callable[[], bool] | None = None Optional callback returning `True` if the event producer process is still alive. ## Returns type: OutputEvent The exit event produced by the router on completion. --- Source: https://yera-labs.io/docs/yera/reference/implementation/runtime/stream/ # yera.runtime.stream Event stream implementation for inter-process app communication. ## Symbols def await_input — Wait for a correlated typed response. class EventStream — Inter-process event stream backed by multiprocessing queues. def failure_exit_event_already_pushed — Return True if a nested app already pushed a failure exit event. def is_restricted_stream — Return whether the current event stream is restricted (only certain block types allowed). def push_input — Push an input event to the current stream. def push_output — Push an output event to the current stream. # await_input ``` await_input( request_id: str, expected_type: type[_InputDataT], value_type: type[_InputValueT], timeout: float | None = None, ) → tuple[_InputDataT, _InputValueT] ``` Wait for a correlated typed response. ## Parameters request_id type: str Block ID of the request awaiting a response. expected_type type: type[_InputDataT] Typed input model expected for the request. value_type type: type[_InputValueT] Python type represented by the serialized payload. timeout type: float | None = None Maximum seconds to wait, or `None` to wait indefinitely. ## Returns type: tuple[_InputDataT, _InputValueT] Typed input data accepted for the request. ## Raises InputRequestMismatchError If the response targets another request. InputTypeMismatchError If the response carries another input type. InputValueError If the submitted payload cannot be deserialized. # EventStream Inter-process event stream backed by multiprocessing queues. ## Methods push_output — Put an output event onto the queue. push_input — Put an input event onto the queue. pop_output — Remove and return the next output event, blocking up to timeout. close — Wake blocked output consumers and prevent duplicate close signals. pop_input — Remove and return the next input event, blocking up to timeout. iter_output_blocking — Yield output events using blocking get(timeout). Reliable across processes. set_current — Bind this stream to the current context variable. get_current — Return the stream bound to the current context, raising if none is set. build — Build an event stream object or return the one currently in-context. new — Create a fresh stream, leaving the ambient context untouched. drain_output — Remove and return all immediately available output events. # EventStream.push_output ``` push_output( event: OutputEvent, ) → None ``` Put an output event onto the queue. # EventStream.push_input ``` push_input( in_event: InputEvent, ) → None ``` Put an input event onto the queue. # EventStream.pop_output ``` pop_output( timeout: float | None = None, ) → OutputEvent ``` Remove and return the next output event, blocking up to timeout. # EventStream.close ``` close() → None ``` Wake blocked output consumers and prevent duplicate close signals. # EventStream.pop_input ``` pop_input( timeout: float | None = None, ) → InputEvent ``` Remove and return the next input event, blocking up to timeout. # EventStream.iter_output_blocking ``` iter_output_blocking( timeout: float = 0.5, should_continue: Callable[[], bool] | None = None, ) → Iterator[OutputEvent] ``` Yield output events using blocking get(timeout). Reliable across processes. Do not use iter_output() when the producer is in another process: Queue.empty() is unreliable across processes and the consumer may never see the event. This method blocks on get(timeout=...) so the exit event is received reliably. # EventStream.set_current ``` set_current() → None ``` Bind this stream to the current context variable. # EventStream.get_current ``` get_current() → EventStream ``` Return the stream bound to the current context, raising if none is set. # EventStream.build ``` build() → EventStream ``` Build an event stream object or return the one currently in-context. # EventStream.new ``` new() → EventStream ``` Create a fresh stream, leaving the ambient context untouched. ## Returns type: EventStream A tuple of the new EventStream and the manager owning its queues. The caller must keep the manager alive and shut it down when done. # EventStream.drain_output ``` drain_output( timeout: float = 0.1, ) → list[OutputEvent] ``` Remove and return all immediately available output events. Does not guarantee the queue is empty afterwards — a producer in another process may still be flushing events. ## Returns type: list[OutputEvent] The events readable without blocking, in queue order. # failure_exit_event_already_pushed ``` failure_exit_event_already_pushed() → bool ``` Return True if a nested app already pushed a failure exit event. # is_restricted_stream ``` is_restricted_stream() → bool ``` Return whether the current event stream is restricted (only certain block types allowed). # push_input ``` push_input( request_id: str, data: InputData, ) → None ``` Push an input event to the current stream. # push_output ``` push_output( event: OutputEvent, ) → None ``` Push an output event to the current stream. --- Source: https://yera-labs.io/docs/yera/reference/implementation/security/ # yera.security Security boundaries shared across Yera. ## Submodules redaction --- Source: https://yera-labs.io/docs/yera/reference/implementation/security/redaction/ # yera.security.redaction Structured redaction for diagnostic values. ## Symbols def install_sensitive_data_filter — Attach structured redaction to every configured root handler. def redact_sensitive_fields — Return diagnostic data with structured secret fields redacted. class SensitiveDataFilter — Redact structured secret fields from log records. # install_sensitive_data_filter ``` install_sensitive_data_filter() → None ``` Attach structured redaction to every configured root handler. # redact_sensitive_fields ``` redact_sensitive_fields( value: object, ) → object ``` Return diagnostic data with structured secret fields redacted. ## Parameters value type: object Nested dictionaries, lists, tuples, or scalar diagnostic data. ## Returns type: object A copied structure in which recognized sensitive fields contain redaction markers. # SensitiveDataFilter Inherits: `logging.Filter` Redact structured secret fields from log records. ## Methods filter — Redact structured values before a record is formatted. # SensitiveDataFilter.filter ``` filter( record: logging.LogRecord, ) → bool ``` Redact structured values before a record is formatted. ## Parameters record type: logging.LogRecord Mutable logging record entering a handler. ## Returns type: bool Always `True` so the redacted record remains loggable. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/ # yera.setup Provide presentation-independent provider and model setup operations. ## Submodules base mcp model_discovery provider_setup write --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/base/ # yera.setup.base Define the common result and interfaces used during interactive setup. ## Symbols class ModelSetup — Obtain and validate model configuration for one provider connection. class ProviderSetup — Obtain and validate configuration for one provider integration. class SetupResult — Describe configuration and diagnostics produced during setup. # ModelSetup Inherits: `ABC`, `Generic[TConnection]` Subclasses: `MistralModelSetup`, `AnthropicModelSetup`, `OllamaModelSetup`, `AzureModelSetup`, `OpenAIModelSetup`, `OpenRouterModelSetup`, `AWSModelSetup`, `LlamaCppModelSetup`, `GeminiModelSetup` Obtain and validate model configuration for one provider connection. A model setup is bound to a configured provider connection. Implementations contain provider-specific discovery and validation but perform no prompting, rendering, or persistence. Expected client, credential, and service failures are returned as diagnostics. ## Attributes provider_type type: str Configuration key identifying the provider. dependencies type: tuple[str, ...] Python import paths required by the integration. connection_name Name of the provider connection used for setup. connection Typed provider connection used to obtain model configuration. ## Methods get_config — Obtain model configuration from the bound provider connection. validate — Validate model configuration without persisting it. # ModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from the bound provider connection. ## Returns type: SetupResult[list[BaseModelConfig]] Discovered model configuration and associated diagnostics. An empty model list is valid when discovery completed successfully without finding supported models. # ModelSetup.validate ``` validate( config: list[BaseModelConfig], ) → SetupResult[list[BaseModelConfig]] ``` Validate model configuration without persisting it. Typed model configuration has already passed schema validation. This default implementation therefore accepts it unchanged. Implementations may override the method when a provider has additional semantic constraints. ## Parameters config type: list[BaseModelConfig] Model configuration obtained or supplied during setup. ## Returns type: SetupResult[list[BaseModelConfig]] A valid result containing the supplied model configuration. # ProviderSetup Inherits: `ABC`, `Generic[TConnection]` Subclasses: `MistralProviderSetup`, `AnthropicProviderSetup`, `OllamaProviderSetup`, `AzureProviderSetup`, `OpenAIProviderSetup`, `OpenRouterProviderSetup`, `AWSProviderSetup`, `LlamaCppProviderSetup`, `GeminiProviderSetup` Obtain and validate configuration for one provider integration. Provider setup implementations contain no prompting, rendering, or persistence. Expected environmental, credential, and connectivity failures are returned as diagnostics so callers can decide whether to retry, edit, skip, or display the failure. ## Attributes provider_type type: str Configuration key identifying the provider. dependencies type: tuple[str, ...] Python import paths required by the integration. ## Methods get_config — Obtain provider configuration candidates from the environment. validate — Validate provider configuration without persisting it. # ProviderSetup.get_config ``` get_config() → SetupResult[tuple[TConnection, ...]] ``` Obtain provider configuration candidates from the environment. Discovery may produce multiple usable connections, such as AWS profiles or Azure OpenAI accounts. Expected discovery failures are returned as errors rather than raised. ## Returns type: SetupResult[tuple[TConnection, ...]] Detected provider connection candidates and associated diagnostics. An empty tuple means discovery completed without finding a candidate. `None` means discovery could not produce a result. # ProviderSetup.validate ``` validate( config: TConnection, ) → SetupResult[TConnection] ``` Validate provider configuration without persisting it. Expected credential, configuration, and connectivity failures are returned as errors. Invalid configuration is retained in the result so an interactive caller can present or edit it. ## Parameters config type: TConnection Provider connection configuration to validate. ## Returns type: SetupResult[TConnection] The supplied configuration and its validation diagnostics. # SetupResult Inherits: `Generic[TConfig]` Describe configuration and diagnostics produced during setup. Setup operations return expected environmental and configuration failures through this type rather than raising exceptions. A result may retain invalid configuration so an interactive caller can display or edit it. ## Attributes config type: TConfig | None Configuration obtained or validated by the operation. errors type: list[str] Problems that prevent the configuration from being used. warnings type: list[str] Recoverable problems that do not prevent configuration. skipped type: int Number of items intentionally omitted while obtaining configuration. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/mcp/ # yera.setup.mcp Presentation-independent setup operations for MCP servers. ## Symbols def add_device_authorized_mcp_server — Authorize, import, and persist one device-authorized MCP server. def add_header_authorized_mcp_server — Store header secrets, then import, persist, and enable one MCP server. def add_mcp_server — Import, persist, and enable one MCP server for a profile. def authorize_mcp_device_setup — Authorize and persist an MCP OAuth device grant. def build_mcp_oauth_setup — Compose browser OAuth around an active callback session. def delete_mcp_server — Remove one MCP server from Yera, with its tools and stored secrets. def loopback_mcp_oauth_setup — Open the dependencies for one browser-based MCP OAuth attempt. class MCPOAuthSetup — Dependencies required to authorize one MCP connection. def popular_mcp_servers — Return Yera's curated remote MCP server suggestions. # add_device_authorized_mcp_server ``` add_device_authorized_mcp_server( server_name: str, config: MCPServerConfig, profile: Profile, authorization_id: str, client_profile: MCPOAuthClientProfile, secret_store: SecretStore, interaction: OAuthDeviceInteraction, oauth_http_client: httpx2.AsyncClient, mcp_http_client: httpx2.AsyncClient | None = None, catalogue: SQLiteMCPCatalogue | None = None, sleep: Callable[[float], Awaitable[None]] = anyio.sleep, ) → None ``` Authorize, import, and persist one device-authorized MCP server. ## Parameters server_name type: str Name used to expose and configure the server. config type: MCPServerConfig Validated Streamable HTTP server configuration. profile type: Profile Profile in which the server will be enabled. authorization_id type: str Stable identity used for stored OAuth state. client_profile type: MCPOAuthClientProfile Registered public device-authorization profile. secret_store type: SecretStore Protected store receiving issued OAuth tokens. interaction type: OAuthDeviceInteraction Presentation implementation showing verification details. oauth_http_client type: httpx2.AsyncClient Client used for OAuth endpoint requests. mcp_http_client type: httpx2.AsyncClient | None = None Optional caller-owned MCP transport client. catalogue type: SQLiteMCPCatalogue | None = None Optional caller-owned MCP catalogue. sleep type: Callable[[float], Awaitable[None]] = anyio.sleep Awaitable delay implementation used between token requests. # add_header_authorized_mcp_server ``` add_header_authorized_mcp_server( server_name: str, config: MCPServerConfig, profile: Profile, headers: Mapping[str, str], secret_store: SecretStore, catalogue: SQLiteMCPCatalogue | None = None, ) → None ``` Store header secrets, then import, persist, and enable one MCP server. The header values are owned by the connection rather than a credential group, so the server works in every project. Each attempt stores its values under a fresh owner, so a server being replaced keeps its own values until the new configuration is written; they are then deleted as stale. If anything fails, the new values are deleted and the previous connection is left untouched. ## Parameters server_name type: str Name used to expose and configure the server. config type: MCPServerConfig Validated Streamable HTTP server configuration. profile type: Profile Profile in which the server will be enabled. headers type: Mapping[str, str] Header values keyed by header name. secret_store type: SecretStore Protected store receiving the header values. catalogue type: SQLiteMCPCatalogue | None = None Optional caller-owned MCP catalogue. # add_mcp_server ``` add_mcp_server( server_name: str, config: MCPServerConfig, profile: Profile, catalogue: SQLiteMCPCatalogue | None = None, http_client: httpx2.AsyncClient | None = None, oauth_setup: MCPOAuthSetup | None = None, secret_store: SecretStore | None = None, ) → None ``` Import, persist, and enable one MCP server for a profile. The live server is imported before configuration is changed, ensuring an unreachable server or unsupported schema cannot leave a new connection in the user's configuration. ## Parameters server_name type: str Name used to expose and configure the server. config type: MCPServerConfig Validated Streamable HTTP server configuration. profile type: Profile Profile in which the server will be enabled. catalogue type: SQLiteMCPCatalogue | None = None Optional caller-owned MCP catalogue. http_client type: httpx2.AsyncClient | None = None Optional caller-owned HTTP client. oauth_setup type: MCPOAuthSetup | None = None Optional dependencies for completing OAuth authorization. secret_store type: SecretStore | None = None Optional protected OAuth storage override. # authorize_mcp_device_setup ``` authorize_mcp_device_setup( server_name: str, server_url: str, authorization_id: str, client_profile: MCPOAuthClientProfile, secret_store: SecretStore, interaction: OAuthDeviceInteraction, http_client: httpx2.AsyncClient, sleep: Callable[[float], Awaitable[None]] = anyio.sleep, ) → MCPOAuthAuth ``` Authorize and persist an MCP OAuth device grant. ## Parameters server_name type: str Yera name of the MCP connection. server_url type: str Streamable HTTP endpoint being authorized. authorization_id type: str Stable identity used for stored OAuth state. client_profile type: MCPOAuthClientProfile Registered public device-authorization profile. secret_store type: SecretStore Protected store receiving issued OAuth tokens. interaction type: OAuthDeviceInteraction Presentation implementation showing verification details. http_client type: httpx2.AsyncClient Client used for OAuth endpoint requests. sleep type: Callable[[float], Awaitable[None]] = anyio.sleep Awaitable delay implementation used between token requests. ## Returns type: MCPOAuthAuth Persistable OAuth authentication configuration. # build_mcp_oauth_setup ``` build_mcp_oauth_setup( authorization_id: str, secret_store: SecretStore, callback_session: OAuthCallbackSession, browser_opener: Callable[[str], bool] = webbrowser.open, fallback_handler: Callable[[OAuthAuthorizationRequest], Awaitable[None]] | None = None, client_profile: str | None = 'yera', ) → MCPOAuthSetup ``` Compose browser OAuth around an active callback session. ## Parameters authorization_id type: str Stable identity used for stored OAuth state. secret_store type: SecretStore Protected store receiving OAuth protocol secrets. callback_session type: OAuthCallbackSession Active local or hosted callback session. browser_opener type: Callable[[str], bool] = webbrowser.open Function opening the transient authorization URL. fallback_handler type: Callable[[OAuthAuthorizationRequest], Awaitable[None]] | None = None Optional presenter used when browser opening fails. client_profile type: str | None = 'yera' Optional predefined OAuth client profile name. ## Returns type: MCPOAuthSetup OAuth setup ready for MCP connection authorization. # delete_mcp_server ``` delete_mcp_server( server_name: str, secret_store: SecretStore, catalogue: SQLiteMCPCatalogue | None = None, ) → bool ``` Remove one MCP server from Yera, with its tools and stored secrets. The server leaves global configuration and every profile first, then the tool catalogue, and its secrets are deleted last. A failure part-way can leave an unused secret, but never a configured server without its credentials. Credential-group values used by static headers are left alone, because they belong to the user's group. ## Parameters server_name type: str Name of the configured server to remove. secret_store type: SecretStore Protected store holding the connection's secrets. catalogue type: SQLiteMCPCatalogue | None = None Optional caller-owned MCP catalogue. ## Returns type: bool Whether a configured server with that name was removed. ## Raises MCPInvalidConfigError If the global MCP configuration is invalid. # loopback_mcp_oauth_setup ``` loopback_mcp_oauth_setup( authorization_id: str, secret_store: SecretStore, browser_opener: Callable[[str], bool] = webbrowser.open, fallback_handler: Callable[[OAuthAuthorizationRequest], Awaitable[None]] | None = None, timeout_seconds: float = 300, client_profile: str | None = 'yera', callback_host: str = '127.0.0.1', callback_port: int = 0, ) → AsyncIterator[MCPOAuthSetup] ``` Open the dependencies for one browser-based MCP OAuth attempt. ## Parameters authorization_id type: str Stable identity used for stored OAuth state. secret_store type: SecretStore Protected store receiving OAuth protocol secrets. browser_opener type: Callable[[str], bool] = webbrowser.open Function opening the transient authorization URL. fallback_handler type: Callable[[OAuthAuthorizationRequest], Awaitable[None]] | None = None Optional presenter used when browser opening fails. timeout_seconds type: float = 300 Maximum time to wait for the OAuth callback. client_profile type: str | None = 'yera' Predefined OAuth client profile, defaulting to Yera's canonical public identity. Pass `None` to use DCR without CIMD. callback_host type: str = '127.0.0.1' Loopback interface receiving the OAuth redirect. callback_port type: int = 0 Fixed callback port, or `0` for an ephemeral port. # MCPOAuthSetup Dependencies required to authorize one MCP connection. ## Attributes authorization_id type: str Stable identity used for stored OAuth state. client_metadata type: OAuthClientMetadata OAuth client declaration supplied to the MCP SDK. secret_store type: SecretStore Protected store receiving OAuth protocol secrets. interaction type: OAuthInteraction | None Optional user-facing authorization interaction. client_profile type: str | None Optional predefined OAuth client profile name. # popular_mcp_servers ``` popular_mcp_servers() → tuple[DiscoveredMCPServer, ...] ``` Return Yera's curated remote MCP server suggestions. ## Returns type: tuple[DiscoveredMCPServer, ...] Stable built-in choices in their intended presentation order. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/ # yera.setup.model_discovery Provide model setup operations for supported provider integrations. ## Submodules anthropic aws azure common gemini llama_cpp mistral ollama openai openrouter registry --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/anthropic/ # yera.setup.model_discovery.anthropic Discover models available through an Anthropic connection. ## Symbols class AnthropicModelSetup — Discover models and capabilities available through Anthropic. # AnthropicModelSetup Inherits: `ModelSetup[AnthropicConnection]` Discover models and capabilities available through Anthropic. The discovery operation lists models exposed to the configured Anthropic account and converts them into typed Yera language-model configuration. Models without capability metadata are retained with conservative capabilities and an accompanying warning. ## Attributes provider_type Provider identifier used by Yera configuration. ## Methods get_config — Obtain model configuration from the configured Anthropic account. # AnthropicModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from the configured Anthropic account. Models without capability metadata are retained with conservative capabilities and an accompanying warning. Expected credential and Anthropic client failures are returned as blocking errors. ## Returns type: SetupResult[list[BaseModelConfig]] Anthropic language-model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/aws/ # yera.setup.model_discovery.aws Discover models available through an AWS Bedrock connection. ## Symbols class AWSModelSetup — Discover and classify models available through AWS Bedrock. # AWSModelSetup Inherits: `ModelSetup[AWSConnection]` Discover and classify models available through AWS Bedrock. The discovery operation lists foundation models in the configured AWS region, resolves inference-profile identifiers where required, and converts supported models into typed Yera configuration objects. Models that are unavailable, legacy, or unsupported are counted as skipped. ## Attributes provider_type Provider identifier used by Yera configuration. ## Methods get_config — Obtain model configuration from AWS Bedrock. # AWSModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from AWS Bedrock. Foundation models are resolved to on-demand or inference-profile identifiers as required. Legacy, unavailable, and unsupported models are omitted and included in the skipped count. Expected AWS client failures are returned as blocking errors. ## Returns type: SetupResult[list[BaseModelConfig]] Supported AWS Bedrock model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/azure/ # yera.setup.model_discovery.azure Azure OpenAI model discovery handler. ## Symbols class AzureModelSetup — Handler for discovering model deployments from Azure OpenAI. # AzureModelSetup Inherits: `ModelSetup[AzureConnection]` Handler for discovering model deployments from Azure OpenAI. Unlike other providers, Azure requires models to be 'deployed' before they can be used. This class discovers these deployments within a specific Azure Cognitive Services account and classifies them by their underlying model type. ## Methods get_config — Obtain model configuration from Azure OpenAI deployments. # AzureModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from Azure OpenAI deployments. Only successfully provisioned deployments with supported underlying model types are returned. Expected Azure authentication and management client failures are returned as blocking errors. ## Returns type: SetupResult[list[BaseModelConfig]] Supported Azure OpenAI model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/common/ # yera.setup.model_discovery.common Shared model discovery utilities. ## Symbols def classify_openai_model — Classify an OpenAI model ID into a Yera model type. # classify_openai_model ``` classify_openai_model( model_id: str, ) → str | None ``` Classify an OpenAI model ID into a Yera model type. OpenAI's model list mixes chat models with ones that answer on a different endpoint entirely: realtime voice, audio, image generation, and the legacy completions API. The list reports no capabilities, so these are matched by name. ## Parameters model_id type: str The provider-side model identifier. ## Returns type: str | None The Yera model type, or None if the model should be skipped. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/gemini/ # yera.setup.model_discovery.gemini Discover models available through a Gemini connection. ## Symbols class GeminiModelSetup — Discover and classify models available through Gemini. # GeminiModelSetup Inherits: `ModelSetup[GeminiConnection]` Discover and classify models available through Gemini. The discovery operation lists models exposed through the configured Gemini Developer API connection and converts supported model families into typed Yera configuration objects. Unsupported specialist models are counted as skipped. ## Attributes provider_type Provider identifier used by Yera configuration. ## Methods get_config — Obtain model configuration from the configured Gemini account. # GeminiModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from the configured Gemini account. Unsupported specialist models are omitted and included in the skipped count. Expected Gemini client failures are returned as blocking errors. ## Returns type: SetupResult[list[BaseModelConfig]] Supported Gemini model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/llama_cpp/ # yera.setup.model_discovery.llama_cpp Llama-cpp model discovery handler. ## Symbols class LlamaCppModelSetup — Handler for discovering local GGUF models for Llama-cpp. # LlamaCppModelSetup Inherits: `ModelSetup[LlamaCppConnection]` Handler for discovering local GGUF models for Llama-cpp. This class crawls configured local directories, parses the binary headers of .gguf files to extract metadata. ## Methods get_config — Obtain model configuration from local GGUF files. # LlamaCppModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from local GGUF files. Configured directories are scanned recursively. Unreadable files and inaccessible directories are omitted with recoverable warnings rather than aborting the complete scan. ## Returns type: SetupResult[list[BaseModelConfig]] Supported llama.cpp model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/mistral/ # yera.setup.model_discovery.mistral Discover models available through a Mistral connection. ## Symbols class MistralModelSetup — Discover chat models available through Mistral. # MistralModelSetup Inherits: `ModelSetup[MistralConnection]` Discover chat models available through Mistral. The discovery operation lists models exposed to the configured Mistral account and converts supported chat models into typed Yera language-model configuration. Non-chat, deprecated, and unrecognized records are omitted from the returned model collection. ## Attributes provider_type Provider identifier used by Yera configuration. ## Methods get_config — Obtain model configuration from the configured Mistral account. # MistralModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from the configured Mistral account. Non-chat and deprecated models are omitted. Records not recognized by the installed Mistral SDK are omitted with a warning. Expected credential and client failures are returned as blocking errors. ## Returns type: SetupResult[list[BaseModelConfig]] Supported Mistral model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/ollama/ # yera.setup.model_discovery.ollama Ollama model discovery handler. ## Symbols class OllamaModelSetup — Handler for discovering models from an Ollama instance. # OllamaModelSetup Inherits: `ModelSetup[OllamaConnection]` Handler for discovering models from an Ollama instance. This class connects to an Ollama server, retrieves the list of available model tags, and queries each model's capabilities to categorise them as either LLMs or embedding models. ## Methods get_config — Obtain model configuration from the configured Ollama server. # OllamaModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from the configured Ollama server. Failure to list server models is returned as a blocking error. Failure to inspect an individual model is recoverable: that model is omitted with a warning and contributes to the skipped count. ## Returns type: SetupResult[list[BaseModelConfig]] Supported Ollama model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/openai/ # yera.setup.model_discovery.openai Discover models available through an OpenAI connection. ## Symbols class OpenAIModelSetup — Discover and classify models available through OpenAI. # OpenAIModelSetup Inherits: `ModelSetup[OpenAIConnection]` Discover and classify models available through OpenAI. The discovery operation lists models exposed to the configured OpenAI account and converts supported model families into typed Yera configuration objects. Unsupported model families are counted as skipped. ## Attributes provider_type Provider identifier used by Yera configuration. ## Methods get_config — Obtain model configuration from the configured OpenAI account. # OpenAIModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from the configured OpenAI account. Unsupported model families are omitted and included in the skipped count. Expected credential and OpenAI client failures are returned as blocking errors. ## Returns type: SetupResult[list[BaseModelConfig]] Supported model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/openrouter/ # yera.setup.model_discovery.openrouter Discover models available through an OpenRouter connection. ## Symbols class OpenRouterModelSetup — Discover and classify models available through OpenRouter. # OpenRouterModelSetup Inherits: `ModelSetup[OpenRouterConnection]` Discover and classify models available through OpenRouter. The discovery operation traverses every model-catalog page exposed to the configured account and converts supported model families into typed Yera configuration objects. Unsupported output modalities are counted as skipped. ## Attributes provider_type Provider identifier used by Yera configuration. ## Methods get_config — Obtain model configuration from the OpenRouter catalogue. # OpenRouterModelSetup.get_config ``` get_config() → SetupResult[list[BaseModelConfig]] ``` Obtain model configuration from the OpenRouter catalogue. Every catalogue page is traversed. Models with unsupported output modalities are omitted and included in the skipped count. Expected OpenRouter client failures are returned as blocking errors. ## Returns type: SetupResult[list[BaseModelConfig]] Supported OpenRouter model configuration and discovery diagnostics. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/model_discovery/registry/ # yera.setup.model_discovery.registry Find model setup operations for configured provider connections. ## Symbols def find_model_setups — Find model setup operations for configured provider connections. def get_model_setup — Get model setup bound to one provider connection. # find_model_setups ``` find_model_setups( providers: Providers, dependencies: Mapping[str, bool], ) → tuple[ModelSetup, ...] ``` Find model setup operations for configured provider connections. One setup object is created for each configured connection belonging to an integration whose Python dependencies are available. Providers without configured connections are omitted. ## Parameters providers type: Providers Configured provider connections. dependencies type: Mapping[str, bool] Dependency availability returned by `find_dependencies`. ## Returns type: ModelSetup Model setup objects in provider presentation order and connection configuration order. # get_model_setup ``` get_model_setup( provider_type: str, connection_name: str, connection: BaseConnection, ) → ModelSetup | None ``` Get model setup bound to one provider connection. ## Parameters provider_type type: str Provider integration owning the connection. connection_name type: str Name assigned to the connection. connection type: BaseConnection Typed provider connection configuration. ## Returns type: ModelSetup | None A model setup bound to the connection, or `None` when the provider does not support model setup. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/ # yera.setup.provider_setup Provider connection setup operations. ## Submodules anthropic aws azure gemini llama_cpp mistral ollama openai openrouter registry --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/anthropic/ # yera.setup.provider_setup.anthropic Obtain and validate Anthropic provider configuration. ## Symbols class AnthropicProviderSetup — Provide presentation-independent Anthropic setup operations. # AnthropicProviderSetup Inherits: `ProviderSetup[AnthropicConnection]` Provide presentation-independent Anthropic setup operations. Configuration discovery looks for the conventional Anthropic API-key environment variable. Validation checks that the configured variable contains a plausibly formatted Anthropic API key. ## Attributes provider_type Configuration key for the Anthropic provider. dependencies Python import paths required by the integration. ## Methods get_config — Obtain Anthropic configuration from the current environment. validate — Validate an Anthropic connection's API-key environment variable. # AnthropicProviderSetup.get_config ``` get_config() → SetupResult[tuple[AnthropicConnection, ...]] ``` Obtain Anthropic configuration from the current environment. ## Returns type: SetupResult[tuple[AnthropicConnection, ...]] A result containing a connection referencing `ANTHROPIC_API_KEY` when it is present. Otherwise, the result contains no configuration. # AnthropicProviderSetup.validate ``` validate( config: AnthropicConnection, ) → SetupResult[AnthropicConnection] ``` Validate an Anthropic connection's API-key environment variable. ## Parameters config type: AnthropicConnection Anthropic connection containing the environment-variable name. ## Returns type: SetupResult[AnthropicConnection] The supplied configuration and any blocking validation errors. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/aws/ # yera.setup.provider_setup.aws Obtain and validate AWS Bedrock provider configuration. ## Symbols class AWSProviderSetup — Provide presentation-independent AWS Bedrock setup operations. # AWSProviderSetup Inherits: `ProviderSetup[AWSConnection]` Provide presentation-independent AWS Bedrock setup operations. Configuration discovery returns every locally configured AWS profile whose region can be resolved. Validation confirms credentials through AWS Security Token Service. ## Attributes provider_type Configuration key for the AWS provider. dependencies Python import paths required by the integration. ## Methods get_config — Obtain connections from locally configured AWS profiles. validate — Validate an AWS connection through Security Token Service. # AWSProviderSetup.get_config ``` get_config() → SetupResult[tuple[AWSConnection, ...]] ``` Obtain connections from locally configured AWS profiles. Profiles without a resolvable region are omitted and reported as recoverable warnings. AWS SDK failures that prevent profile discovery are returned as blocking errors. ## Returns type: SetupResult[tuple[AWSConnection, ...]] Complete AWS connection candidates and discovery diagnostics. # AWSProviderSetup.validate ``` validate( config: AWSConnection, ) → SetupResult[AWSConnection] ``` Validate an AWS connection through Security Token Service. ## Parameters config type: AWSConnection AWS connection containing a profile and target region. ## Returns type: SetupResult[AWSConnection] The supplied connection and a blocking error when AWS credentials or connectivity cannot be validated. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/azure/ # yera.setup.provider_setup.azure Obtain and validate Azure OpenAI provider configuration. ## Symbols class AzureProviderSetup — Provide presentation-independent Azure OpenAI setup operations. # AzureProviderSetup Inherits: `ProviderSetup[AzureConnection]` Provide presentation-independent Azure OpenAI setup operations. Configuration discovery enumerates accessible subscriptions and returns every Cognitive Services account whose kind is OpenAI. Validation requests a Cognitive Services token for the connection's configured tenant. ## Attributes provider_type Configuration key for the Azure provider. dependencies Python import paths required by the integration. ## Methods get_config — Obtain accessible Azure OpenAI connection candidates. validate — Validate access to an Azure OpenAI connection's tenant. # AzureProviderSetup.get_config ``` get_config() → SetupResult[tuple[AzureConnection, ...]] ``` Obtain accessible Azure OpenAI connection candidates. Expected Azure authentication and resource-enumeration failures are returned as diagnostics instead of raised. ## Returns type: SetupResult[tuple[AzureConnection, ...]] Every discovered Azure OpenAI connection and any blocking discovery error. # AzureProviderSetup.validate ``` validate( config: AzureConnection, ) → SetupResult[AzureConnection] ``` Validate access to an Azure OpenAI connection's tenant. ## Parameters config type: AzureConnection Azure OpenAI connection containing the tenant to validate. ## Returns type: SetupResult[AzureConnection] The supplied connection and a blocking error when a Cognitive Services token cannot be acquired. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/gemini/ # yera.setup.provider_setup.gemini Obtain and validate Gemini provider configuration. ## Symbols class GeminiProviderSetup — Provide presentation-independent Gemini setup operations. # GeminiProviderSetup Inherits: `ProviderSetup[GeminiConnection]` Provide presentation-independent Gemini setup operations. Configuration discovery follows the Gemini SDK's API-key environment variable precedence. Validation requires the configured variable to contain a non-empty value. ## Attributes provider_type Configuration key for the Gemini provider. dependencies Python import paths required by the integration. ## Methods get_config — Obtain Gemini configuration from the current environment. validate — Validate a Gemini connection's API-key environment variable. # GeminiProviderSetup.get_config ``` get_config() → SetupResult[tuple[GeminiConnection, ...]] ``` Obtain Gemini configuration from the current environment. ## Returns type: SetupResult[tuple[GeminiConnection, ...]] A result containing a connection referencing the first populated Gemini API-key variable in SDK precedence order. Otherwise, the result contains no configuration. # GeminiProviderSetup.validate ``` validate( config: GeminiConnection, ) → SetupResult[GeminiConnection] ``` Validate a Gemini connection's API-key environment variable. ## Parameters config type: GeminiConnection Gemini connection containing the environment-variable name. ## Returns type: SetupResult[GeminiConnection] The supplied configuration and any blocking validation errors. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/llama_cpp/ # yera.setup.provider_setup.llama_cpp Obtain and validate llama.cpp provider configuration. ## Symbols class LlamaCppProviderSetup — Provide presentation-independent llama.cpp setup operations. # LlamaCppProviderSetup Inherits: `ProviderSetup[LlamaCppConnection]` Provide presentation-independent llama.cpp setup operations. Configuration discovery searches an environment-defined path and conventional local model directories. Validation reports inaccessible paths as recoverable warnings because removable or network storage may become available later. ## Attributes provider_type Configuration key for the llama.cpp provider. dependencies Python import paths required by the integration. ## Methods get_config — Obtain configuration from accessible local model directories. validate — Validate configured llama.cpp model directories. # LlamaCppProviderSetup.get_config ``` get_config() → SetupResult[tuple[LlamaCppConnection, ...]] ``` Obtain configuration from accessible local model directories. ## Returns type: SetupResult[tuple[LlamaCppConnection, ...]] A result containing one connection candidate with every detected model directory, or an empty candidate tuple when none of the directories are accessible. # LlamaCppProviderSetup.validate ``` validate( config: LlamaCppConnection, ) → SetupResult[LlamaCppConnection] ``` Validate configured llama.cpp model directories. Missing directories are recoverable because external or removable storage may be mounted after setup. ## Parameters config type: LlamaCppConnection llama.cpp connection containing model directory paths. ## Returns type: SetupResult[LlamaCppConnection] The supplied configuration and warnings for empty or currently inaccessible directory configuration. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/mistral/ # yera.setup.provider_setup.mistral Obtain and validate Mistral provider configuration. ## Symbols class MistralProviderSetup — Provide presentation-independent Mistral setup operations. # MistralProviderSetup Inherits: `ProviderSetup[MistralConnection]` Provide presentation-independent Mistral setup operations. Configuration discovery looks for the conventional Mistral API-key environment variable. Validation checks that the configured variable contains a plausibly sized API key. ## Attributes provider_type Configuration key for the Mistral provider. dependencies Python import paths required by the integration. ## Methods get_config — Obtain Mistral configuration from the current environment. validate — Validate a Mistral connection's API-key environment variable. # MistralProviderSetup.get_config ``` get_config() → SetupResult[tuple[MistralConnection, ...]] ``` Obtain Mistral configuration from the current environment. ## Returns type: SetupResult[tuple[MistralConnection, ...]] A result containing a connection referencing `MISTRAL_API_KEY` when it is present. Otherwise, the result contains no configuration. # MistralProviderSetup.validate ``` validate( config: MistralConnection, ) → SetupResult[MistralConnection] ``` Validate a Mistral connection's API-key environment variable. Mistral does not document a stable API-key prefix, so validation only checks presence and a plausible minimum length. ## Parameters config type: MistralConnection Mistral connection containing the environment-variable name. ## Returns type: SetupResult[MistralConnection] The supplied configuration and any blocking validation errors. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/ollama/ # yera.setup.provider_setup.ollama Obtain and validate Ollama provider configuration. ## Symbols class OllamaProviderSetup — Provide presentation-independent Ollama setup operations. # OllamaProviderSetup Inherits: `ProviderSetup[OllamaConnection]` Provide presentation-independent Ollama setup operations. Configuration discovery resolves `OLLAMA_HOST` with the conventional local server as its fallback. Validation probes the configured server's tags endpoint. ## Attributes provider_type Configuration key for the Ollama provider. dependencies Python import paths required by the integration. ## Methods get_config — Obtain Ollama configuration from the current environment. validate — Validate connectivity to an Ollama server. # OllamaProviderSetup.get_config ``` get_config() → SetupResult[tuple[OllamaConnection, ...]] ``` Obtain Ollama configuration from the current environment. ## Returns type: SetupResult[tuple[OllamaConnection, ...]] A valid result containing one normalized Ollama connection candidate based on `OLLAMA_HOST` or the conventional local URL. # OllamaProviderSetup.validate ``` validate( config: OllamaConnection, ) → SetupResult[OllamaConnection] ``` Validate connectivity to an Ollama server. ## Parameters config type: OllamaConnection Ollama connection whose tags endpoint should be probed. ## Returns type: SetupResult[OllamaConnection] The supplied configuration and a blocking error when the server is unreachable or returns an unsuccessful HTTP response. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/openai/ # yera.setup.provider_setup.openai Obtain and validate OpenAI provider configuration. ## Symbols class OpenAIProviderSetup — Provide presentation-independent OpenAI setup operations. # OpenAIProviderSetup Inherits: `ProviderSetup[OpenAIConnection]` Provide presentation-independent OpenAI setup operations. Configuration discovery looks for the conventional OpenAI API-key environment variable. Validation checks that the configured variable exists and contains a plausibly formatted OpenAI API key. ## Attributes provider_type Configuration key for the OpenAI provider. dependencies Python modules required by the integration. ## Methods get_config — Obtain OpenAI configuration from the process environment. validate — Validate an OpenAI API-key environment variable. # OpenAIProviderSetup.get_config ``` get_config() → SetupResult[tuple[OpenAIConnection, ...]] ``` Obtain OpenAI configuration from the process environment. ## Returns type: SetupResult[tuple[OpenAIConnection, ...]] A result containing one connection candidate referencing `OPENAI_API_KEY` when it is present. Otherwise, the result contains an empty candidate tuple. # OpenAIProviderSetup.validate ``` validate( config: OpenAIConnection, ) → SetupResult[OpenAIConnection] ``` Validate an OpenAI API-key environment variable. ## Parameters config type: OpenAIConnection OpenAI connection containing the environment-variable name. ## Returns type: SetupResult[OpenAIConnection] The supplied configuration with errors describing a missing, empty, or implausibly formatted API key. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/openrouter/ # yera.setup.provider_setup.openrouter Obtain and validate OpenRouter provider configuration. ## Symbols class OpenRouterProviderSetup — Provide presentation-independent OpenRouter setup operations. # OpenRouterProviderSetup Inherits: `ProviderSetup[OpenRouterConnection]` Provide presentation-independent OpenRouter setup operations. Configuration discovery looks for the conventional OpenRouter API-key environment variable. Validation checks that the configured variable contains a plausibly formatted OpenRouter API key. ## Attributes provider_type Configuration key for the OpenRouter provider. dependencies Python import paths required by the integration. ## Methods get_config — Obtain OpenRouter configuration from the current environment. validate — Validate an OpenRouter connection's API-key environment variable. # OpenRouterProviderSetup.get_config ``` get_config() → SetupResult[tuple[OpenRouterConnection, ...]] ``` Obtain OpenRouter configuration from the current environment. ## Returns type: SetupResult[tuple[OpenRouterConnection, ...]] A result containing a connection referencing `OPENROUTER_API_KEY` when it is present. Otherwise, the result contains no configuration. # OpenRouterProviderSetup.validate ``` validate( config: OpenRouterConnection, ) → SetupResult[OpenRouterConnection] ``` Validate an OpenRouter connection's API-key environment variable. ## Parameters config type: OpenRouterConnection OpenRouter connection containing its environment-variable name and optional attribution settings. ## Returns type: SetupResult[OpenRouterConnection] The supplied configuration and any blocking validation errors. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/provider_setup/registry/ # yera.setup.provider_setup.registry Find installed provider setup operations and their dependencies. ## Symbols def find_dependencies — Find Python dependencies used by provider setup integrations. def find_provider_setups — Find provider setup operations supported by installed dependencies. # find_dependencies ``` find_dependencies() → dict[str, bool] ``` Find Python dependencies used by provider setup integrations. Each import path is inspected without importing the corresponding client module. Dependencies shared by multiple providers appear once in the returned mapping. ## Returns type: dict[str, bool] Import paths mapped to whether Python can resolve them. # find_provider_setups ``` find_provider_setups( dependencies: Mapping[str, bool], ) → tuple[ProviderSetup, ...] ``` Find provider setup operations supported by installed dependencies. ## Parameters dependencies type: Mapping[str, bool] Dependency availability returned by `find_dependencies`. ## Returns type: ProviderSetup Provider setup objects whose required dependencies are all available, preserving presentation order. --- Source: https://yera-labs.io/docs/yera/reference/implementation/setup/write/ # yera.setup.write Persist provider and model configuration produced during setup. ## Symbols def write_mcp_server_config — Write an MCP server connection to global Yera configuration. def write_model_config — Replace model configuration for one provider connection. def write_profile_config — Write a profile to the global Yera configuration. def write_provider_config — Write a provider connection to the global Yera configuration. # write_mcp_server_config ``` write_mcp_server_config( server_name: str, config: MCPServerConfig, ) → None ``` Write an MCP server connection to global Yera configuration. ## Parameters server_name type: str Name used to enable the server in profiles. config type: MCPServerConfig Typed MCP server configuration to persist. # write_model_config ``` write_model_config( provider_type: str, connection_name: str, config: list[BaseModelConfig], ) → None ``` Replace model configuration for one provider connection. The caller is responsible for obtaining and validating the models before writing them. This operation performs no discovery, validation, prompting, or rendering. ## Parameters provider_type type: str Provider configuration key. connection_name type: str Provider connection whose models are replaced. config type: list[BaseModelConfig] Complete model configuration for the connection. # write_profile_config ``` write_profile_config( config: Profile, make_default: bool = False, ) → None ``` Write a profile to the global Yera configuration. The complete profile is written in one operation after the setup flow has collected its provider connections and selected model defaults. The caller explicitly controls whether the profile becomes Yera's global default. ## Parameters config type: Profile Complete profile configuration to persist. make_default type: bool = False Whether to make this profile the global default. # write_provider_config ``` write_provider_config( provider_type: str, connection_name: str, config: BaseConnection, ) → None ``` Write a provider connection to the global Yera configuration. The caller is responsible for validating the connection before writing it. This operation performs no discovery, validation, prompting, or rendering. ## Parameters provider_type type: str Provider configuration key. connection_name type: str Name under which the connection is stored. config type: BaseConnection Typed provider connection configuration to persist. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/ # yera.tools Tools — self-contained capabilities apps can call into. - `@tool` — decorate a function to make it app-callable. - `tool_creds` — read the active tool's credentials from inside its body. ## Submodules base creds decorated_tool decorator exceptions mcp --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/base/ # yera.tools.base Core interface def for all yera tools. ## Symbols class BaseTool — Define the common callable contract for Yera tool implementations. # BaseTool Inherits: `OpaqueCallable`, `ABC` Subclasses: `DecoratedTool`, `MCPTool` Define the common callable contract for Yera tool implementations. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/creds/ # yera.tools.creds Tool runtime credential snapshot and context for `@yr.tool` invocations. Credential loading, stores, and authorisation live in `yera.creds`. ## Symbols def __getattr__ — # __getattr__ ``` __getattr__( name: str, ) → object ``` ## Submodules context resolve snapshot --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/creds/context/ # yera.tools.creds.context Credential context for tool invocations. When a `@tool`-decorated function runs, its credentials are resolved and bound to a `ContextVar` before the function body executes. The tool body reads them back via `tool_creds`. ## Symbols def clear_tool_creds_context — Clear the current tool credential snapshot (tests and explicit teardown). def reset_tool_creds_context — Restore the tool credential snapshot to the value bound before :func:`set_tool_creds_context`. def set_tool_creds_context — Store the credential snapshot for the currently executing tool. def tool_creds — Return the active tool's credentials. # clear_tool_creds_context ``` clear_tool_creds_context() → None ``` Clear the current tool credential snapshot (tests and explicit teardown). This sets the context to `None` without using a prior token. Prefer :func:`reset_tool_creds_context` when unwinding a paired :func:`set_tool_creds_context`. # reset_tool_creds_context ``` reset_tool_creds_context( token: Token, ) → None ``` Restore the tool credential snapshot to the value bound before :func:`set_tool_creds_context`. # set_tool_creds_context ``` set_tool_creds_context( creds: ToolCreds, ) → Token ``` Store the credential snapshot for the currently executing tool. ## Returns type: Token A `ContextVar` token for use with :func:`reset_tool_creds_context` so nested tool invocations can restore the previous snapshot. # tool_creds ``` tool_creds() → ToolCreds ``` Return the active tool's credentials. Call from inside a `@tool`-decorated function to read the credentials the tool declared with `creds=...`. The returned `ToolCreds` is a read-only snapshot of the configured credential groups, flattened to dotted keys. ## Examples ```python @yr.tool(creds=["my_api"]) def call_api(prompt: str) -> str: api_key = yr.tool_creds().require("my_api.api_key") ... ``` ## Returns type: ToolCreds The active tool's credential snapshot. ## Raises RuntimeError When called outside an active tool invocation. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/creds/resolve/ # yera.tools.creds.resolve Resolve tool credential keys against the store and active group. ## Symbols def resolve_and_set_tool_creds — Resolve declared keys against the active credential group and set context. # resolve_and_set_tool_creds ``` resolve_and_set_tool_creds( creds_keys: list[str], ) → Token ``` Resolve declared keys against the active credential group and set context. ## Parameters creds_keys type: list[str] Exact credential keys or dotted namespace prefixes requested by the tool. ## Returns type: Token Token used to restore the previous tool-credential context. ## Raises CredentialGroupNotSpecifiedError If no active group is configured. CredentialGroupNotFoundError If the configured group does not exist. CredentialGroupNotAuthorisedError If the current project is not authorized for the group. CredentialKeyError If a selected value is not UTF-8 text. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/creds/snapshot/ # yera.tools.creds.snapshot Read-only flat credential snapshot exposed to tool bodies. ## Symbols class ToolCreds — Read-only snapshot of credentials available to a tool. # ToolCreds Read-only snapshot of credentials available to a tool. Wraps a flat `dict[str, str]` mapping dotted keys (`.`) to their string values. Tools obtain an instance via `tool_creds` rather than constructing one directly. Example: ```python @yr.tool(creds=["db"]) def query(sql: str) -> list[dict]: creds = yr.tool_creds() host = creds.require("db.host") port = creds.require("db.port") ... ``` ## Methods get — Look up a credential by dotted key, returning ``None`` if absent. require — Look up a credential by dotted key, raising if absent. keys — Return the configured credential keys, sorted alphabetically. __contains__ — Check whether a dotted key is configured. __len__ — Number of configured credentials. __repr__ — Repr string for ToolCreds. # ToolCreds.get ``` get( key: str, ) → str | None ``` Look up a credential by dotted key, returning `None` if absent. ## Parameters key type: str Dotted credential key, e.g. `"openai.api_key"`. ## Returns type: str | None The credential value, or `None` if no such key is configured. # ToolCreds.require ``` require( key: str, ) → str ``` Look up a credential by dotted key, raising if absent. ## Parameters key type: str Dotted credential key, e.g. `"openai.api_key"`. ## Returns type: str The credential value. ## Raises CredentialKeyError If no such key is configured. # ToolCreds.keys ``` keys() → list[str] ``` Return the configured credential keys, sorted alphabetically. # ToolCreds.__contains__ ``` __contains__( key: str, ) → bool ``` Check whether a dotted key is configured. # ToolCreds.__len__ ``` __len__() → int ``` Number of configured credentials. # ToolCreds.__repr__ ``` __repr__() → str ``` Repr string for ToolCreds. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/decorated_tool/ # yera.tools.decorated_tool The callable wrapper produced by `@tool`. ## Symbols class DecoratedTool — Callable wrapper around a tool function. # DecoratedTool Inherits: `BaseTool` Callable wrapper around a tool function. Produced by the `@tool` decorator. When called, resolves the tool's declared credential groups, binds them to the tool credential context, runs the wrapped function, and tears the context down on completion (even on failure). Instances are normally produced by the decorator rather than constructed directly. ## Methods __call__ — Invoke the tool. invoke — Fill the inputs to this tool using the active LLM and then call it. # DecoratedTool.__call__ ``` __call__( *args, **kwargs, ) → object ``` Invoke the tool. Resolves and binds the tool's credentials (if any), calls the wrapped function, and restores the previous credential context on completion. ## Parameters *args type: object = () Positional arguments forwarded to the wrapped function. **kwargs type: object Keyword arguments forwarded to the wrapped function. ## Returns type: object The wrapped function's return value. # DecoratedTool.invoke ``` invoke( instruction: str | None = None, **kwargs, ) → object ``` Fill the inputs to this tool using the active LLM and then call it. ## Parameters instruction type: str | None = None Optional guiding prompt for structured input generation. **kwargs type: str | int | float | bool additional values to pass down the the llm generation such as temperature. ## Returns type: object The result of calling the tool. ## Submodules result_block section spinner --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/decorator/ # yera.tools.decorator The `@tool` decorator for declaring app-callable capabilities. ## Symbols def tool — Decorate a Python function as a Yera tool. # tool ``` tool( fn: Callable | None = None, creds: str | list[str] | None = None, insert_result: bool = True, ) → DecoratedTool | Callable[[Callable], DecoratedTool] ``` Decorate a Python function as a Yera tool. Tools are self-contained chunks of Python an `@app` can call into — the app's LLM drives control flow, deciding when and with what arguments to invoke each tool. Usable bare (`@tool`) or with keyword arguments (`@tool(creds=...)`). If `creds` is provided, the named credential groups are resolved from the active Yera profile and bound to the tool's context before the function body runs; the body reads them back via `tool_creds`. ## Parameters fn type: Callable | None = None The function being decorated when used bare. Left as `None` when the decorator is invoked with arguments. creds type: str | list[str] | None = None Credential group(s) the tool needs access to. A single group name, a list of group names, or `None` for no credentials. Group names are configured in the active Yera profile; the resolved keys appear as `.` in `tool_creds`. insert_result type: bool = True whether to add the return value of this tool to the active LLM context. ## Returns type: DecoratedTool | Callable[[Callable], DecoratedTool] A `DecoratedTool` callable that resolves credentials and runs the function under the tool credential context when invoked. When called with arguments (`fn is None`), returns a decorator that produces the wrapper. ## Raises InvalidToolCredsArgumentError If `creds` is not `None`, a `str`, or `list[str]`. Example: ```python @yr.tool(creds=["db"]) def get_customer(customer_id: str) -> dict: creds = yr.tool_creds() conn = psycopg.connect( host=creds.require("db.host"), port=creds.require("db.port"), user=creds.require("db.user"), password=creds.require("db.password"), ) with conn.cursor() as cur: cur.execute("SELECT * FROM customers WHERE id = %s", (customer_id,)) return cur.fetchone() ``` --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/exceptions/ # yera.tools.exceptions Tool-related user-facing errors. ## Symbols class InvalidToolCredsArgumentError — Raised when ``creds=`` is not ``None``, a ``str``, or ``list[str]``. class ToolDecoratorError — Raised when ``@tool`` is used with invalid arguments. # InvalidToolCredsArgumentError Inherits: `ToolDecoratorError` Raised when `creds=` is not `None`, a `str`, or `list[str]`. # ToolDecoratorError Inherits: `YeraError` Subclasses: `InvalidToolCredsArgumentError` Raised when `@tool` is used with invalid arguments. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/ # yera.tools.mcp MCP-backed Yera tools. ## Submodules auth catalogue client discovery exceptions importer lazy_loading metadata namespace oauth_browser oauth_callback oauth_device oauth_interaction oauth_profiles oauth_storage results schema signature task task_extension task_protocol tool --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/auth/ # yera.tools.mcp.auth Authentication support for MCP HTTP connections. ## Symbols def build_mcp_oauth_auth — Build MCP SDK OAuth authentication from Yera configuration. def mcp_connection_secrets — List the secrets an MCP connection owns in Yera's secret store. def mcp_header_identity — Build the secret identity for one connection-owned MCP header. def mcp_http_client — Provide an HTTP client configured for an MCP server. class MCPAuthenticationProbe — Detect authentication challenges without performing authorization. class MCPOAuthInteractionAdapter — Adapt Yera OAuth interaction to MCP SDK callback handlers. def resolve_mcp_headers — Resolve configured MCP HTTP headers. # build_mcp_oauth_auth ``` build_mcp_oauth_auth( server_name: str, server: MCPServerConfig, store: SecretStore, client_metadata: OAuthClientMetadata, interaction: OAuthInteraction | None = None, client_metadata_url: str | None = None, ) → OAuthClientProvider ``` Build MCP SDK OAuth authentication from Yera configuration. ## Parameters server_name type: str Yera name of the MCP server connection. server type: MCPServerConfig OAuth-authenticated MCP server configuration. store type: SecretStore Secret store containing OAuth protocol state. client_metadata type: OAuthClientMetadata OAuth client metadata used by the MCP SDK. interaction type: OAuthInteraction | None = None Optional presentation and callback implementation. client_metadata_url type: str | None = None Optional HTTPS CIMD identity for the OAuth client. ## Returns type: OAuthClientProvider HTTP authentication backed by persisted OAuth state. ## Raises TypeError If the server does not use OAuth authentication. # mcp_connection_secrets ``` mcp_connection_secrets( server: MCPServerConfig, ) → tuple[SecretIdentity, ...] ``` List the secrets an MCP connection owns in Yera's secret store. Static headers own none, because their values belong to the user's credential group rather than the connection. ## Parameters server type: MCPServerConfig MCP server connection configuration. ## Returns type: tuple[SecretIdentity, ...] Identities of the connection's header values or OAuth state. # mcp_header_identity ``` mcp_header_identity( secret_id: str, header: str, ) → SecretIdentity ``` Build the secret identity for one connection-owned MCP header. ## Parameters secret_id type: str Owner of the connection's header values. header type: str HTTP header name. ## Returns type: SecretIdentity Secret-store identity holding the header's value. # mcp_http_client ``` mcp_http_client( server: MCPServerConfig, http_client: httpx2.AsyncClient | None = None, server_name: str | None = None, secret_store: SecretStore | None = None, oauth_client_metadata: OAuthClientMetadata | None = None, oauth_interaction: OAuthInteraction | None = None, probe_authentication: bool = False, oauth_client_metadata_url: str | None = None, ) → AsyncIterator[httpx2.AsyncClient] ``` Provide an HTTP client configured for an MCP server. ## Parameters server type: MCPServerConfig MCP server connection configuration. http_client type: httpx2.AsyncClient | None = None Optional caller-owned client used without closing it. server_name type: str | None = None Optional configured connection name used in OAuth UX. secret_store type: SecretStore | None = None Optional OAuth secret-store override. oauth_client_metadata type: OAuthClientMetadata | None = None OAuth client metadata used by the MCP SDK. oauth_interaction type: OAuthInteraction | None = None Optional interactive authorization implementation. probe_authentication type: bool = False Whether HTTP 401 responses should be surfaced as MCP authentication challenges during explicit setup. oauth_client_metadata_url type: str | None = None Optional HTTPS CIMD identity passed to the OAuth provider. # MCPAuthenticationProbe Inherits: `httpx2.Auth` Detect authentication challenges without performing authorization. ## Methods async_auth_flow — Send one request and report an authentication challenge. # MCPAuthenticationProbe.async_auth_flow ``` async_auth_flow( request: httpx2.Request, ) → AsyncGenerator[httpx2.Request, httpx2.Response] ``` Send one request and report an authentication challenge. ## Parameters request type: httpx2.Request Outbound MCP request. ## Raises MCPAuthenticationRequiredError If the resource returns HTTP 401. # MCPOAuthInteractionAdapter Adapt Yera OAuth interaction to MCP SDK callback handlers. ## Methods present_authorization — Present an SDK authorization redirect through Yera. await_callback — Return Yera's captured callback in the MCP SDK representation. # MCPOAuthInteractionAdapter.present_authorization ``` present_authorization( authorization_url: str, ) → None ``` Present an SDK authorization redirect through Yera. ## Parameters authorization_url type: str Complete transient URL prepared by the SDK. # MCPOAuthInteractionAdapter.await_callback ``` await_callback() → AuthorizationCodeResult ``` Return Yera's captured callback in the MCP SDK representation. ## Returns type: AuthorizationCodeResult Authorization callback values expected by the MCP SDK. # resolve_mcp_headers ``` resolve_mcp_headers( server: MCPServerConfig, secret_store: SecretStore | None = None, ) → dict[str, str] ``` Resolve configured MCP HTTP headers. Connection-owned headers are read from the secret store. Static headers are read from the active credential group. ## Parameters server type: MCPServerConfig MCP server connection configuration. secret_store type: SecretStore | None = None Optional secret-store override for connection-owned headers. ## Returns type: dict[str, str] HTTP headers containing resolved values, or an empty mapping when the server does not authenticate with headers. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/catalogue/ # yera.tools.mcp.catalogue Rebuildable SQLite catalogue for discovered MCP tools. ## Symbols class MCPServerRecord — Metadata retained for one imported MCP server. class MCPToolRecord — Metadata retained for one tool discovered from an MCP server. class SQLiteMCPCatalogue — Cache discovered MCP metadata in a persistent, rebuildable database. # MCPServerRecord Metadata retained for one imported MCP server. # MCPToolRecord Metadata retained for one tool discovered from an MCP server. ## Methods from_discovered_tool — Build a catalogue record from MCP discovery metadata. # MCPToolRecord.from_discovered_tool ``` from_discovered_tool( server_name: str, tool: Tool, ) → Self ``` Build a catalogue record from MCP discovery metadata. ## Parameters server_name type: str Yera's configured name for the supplying server. tool type: Tool Tool definition returned by the MCP server. ## Returns type: Self A serializable catalogue record retaining the discovered metadata. # SQLiteMCPCatalogue Cache discovered MCP metadata in a persistent, rebuildable database. ## Methods __enter__ — Open the catalogue, rebuilding unsupported schemas. __exit__ — Close the catalogue connection. replace_server — Atomically replace one server and all its discovered tools. remove_server — Atomically remove one server and all its discovered tools. tools_for_server — Return one server's imported tools ordered by tool name. # SQLiteMCPCatalogue.__enter__ ``` __enter__() → SQLiteMCPCatalogue ``` Open the catalogue, rebuilding unsupported schemas. # SQLiteMCPCatalogue.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) → None ``` Close the catalogue connection. # SQLiteMCPCatalogue.replace_server ``` replace_server( server: MCPServerRecord, tools: list[MCPToolRecord], ) → None ``` Atomically replace one server and all its discovered tools. # SQLiteMCPCatalogue.remove_server ``` remove_server( server_name: str, ) → None ``` Atomically remove one server and all its discovered tools. # SQLiteMCPCatalogue.tools_for_server ``` tools_for_server( server_name: str, ) → list[MCPToolRecord] ``` Return one server's imported tools ordered by tool name. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/client/ # yera.tools.mcp.client Client boundary for MCP Streamable HTTP servers. ## Symbols class MCPClient — Communicate with one MCP server over Streamable HTTP. # MCPClient Communicate with one MCP server over Streamable HTTP. ## Methods list_tools — Return the tools advertised by the MCP server. call_tool — Call a tool and return its raw MCP result. start_tool — Start a tool call without waiting for a returned task. get_task — Return the current state of one server-backed task. update_task — Supply responses requested by an input-required task. cancel_task — Request cooperative cancellation of one server-backed task. # MCPClient.list_tools ``` list_tools() → list[Tool] ``` Return the tools advertised by the MCP server. # MCPClient.call_tool ``` call_tool( name: str, arguments: Mapping[str, Any], ) → CallToolResult ``` Call a tool and return its raw MCP result. # MCPClient.start_tool ``` start_tool( name: str, arguments: Mapping[str, Any], ) → CallToolResult | CreateTaskResult ``` Start a tool call without waiting for a returned task. ## Parameters name type: str Exact tool name advertised by the MCP server. arguments type: Mapping[str, Any] Validated values for the tool input schema. ## Returns type: CallToolResult | CreateTaskResult An immediate tool result or the initial server-created task state. # MCPClient.get_task ``` get_task( task_id: str, ) → GetTaskResult ``` Return the current state of one server-backed task. ## Parameters task_id type: str Stable identifier minted by the MCP server. ## Returns type: GetTaskResult Current task state and any status-specific payload. # MCPClient.update_task ``` update_task( task_id: str, input_responses: InputResponses, ) → TaskAcknowledgementResult ``` Supply responses requested by an input-required task. ## Parameters task_id type: str Stable identifier minted by the MCP server. input_responses type: InputResponses Responses keyed by outstanding request identity. ## Returns type: TaskAcknowledgementResult The server's update acknowledgement. # MCPClient.cancel_task ``` cancel_task( task_id: str, ) → TaskAcknowledgementResult ``` Request cooperative cancellation of one server-backed task. ## Parameters task_id type: str Stable identifier minted by the MCP server. ## Returns type: TaskAcknowledgementResult The server's cancellation acknowledgement. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/discovery/ # yera.tools.mcp.discovery Discover remote MCP servers from domain-level metadata. ## Symbols def discover_mcp_servers — Discover Streamable HTTP MCP servers advertised by a domain. class DiscoveredMCPServer — Describe a remote MCP server found during discovery. # discover_mcp_servers ``` discover_mcp_servers( reference: str, http_client: httpx2.AsyncClient, ) → list[DiscoveredMCPServer] ``` Discover Streamable HTTP MCP servers advertised by a domain. ## Parameters reference type: str Website or domain URL used as the discovery origin. http_client type: httpx2.AsyncClient Caller-owned client used for metadata requests. ## Returns type: list[DiscoveredMCPServer] Every compatible server advertised by the domain, in catalog order. ## Raises httpx2.HTTPError If catalog or Server Card retrieval fails. TypeError If the AI Catalog document has an invalid root shape. # DiscoveredMCPServer Describe a remote MCP server found during discovery. ## Attributes name type: str Stable server identifier from its Server Card. title type: str Human-readable server title. description type: str | None Human-readable description when supplied. url type: str Streamable HTTP endpoint. client_profile type: str | None Optional trusted OAuth client profile selected by Yera. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/exceptions/ # yera.tools.mcp.exceptions Exceptions raised by MCP-backed Yera tools. ## Symbols class MCPAuthenticationError — Base exception for MCP authentication failures. class MCPAuthenticationRequiredError — Raised when an MCP resource requires authentication. class MCPError — Base exception for MCP tool integration failures. class MCPOAuthCallbackError — Raised when an OAuth callback reports failure. class MCPOAuthCallbackTimeoutError — Raised when OAuth authorization does not return before its deadline. class MCPOAuthCallbackUnavailableError — Raised when Yera cannot bind the configured OAuth callback endpoint. class MCPOAuthCancelledError — Raised when the user cancels OAuth authorization. class MCPOAuthDeviceDeniedError — Raised when the user denies device authorization. class MCPOAuthDeviceError — Raised when device authorization reports a terminal OAuth error. class MCPOAuthDeviceExpiredError — Raised when device authorization expires before approval. class MCPTaskCancelledError — Raised when an MCP task reaches the cancelled state. class MCPTaskError — Base exception for MCP task lifecycle failures. class MCPTaskExecutionRequiredError — Raised when an MCP tool requires unsupported task execution. class MCPTaskExpiredError — Raised when an MCP task has expired or is no longer available. class MCPTaskFailedError — Raised when an MCP task reaches the failed state. class MCPTaskInputRequiredError — Raised when an MCP task requires unsupported client input. class MCPToolCallError — Raised when an MCP server reports that a tool call failed. # MCPAuthenticationError Inherits: `MCPError` Subclasses: `MCPAuthenticationRequiredError`, `MCPOAuthCallbackError`, `MCPOAuthCallbackTimeoutError`, `MCPOAuthCallbackUnavailableError`, `MCPOAuthCancelledError`, `MCPOAuthDeviceDeniedError`, `MCPOAuthDeviceError`, `MCPOAuthDeviceExpiredError` Base exception for MCP authentication failures. # MCPAuthenticationRequiredError Inherits: `MCPAuthenticationError` Raised when an MCP resource requires authentication. ## Attributes server_url MCP resource that rejected the request. challenge Complete `WWW-Authenticate` challenge, when supplied. # MCPError Inherits: `YeraError` Subclasses: `MCPAuthenticationError`, `MCPTaskError`, `MCPTaskExecutionRequiredError`, `MCPToolCallError` Base exception for MCP tool integration failures. # MCPOAuthCallbackError Inherits: `MCPAuthenticationError` Raised when an OAuth callback reports failure. ## Attributes error OAuth error code returned by the authorization server. description Optional human-readable provider detail. # MCPOAuthCallbackTimeoutError Inherits: `MCPAuthenticationError` Raised when OAuth authorization does not return before its deadline. # MCPOAuthCallbackUnavailableError Inherits: `MCPAuthenticationError` Raised when Yera cannot bind the configured OAuth callback endpoint. # MCPOAuthCancelledError Inherits: `MCPAuthenticationError` Raised when the user cancels OAuth authorization. # MCPOAuthDeviceDeniedError Inherits: `MCPAuthenticationError` Raised when the user denies device authorization. # MCPOAuthDeviceError Inherits: `MCPAuthenticationError` Raised when device authorization reports a terminal OAuth error. ## Attributes error OAuth error code returned by the authorization server. description Optional human-readable provider detail. # MCPOAuthDeviceExpiredError Inherits: `MCPAuthenticationError` Raised when device authorization expires before approval. # MCPTaskCancelledError Inherits: `MCPTaskError` Raised when an MCP task reaches the cancelled state. # MCPTaskError Inherits: `MCPError` Subclasses: `MCPTaskCancelledError`, `MCPTaskExpiredError`, `MCPTaskFailedError`, `MCPTaskInputRequiredError` Base exception for MCP task lifecycle failures. # MCPTaskExecutionRequiredError Inherits: `MCPError` Raised when an MCP tool requires unsupported task execution. # MCPTaskExpiredError Inherits: `MCPTaskError` Raised when an MCP task has expired or is no longer available. # MCPTaskFailedError Inherits: `MCPTaskError` Raised when an MCP task reaches the failed state. # MCPTaskInputRequiredError Inherits: `MCPTaskError` Raised when an MCP task requires unsupported client input. # MCPToolCallError Inherits: `MCPError` Raised when an MCP server reports that a tool call failed. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/importer/ # yera.tools.mcp.importer Import metadata from live MCP servers. ## Symbols def import_mcp_server — Import one live MCP server into the local catalogue. # import_mcp_server ``` import_mcp_server( name: str, config: MCPServerConfig, catalogue: SQLiteMCPCatalogue, probe_authentication: bool = False, secret_store: SecretStore | None = None, oauth_client_metadata: OAuthClientMetadata | None = None, oauth_interaction: OAuthInteraction | None = None, http_client: httpx2.AsyncClient | None = None, ) → None ``` Import one live MCP server into the local catalogue. ## Parameters name type: str Configured name of the MCP server. config type: MCPServerConfig Connection configuration for the server. catalogue type: SQLiteMCPCatalogue Open catalogue receiving the discovered metadata. http_client type: httpx2.AsyncClient | None = None Optional caller-owned HTTP client. probe_authentication type: bool = False Whether setup should surface HTTP authentication challenges before configuration is persisted. secret_store type: SecretStore | None = None Optional OAuth secret-store override. oauth_client_metadata type: OAuthClientMetadata | None = None OAuth client metadata used for authorization. oauth_interaction type: OAuthInteraction | None = None Optional interactive OAuth presentation. ## Returns type: None None. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/lazy_loading/ # yera.tools.mcp.lazy_loading Lazy access to MCP tools selected by the active profile. ## Symbols def invalidate_mcp_tools — Discard the cached MCP tool namespace. # invalidate_mcp_tools ``` invalidate_mcp_tools() → None ``` Discard the cached MCP tool namespace. The next access rebuilds the namespace from the active profile and imported MCP catalogue. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/metadata/ # yera.tools.mcp.metadata Public metadata exposed by MCP-backed Yera tools. ## Symbols class MCPServerMetadata — Describe the configured server that supplied an MCP tool. class MCPToolAnnotations — Retain the behavioural hints advertised by an MCP server. class MCPToolIcon — Describe an icon advertised for an MCP tool. class MCPToolMetadata — Describe an imported MCP tool without refreshing the remote server. # MCPServerMetadata Describe the configured server that supplied an MCP tool. ## Attributes name type: str Yera's configured name for the server. url type: str Streamable HTTP endpoint used to reach the server. # MCPToolAnnotations Retain the behavioural hints advertised by an MCP server. These values are untrusted hints and must not be treated as an authorization or security boundary. ## Attributes title type: str | None Alternate human-readable title. read_only_hint type: bool | None Whether the server claims the tool is read-only. destructive_hint type: bool | None Whether the server claims writes may be destructive. idempotent_hint type: bool | None Whether repeated calls should have no additional effect. open_world_hint type: bool | None Whether the tool may interact with external entities. ## Methods from_dict — Build annotations from serialized MCP protocol metadata. # MCPToolAnnotations.from_dict ``` from_dict( values: Mapping[str, object] | None, ) → MCPToolAnnotations ``` Build annotations from serialized MCP protocol metadata. ## Parameters values type: Mapping[str, object] | None Serialized annotations, or `None` when absent. ## Returns type: MCPToolAnnotations Parsed server-supplied annotation hints. # MCPToolIcon Describe an icon advertised for an MCP tool. ## Attributes src type: str Icon URL or data URI supplied by the server. mime_type type: str | None Optional advertised media type. sizes type: tuple[str, ...] Optional supported icon sizes. theme type: Literal['light', 'dark'] | None Optional light or dark theme restriction. ## Methods from_dict — Build an icon description from serialized MCP metadata. # MCPToolIcon.from_dict ``` from_dict( values: Mapping[str, object], ) → MCPToolIcon ``` Build an icon description from serialized MCP metadata. ## Parameters values type: Mapping[str, object] Serialized icon metadata. ## Returns type: MCPToolIcon Parsed icon metadata without fetching its source. # MCPToolMetadata Describe an imported MCP tool without refreshing the remote server. ## Attributes path type: str Fully qualified Python path beneath `yr.mcp_tools`. python_name type: str Python-safe leaf name. remote_name type: str Exact tool name advertised by the MCP server. server type: MCPServerMetadata Configured server identity. title type: str | None Preferred human-readable title. description type: str | None Human-readable tool description. input_schema type: Mapping[str, object] Advertised JSON Schema for tool arguments. output_schema type: Mapping[str, object] | None Optional advertised JSON Schema for structured output. annotations type: MCPToolAnnotations Untrusted behavioural hints supplied by the server. icons type: tuple[MCPToolIcon, ...] Icon descriptions retained without fetching their contents. task_support type: Literal['forbidden', 'optional', 'required'] | None Advertised legacy task-execution support. extensions type: Mapping[str, object] Arbitrary namespaced MCP metadata. ## Methods from_record — Build public metadata from a locally cached catalogue record. # MCPToolMetadata.from_record ``` from_record( server_name: str, server_url: str, record: MCPToolRecord, ) → MCPToolMetadata ``` Build public metadata from a locally cached catalogue record. ## Parameters server_name type: str Yera's configured name for the server. server_url type: str Configured Streamable HTTP endpoint. record type: MCPToolRecord Cached tool discovery metadata. ## Returns type: MCPToolMetadata Public metadata for local inspection. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/namespace/ # yera.tools.mcp.namespace Navigable namespace of configured MCP tools. ## Symbols def build_mcp_tool_namespace — Build the MCP tool namespace for selected servers. class MCPToolNamespace — A navigable tree of MCP-backed Yera tools. # build_mcp_tool_namespace ``` build_mcp_tool_namespace( servers: Mapping[str, MCPServerConfig], catalogue: SQLiteMCPCatalogue, ) → MCPToolNamespace ``` Build the MCP tool namespace for selected servers. ## Parameters servers type: Mapping[str, MCPServerConfig] MCP server connections selected by the active profile. catalogue type: SQLiteMCPCatalogue Open catalogue containing imported tool metadata. ## Returns type: MCPToolNamespace A namespace containing fully qualified MCP tool paths. # MCPToolNamespace Inherits: `PathTree[MCPTool]` A navigable tree of MCP-backed Yera tools. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/oauth_browser/ # yera.tools.mcp.oauth_browser Browser presentation for MCP OAuth authorization. ## Symbols class BrowserOAuthDeviceInteraction — Open device verification and present its user instructions. class BrowserOAuthInteraction — Open OAuth authorization and delegate callback capture. # BrowserOAuthDeviceInteraction Open device verification and present its user instructions. ## Methods present_device_authorization — Open verification and display its instructions. # BrowserOAuthDeviceInteraction.present_device_authorization ``` present_device_authorization( request: OAuthDeviceAuthorizationRequest, ) → None ``` Open verification and display its instructions. ## Parameters request type: OAuthDeviceAuthorizationRequest Non-secret device-verification context. # BrowserOAuthInteraction Open OAuth authorization and delegate callback capture. ## Methods present_authorization — Open the transient authorization URL. await_callback — Wait for and return the captured OAuth callback. # BrowserOAuthInteraction.present_authorization ``` present_authorization( request: OAuthAuthorizationRequest, ) → None ``` Open the transient authorization URL. ## Parameters request type: OAuthAuthorizationRequest Authorization context prepared by the MCP SDK. ## Raises MCPAuthenticationError If no browser accepts the URL. # BrowserOAuthInteraction.await_callback ``` await_callback() → OAuthAuthorizationResult ``` Wait for and return the captured OAuth callback. ## Returns type: OAuthAuthorizationResult Authorization code, state, and optional issuer. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/oauth_callback/ # yera.tools.mcp.oauth_callback OAuth callback parsing for MCP authorization. ## Symbols class LoopbackOAuthCallbackServer — Serve one OAuth callback on a temporary loopback port. class OAuthCallbackReceiver — Coordinate one OAuth callback with a waiting authorization flow. class OAuthCallbackSession — Expose an OAuth redirect destination and its eventual result. def parse_oauth_callback — Validate callback parameters returned by an authorization server. def register_oauth_callback_route — Register an OAuth redirect endpoint on a FastAPI application. # LoopbackOAuthCallbackServer Serve one OAuth callback on a temporary loopback port. ## Methods __aenter__ — Start the temporary callback server. __aexit__ — Stop the callback server and release its socket. await_result — Wait for the OAuth callback. # LoopbackOAuthCallbackServer.__aenter__ ``` __aenter__() → Self ``` Start the temporary callback server. # LoopbackOAuthCallbackServer.__aexit__ ``` __aexit__( exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) → None ``` Stop the callback server and release its socket. # LoopbackOAuthCallbackServer.await_result ``` await_result() → OAuthAuthorizationResult ``` Wait for the OAuth callback. ## Returns type: OAuthAuthorizationResult Validated callback values. # OAuthCallbackReceiver Coordinate one OAuth callback with a waiting authorization flow. ## Methods capture — Capture callback parameters and release the waiter. await_result — Wait for the captured callback result. # OAuthCallbackReceiver.capture ``` capture( parameters: Mapping[str, str], ) → None ``` Capture callback parameters and release the waiter. ## Parameters parameters type: Mapping[str, str] Decoded OAuth callback query parameters. # OAuthCallbackReceiver.await_result ``` await_result() → OAuthAuthorizationResult ``` Wait for the captured callback result. ## Returns type: OAuthAuthorizationResult Validated authorization callback values. ## Raises MCPOAuthCallbackTimeoutError If no callback arrives in time. Exception If callback validation failed. # OAuthCallbackSession Inherits: `Protocol` Expose an OAuth redirect destination and its eventual result. ## Methods await_result — Wait for the authorization callback. # OAuthCallbackSession.await_result ``` await_result() → OAuthAuthorizationResult ``` Wait for the authorization callback. ## Returns type: OAuthAuthorizationResult The captured authorization code and state. # parse_oauth_callback ``` parse_oauth_callback( parameters: Mapping[str, str], ) → OAuthAuthorizationResult ``` Validate callback parameters returned by an authorization server. ## Parameters parameters type: Mapping[str, str] Decoded OAuth callback query parameters. ## Returns type: OAuthAuthorizationResult Authorization values required by the MCP SDK. ## Raises MCPOAuthCallbackError If the authorization server reports failure. ValueError If the callback omits its authorization code or state. # register_oauth_callback_route ``` register_oauth_callback_route( app: FastAPI, receiver: OAuthCallbackReceiver, path: str = '/oauth/callback', ) → None ``` Register an OAuth redirect endpoint on a FastAPI application. ## Parameters app type: FastAPI Application receiving the callback route. receiver type: OAuthCallbackReceiver Receiver coordinating the callback with OAuth setup. path type: str = '/oauth/callback' URL path registered for the authorization redirect. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/oauth_device/ # yera.tools.mcp.oauth_device OAuth device-authorization support for MCP connections. ## Symbols def authorize_mcp_device — Authorize an MCP connection using the OAuth device grant. def authorize_mcp_device_profile — Authorize an MCP connection through a predefined device profile. class OAuthDeviceAuthorizationResponse — Represent a validated OAuth device-authorization response. def poll_device_token — Poll an OAuth token endpoint for an approved device authorization. def present_device_authorization — Present safe device-verification instructions to the user. def request_device_authorization — Start device authorization for a public OAuth client. # authorize_mcp_device ``` authorize_mcp_device( http_client: httpx2.AsyncClient, server_name: str, server_url: str, authorization_server: str, device_authorization_endpoint: str, token_endpoint: str, client_id: str, scopes: tuple[str, ...], interaction: OAuthDeviceInteraction, sleep: Callable[[float], Awaitable[None]] = anyio.sleep, clock: Callable[[], float] = monotonic, ) → OAuthToken ``` Authorize an MCP connection using the OAuth device grant. ## Parameters http_client type: httpx2.AsyncClient Client used for OAuth endpoint requests. server_name type: str Yera name of the MCP connection. server_url type: str Streamable HTTP endpoint being authorized. authorization_server type: str Issuer performing authorization. device_authorization_endpoint type: str Endpoint issuing the device code. token_endpoint type: str Endpoint polled for issued tokens. client_id type: str Public identifier registered for Yera. scopes type: tuple[str, ...] OAuth scopes requested for the MCP connection. interaction type: OAuthDeviceInteraction Presentation implementation showing verification details. sleep type: Callable[[float], Awaitable[None]] = anyio.sleep Awaitable delay implementation used between token requests. clock type: Callable[[], float] = monotonic Monotonic clock used to enforce local expiry. ## Returns type: OAuthToken Validated OAuth tokens issued after user approval. # authorize_mcp_device_profile ``` authorize_mcp_device_profile( http_client: httpx2.AsyncClient, profile: MCPOAuthClientProfile, server_name: str, server_url: str, interaction: OAuthDeviceInteraction, sleep: Callable[[float], Awaitable[None]] = anyio.sleep, clock: Callable[[], float] = monotonic, ) → OAuthToken ``` Authorize an MCP connection through a predefined device profile. ## Parameters http_client type: httpx2.AsyncClient Client used for OAuth endpoint requests. profile type: MCPOAuthClientProfile Registered public device-authorization profile. server_name type: str Yera name of the MCP connection. server_url type: str Streamable HTTP endpoint being authorized. interaction type: OAuthDeviceInteraction Presentation implementation showing verification details. sleep type: Callable[[float], Awaitable[None]] = anyio.sleep Awaitable delay implementation used between token requests. clock type: Callable[[], float] = monotonic Monotonic clock used to enforce local expiry. ## Returns type: OAuthToken Validated OAuth tokens issued after user approval. ## Raises TypeError If the profile does not use device authorization. MCPAuthenticationError If the profile has no deployed client ID. # OAuthDeviceAuthorizationResponse Inherits: `BaseModel` Represent a validated OAuth device-authorization response. ## Attributes device_code type: SecretStr Secret polling credential issued to Yera. user_code type: str Short code presented to the user. verification_uri type: str Page at which the user enters the code. verification_uri_complete type: str | None Optional link containing the user code. expires_in type: int Lifetime of the device authorization in seconds. interval type: int Minimum polling interval in seconds. # poll_device_token ``` poll_device_token( http_client: httpx2.AsyncClient, endpoint: str, client_id: str, authorization: OAuthDeviceAuthorizationResponse, sleep: Callable[[float], Awaitable[None]] = anyio.sleep, clock: Callable[[], float] = monotonic, ) → OAuthToken ``` Poll an OAuth token endpoint for an approved device authorization. ## Parameters http_client type: httpx2.AsyncClient Client used to call the authorization server. endpoint type: str OAuth token endpoint. client_id type: str Public identifier registered for Yera. authorization type: OAuthDeviceAuthorizationResponse Device authorization containing the polling credential. sleep type: Callable[[float], Awaitable[None]] = anyio.sleep Awaitable delay implementation used between requests. clock type: Callable[[], float] = monotonic Monotonic clock used to enforce local expiry. ## Returns type: OAuthToken Validated OAuth tokens issued by the authorization server. ## Raises httpx2.HTTPStatusError If the token endpoint rejects the request. pydantic.ValidationError If the token response is invalid. # present_device_authorization ``` present_device_authorization( interaction: OAuthDeviceInteraction, server_name: str, server_url: str, authorization_server: str, scopes: tuple[str, ...], response: OAuthDeviceAuthorizationResponse, ) → None ``` Present safe device-verification instructions to the user. ## Parameters interaction type: OAuthDeviceInteraction Presentation implementation receiving the instructions. server_name type: str Yera name of the MCP connection. server_url type: str Streamable HTTP endpoint being authorized. authorization_server type: str Issuer performing device authorization. scopes type: tuple[str, ...] OAuth scopes requested for the MCP connection. response type: OAuthDeviceAuthorizationResponse Validated device-authorization response. # request_device_authorization ``` request_device_authorization( http_client: httpx2.AsyncClient, endpoint: str, client_id: str, scopes: tuple[str, ...] = (), ) → OAuthDeviceAuthorizationResponse ``` Start device authorization for a public OAuth client. ## Parameters http_client type: httpx2.AsyncClient Client used to call the authorization server. endpoint type: str Device-authorization endpoint. client_id type: str Public identifier registered for Yera. scopes type: tuple[str, ...] = () OAuth scopes requested for the MCP connection. ## Returns type: OAuthDeviceAuthorizationResponse Validated device authorization and verification instructions. ## Raises httpx2.HTTPStatusError If the authorization server rejects the request. pydantic.ValidationError If the response does not follow RFC 8628. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/oauth_interaction/ # yera.tools.mcp.oauth_interaction Presentation-neutral interaction contracts for MCP OAuth. ## Symbols class OAuthAuthorizationRequest — Describe an OAuth authorization redirect for presentation. class OAuthAuthorizationResult — Carry transient values captured from an OAuth callback. class OAuthDeviceAuthorizationRequest — Describe a device-authorization verification step for presentation. class OAuthDeviceInteraction — Present a device-authorization verification step to the user. class OAuthInteraction — Present OAuth authorization and capture its callback result. # OAuthAuthorizationRequest Describe an OAuth authorization redirect for presentation. The authorization URL is transient protocol state and must not be persisted or written to logs. ## Attributes server_name type: str Yera name of the MCP connection. server_url type: str Streamable HTTP endpoint being authorized. authorization_server type: str Discovered authorization-server issuer. resource type: str Protected OAuth resource requested by the MCP server. scopes type: tuple[str, ...] OAuth scopes requested from the user. authorization_url type: str Complete transient browser authorization URL. # OAuthAuthorizationResult Carry transient values captured from an OAuth callback. These values must remain in memory and must not be persisted or logged. ## Attributes code type: str Short-lived authorization code returned by the server. state type: str State value returned for request-correlation validation. issuer type: str | None Optional authorization-response issuer supplied under RFC 9207. # OAuthDeviceAuthorizationRequest Describe a device-authorization verification step for presentation. The device code is secret protocol state and is intentionally excluded. ## Attributes server_name type: str Yera name of the MCP connection. server_url type: str Streamable HTTP endpoint being authorized. authorization_server type: str Discovered authorization-server issuer. scopes type: tuple[str, ...] OAuth scopes requested from the user. verification_uri type: str Page at which the user enters the displayed code. verification_uri_complete type: str | None Optional link containing the user code. user_code type: str Short code displayed for user verification. expires_in_seconds type: int Lifetime of the verification request. # OAuthDeviceInteraction Inherits: `Protocol` Present a device-authorization verification step to the user. ## Methods present_device_authorization — Present device verification instructions. # OAuthDeviceInteraction.present_device_authorization ``` present_device_authorization( request: OAuthDeviceAuthorizationRequest, ) → None ``` Present device verification instructions. ## Parameters request type: OAuthDeviceAuthorizationRequest Non-secret verification context to present. # OAuthInteraction Inherits: `Protocol` Present OAuth authorization and capture its callback result. ## Methods present_authorization — Present an authorization request to the user. await_callback — Wait for the authorization server callback. # OAuthInteraction.present_authorization ``` present_authorization( request: OAuthAuthorizationRequest, ) → None ``` Present an authorization request to the user. ## Parameters request type: OAuthAuthorizationRequest Transient authorization context to present. # OAuthInteraction.await_callback ``` await_callback() → OAuthAuthorizationResult ``` Wait for the authorization server callback. ## Returns type: OAuthAuthorizationResult The captured authorization code and state. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/oauth_profiles/ # yera.tools.mcp.oauth_profiles Predefined OAuth client behavior for MCP providers. ## Symbols def get_mcp_oauth_client_profile — Return a predefined MCP OAuth client profile. class MCPOAuthClientProfile — Describe how Yera authenticates with one MCP provider. def resolve_mcp_oauth_client_profile — Resolve the predefined profile referenced by OAuth configuration. def yera_oauth_client_metadata_document — Return Yera's canonical public OAuth client metadata document. # get_mcp_oauth_client_profile ``` get_mcp_oauth_client_profile( name: str, ) → MCPOAuthClientProfile | None ``` Return a predefined MCP OAuth client profile. ## Parameters name type: str Stable profile name from MCP server configuration. ## Returns type: MCPOAuthClientProfile | None The matching client profile, or `None` when it is unknown. # MCPOAuthClientProfile Inherits: `BaseModel` Describe how Yera authenticates with one MCP provider. ## Attributes name type: str Stable name persisted in MCP server configuration. client_kind type: Literal['public', 'confidential'] Whether the OAuth client can protect a client secret. grant_type type: Literal['authorization_code', 'device_code'] OAuth grant used to authorize the user. registration_method type: Literal['cimd', 'dcr', 'pre_registered'] How the provider recognizes Yera as a client. callback_strategy type: Literal['none', 'ephemeral_loopback', 'fixed_loopback', 'hosted'] How authorization results return to Yera. availability type: Literal['open', 'vendor_approval', 'internal_only'] Whether users may connect without provider approval. supports_static_token type: bool Whether users may supply a token instead. client_id type: str | None Optional public identifier assigned to Yera by the provider. client_metadata_url type: str | None Optional HTTPS Client ID Metadata Document URL. device_authorization_endpoint type: str | None Optional endpoint issuing device codes. token_endpoint type: str | None Optional endpoint issuing OAuth tokens. default_scopes type: tuple[str, ...] Provider-specific scopes requested by default. ## Methods require_client_id — Return the profile's deployed OAuth client identifier. # MCPOAuthClientProfile.require_client_id ``` require_client_id() → str ``` Return the profile's deployed OAuth client identifier. ## Returns type: str Public OAuth client identifier configured for this Yera build. ## Raises MCPAuthenticationError If the client has not been registered. # resolve_mcp_oauth_client_profile ``` resolve_mcp_oauth_client_profile( auth: MCPOAuthAuth, ) → MCPOAuthClientProfile | None ``` Resolve the predefined profile referenced by OAuth configuration. ## Parameters auth type: MCPOAuthAuth Persisted OAuth authentication configuration. ## Returns type: MCPOAuthClientProfile | None The selected predefined profile, or `None` for generic OAuth. ## Raises MCPAuthenticationError If an explicitly selected profile is unknown. # yera_oauth_client_metadata_document ``` yera_oauth_client_metadata_document() → dict[str, object] ``` Return Yera's canonical public OAuth client metadata document. ## Returns type: dict[str, object] JSON-compatible CIMD metadata to publish at Yera's client ID URL. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/oauth_storage/ # yera.tools.mcp.oauth_storage Persistent secret storage for MCP OAuth protocol state. ## Symbols def decode_oauth_client_info — Decode OAuth client registration from an opaque secret. def decode_oauth_tokens — Decode an OAuth token bundle from an opaque secret. def encode_oauth_client_info — Encode OAuth client registration as an opaque secret. def encode_oauth_tokens — Encode a complete OAuth token bundle as an opaque secret. def oauth_client_info_identity — Build the secret identity for OAuth client registration. def oauth_token_identity — Build the secret identity for one OAuth token bundle. class SecretStoreOAuthStorage — Adapt Yera secret storage to the MCP SDK OAuth storage contract. # decode_oauth_client_info ``` decode_oauth_client_info( value: SecretValue, ) → OAuthClientInformationFull ``` Decode OAuth client registration from an opaque secret. ## Parameters value type: SecretValue Versioned opaque value read from the Yera secret store. ## Returns type: OAuthClientInformationFull The validated OAuth client registration. # decode_oauth_tokens ``` decode_oauth_tokens( value: SecretValue, ) → OAuthToken ``` Decode an OAuth token bundle from an opaque secret. ## Parameters value type: SecretValue Versioned opaque value read from the Yera secret store. ## Returns type: OAuthToken The validated OAuth token bundle. # encode_oauth_client_info ``` encode_oauth_client_info( client_info: OAuthClientInformationFull, ) → SecretValue ``` Encode OAuth client registration as an opaque secret. ## Parameters client_info type: OAuthClientInformationFull Registration returned by the authorization server. ## Returns type: SecretValue A versioned opaque value suitable for the Yera secret store. # encode_oauth_tokens ``` encode_oauth_tokens( tokens: OAuthToken, ) → SecretValue ``` Encode a complete OAuth token bundle as an opaque secret. ## Parameters tokens type: OAuthToken Tokens returned by the OAuth authorization server. ## Returns type: SecretValue A versioned opaque value suitable for the Yera secret store. # oauth_client_info_identity ``` oauth_client_info_identity( authorization_id: str, ) → SecretIdentity ``` Build the secret identity for OAuth client registration. ## Parameters authorization_id type: str Stable identity of the OAuth authorization. ## Returns type: SecretIdentity Secret-store identity for registered client information. # oauth_token_identity ``` oauth_token_identity( authorization_id: str, ) → SecretIdentity ``` Build the secret identity for one OAuth token bundle. ## Parameters authorization_id type: str Stable identity of the OAuth authorization. ## Returns type: SecretIdentity Secret-store identity for the authorization's tokens. # SecretStoreOAuthStorage Adapt Yera secret storage to the MCP SDK OAuth storage contract. ## Methods get_tokens — Return stored OAuth tokens when present. get_client_info — Return stored OAuth client registration when present. set_tokens — Create or replace the stored OAuth token bundle. set_client_info — Create or replace stored OAuth client registration. # SecretStoreOAuthStorage.get_tokens ``` get_tokens() → OAuthToken | None ``` Return stored OAuth tokens when present. ## Returns type: OAuthToken | None The stored token bundle, or `None` before authorization. # SecretStoreOAuthStorage.get_client_info ``` get_client_info() → OAuthClientInformationFull | None ``` Return stored OAuth client registration when present. ## Returns type: OAuthClientInformationFull | None Registered client information, or `None` when unavailable. # SecretStoreOAuthStorage.set_tokens ``` set_tokens( tokens: OAuthToken, ) → None ``` Create or replace the stored OAuth token bundle. ## Parameters tokens type: OAuthToken Complete token response supplied by the MCP SDK. # SecretStoreOAuthStorage.set_client_info ``` set_client_info( client_info: OAuthClientInformationFull, ) → None ``` Create or replace stored OAuth client registration. ## Parameters client_info type: OAuthClientInformationFull Registration supplied by the MCP SDK. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/results/ # yera.tools.mcp.results Conversion of MCP results into Yera-supported Python values. ## Symbols def convert_tool_result — Convert an MCP tool result into its declared Python type. # convert_tool_result ``` convert_tool_result( result: CallToolResult, result_type: type, ) → object ``` Convert an MCP tool result into its declared Python type. ## Parameters result type: CallToolResult The raw result returned by the MCP server. result_type type: type The generated Yera-supported result type. ## Returns type: object The validated and coerced Python value. ## Raises MCPToolCallError If the MCP server reports that the tool call failed. TypeError If the successful result does not contain structured content. ValueError If the result cannot be coerced to its declared type. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/schema/ # yera.tools.mcp.schema Compile MCP JSON Schemas into Yera Struct types. ## Symbols def generation_struct_from_json_schema — Compile MCP arguments for sparse LLM structured generation. def struct_from_json_schema — Compile an MCP object schema into a dynamic Yera Struct type. def type_from_json_schema — Compile JSON Schema into a Yera-supported Python type. def type_from_mcp_output_schema — Compile an MCP tool output schema into its Python return type. # generation_struct_from_json_schema ``` generation_struct_from_json_schema( name: str, schema: dict[str, object], ) → type[Struct] ``` Compile MCP arguments for sparse LLM structured generation. Non-required properties accept null so strict structured-output providers can express omission. The resulting values must still be reduced and validated through the ordinary execution structure. ## Parameters name type: str Name assigned to the generated Struct class. schema type: dict[str, object] MCP JSON Schema describing the tool arguments. ## Returns type: type[Struct] A dynamic Struct subclass suitable only for argument generation. # struct_from_json_schema ``` struct_from_json_schema( name: str, schema: dict[str, object], ) → type[Struct] ``` Compile an MCP object schema into a dynamic Yera Struct type. ## Parameters name type: str Name assigned to the generated Struct class. schema type: dict[str, object] MCP JSON Schema describing the tool arguments. ## Returns type: type[Struct] A dynamic Struct subclass validating those arguments. ## Raises ValueError If the root is not an object schema or a property uses an unsupported schema shape. # type_from_json_schema ``` type_from_json_schema( name: str, schema: dict[str, object], ) → object ``` Compile JSON Schema into a Yera-supported Python type. Unlike tool input compilation, the schema root may describe any supported JSON value rather than requiring an object. ## Parameters name type: str Name used for any generated Struct classes. schema type: dict[str, object] JSON Schema to compile. ## Returns type: object A Python annotation suitable for Yera's coercion infrastructure. # type_from_mcp_output_schema ``` type_from_mcp_output_schema( name: str, schema: dict[str, object], ) → object ``` Compile an MCP tool output schema into its Python return type. MCP servers represent scalar returns as an object containing one required property named `result`. This wrapper belongs to the protocol and is not exposed to Python callers. ## Parameters name type: str Name used for any generated Struct classes. schema type: dict[str, object] MCP output schema advertised by the server. ## Returns type: object The unwrapped scalar type or compiled structured result type. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/signature/ # yera.tools.mcp.signature Python signature generation for imported MCP tools. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/task/ # yera.tools.mcp.task Public lifecycle values for MCP tasks. ## Symbols class MCPTask — Represent an immediate or server-backed MCP tool execution. class MCPTaskState — Describe one observed state of a server-backed MCP task. # MCPTask Inherits: `Generic[ResultT]` Represent an immediate or server-backed MCP tool execution. ## Methods async_refresh — Refresh and return the latest server-reported task state. async_cancel — Cancel this server-backed task and return its resulting state. async_update — Submit requested input and return the resulting task state. async_wait — Wait for completion and return the converted tool result. refresh — Refresh and return the latest server-reported task state. cancel — Cancel this server-backed task and return its resulting state. update — Submit requested input and return the resulting task state. wait — Wait synchronously for completion and return the converted result. # MCPTask.async_refresh ``` async_refresh() → MCPTaskState ``` Refresh and return the latest server-reported task state. ## Returns type: MCPTaskState The latest immutable task state. Immediate tasks retain their completed local state. ## Raises RuntimeError If a server-backed task has no refresh operation. # MCPTask.async_cancel ``` async_cancel() → MCPTaskState ``` Cancel this server-backed task and return its resulting state. ## Returns type: MCPTaskState The task state observed after the server acknowledges cancellation. ## Raises RuntimeError If the task is already complete or cannot be cancelled. # MCPTask.async_update ``` async_update( input_responses: InputResponses, ) → MCPTaskState ``` Submit requested input and return the resulting task state. ## Parameters input_responses type: InputResponses Responses keyed by outstanding request identity. ## Returns type: MCPTaskState The task state observed after the server accepts the responses. ## Raises RuntimeError If this task is not awaiting input or cannot be updated. # MCPTask.async_wait ``` async_wait() → ResultT ``` Wait for completion and return the converted tool result. ## Returns type: ResultT The converted result of the completed task. ## Raises RuntimeError If the task reaches a terminal state without a converted result. # MCPTask.refresh ``` refresh() → MCPTaskState ``` Refresh and return the latest server-reported task state. # MCPTask.cancel ``` cancel() → MCPTaskState ``` Cancel this server-backed task and return its resulting state. # MCPTask.update ``` update( input_responses: InputResponses, ) → MCPTaskState ``` Submit requested input and return the resulting task state. ## Parameters input_responses type: InputResponses Responses keyed by outstanding request identity. ## Returns type: MCPTaskState The task state observed after the server accepts the responses. # MCPTask.wait ``` wait() → ResultT ``` Wait synchronously for completion and return the converted result. # MCPTaskState Describe one observed state of a server-backed MCP task. ## Attributes task_id type: str | None Stable identifier minted by the MCP server. status type: MCPTaskStatus Current lifecycle status. status_message type: str | None Optional human-readable detail supplied by the server. created_at type: datetime Time at which the server created the task. last_updated_at type: datetime Time at which the server last updated the task. ttl type: timedelta | None Retention duration from creation, or `None` when unlimited. poll_interval type: timedelta | None Server-recommended delay between status requests. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/task_extension/ # yera.tools.mcp.task_extension Client extension support for current MCP tasks. ## Symbols class MCPTasksExtension — Advertise current Tasks support and claim task tool results. # MCPTasksExtension Inherits: `ClientExtension` Advertise current Tasks support and claim task tool results. ## Methods claims — Return the tools/call result shapes owned by this extension. # MCPTasksExtension.claims ``` claims() → Sequence[ResultClaim[CreateTaskResult]] ``` Return the tools/call result shapes owned by this extension. ## Returns type: Sequence[ResultClaim[CreateTaskResult]] The current task-result claim for the 2026-07-28 protocol. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/task_protocol/ # yera.tools.mcp.task_protocol Wire models for the current MCP Tasks extension. ## Symbols class CancelTaskRequest — Request cooperative cancellation of one MCP task. class CreateTaskResult — Represent a task handle returned instead of a completed tool result. class GetTaskRequest — Request the latest state of one MCP task. class GetTaskResult — Represent task state returned by the tasks/get method. class TaskAcknowledgementResult — Represent a successful tasks/update or tasks/cancel acknowledgement. class UpdateTaskRequest — Supply responses requested by an input-required MCP task. # CancelTaskRequest Inherits: `Request[_CancelTaskRequestParams, Literal['tasks/cancel']]` Request cooperative cancellation of one MCP task. ## Methods for_task — Build a cancellation request for one server task. # CancelTaskRequest.for_task ``` for_task( task_id: str, ) → CancelTaskRequest ``` Build a cancellation request for one server task. ## Parameters task_id type: str Stable identifier minted by the MCP server. ## Returns type: CancelTaskRequest A tasks/cancel request carrying the task routing identity. # CreateTaskResult Inherits: `_TaskFields` Represent a task handle returned instead of a completed tool result. # GetTaskRequest Inherits: `Request[_GetTaskRequestParams, Literal['tasks/get']]` Request the latest state of one MCP task. ## Methods for_task — Build a status request for one server task. # GetTaskRequest.for_task ``` for_task( task_id: str, ) → GetTaskRequest ``` Build a status request for one server task. ## Parameters task_id type: str Stable identifier minted by the MCP server. ## Returns type: GetTaskRequest A tasks/get request carrying the task routing identity. # GetTaskResult Inherits: `_TaskFields` Represent task state returned by the tasks/get method. # TaskAcknowledgementResult Inherits: `Result` Represent a successful tasks/update or tasks/cancel acknowledgement. # UpdateTaskRequest Inherits: `Request[_UpdateTaskRequestParams, Literal['tasks/update']]` Supply responses requested by an input-required MCP task. ## Methods for_task — Build an update request for one server task. # UpdateTaskRequest.for_task ``` for_task( task_id: str, input_responses: InputResponses, ) → UpdateTaskRequest ``` Build an update request for one server task. ## Parameters task_id type: str Stable identifier minted by the MCP server. input_responses type: InputResponses Responses keyed by outstanding request identity. ## Returns type: UpdateTaskRequest A tasks/update request carrying the supplied responses. --- Source: https://yera-labs.io/docs/yera/reference/implementation/tools/mcp/tool/ # yera.tools.mcp.tool MCP-backed Yera tool implementation. ## Symbols class MCPTool — A Yera tool backed by a remote MCP server. # MCPTool Inherits: `BaseTool` A Yera tool backed by a remote MCP server. ## Methods __repr__ — Return a concise representation of the imported MCP tool. async_start — Start the MCP tool without waiting for server-created work. start — Start the MCP tool synchronously without waiting for server-created work. async_call — Validate arguments and invoke the MCP tool asynchronously. async_invoke — Fill this tool's inputs and invoke it asynchronously. invoke — Fill this tool's inputs and invoke it synchronously. __call__ — Validate arguments and invoke the remote MCP tool. # MCPTool.__repr__ ``` __repr__() → str ``` Return a concise representation of the imported MCP tool. # MCPTool.async_start ``` async_start( *args, **kwargs, ) → MCPTask[object] ``` Start the MCP tool without waiting for server-created work. ## Parameters *args type: object = () Positional values in imported schema-property order. **kwargs type: object Named values matching the generated MCP input structure. ## Returns type: MCPTask[object] A stable task handle for immediate or asynchronous execution. # MCPTool.start ``` start( *args, **kwargs, ) → MCPTask[object] ``` Start the MCP tool synchronously without waiting for server-created work. ## Parameters *args type: object = () Positional values in imported schema-property order. **kwargs type: object Named values matching the generated MCP input structure. ## Returns type: MCPTask[object] A stable task handle for immediate or asynchronous execution. # MCPTool.async_call ``` async_call( *args, **kwargs, ) → object ``` Validate arguments and invoke the MCP tool asynchronously. ## Parameters *args type: object = () Positional values in imported schema-property order. **kwargs type: object Named values matching the generated MCP input structure. ## Returns type: object The converted Python result. ## Raises TypeError If the positional and keyword arguments cannot be bound. ValueError If the arguments do not satisfy the imported schema. MCPToolCallError If the remote server reports tool failure. # MCPTool.async_invoke ``` async_invoke( instruction: str | None = None, retry_on_mcp_error: bool = False, **kwargs, ) → object ``` Fill this tool's inputs and invoke it asynchronously. ## Parameters instruction type: str | None = None Optional instruction guiding input generation. retry_on_mcp_error type: bool = False Whether to correct arguments and retry once after the MCP server rejects a call. **kwargs type: str | int | float | bool Additional values passed to LLM generation. ## Returns type: object The converted result returned by the MCP tool. # MCPTool.invoke ``` invoke( instruction: str | None = None, retry_on_mcp_error: bool = False, **kwargs, ) → object ``` Fill this tool's inputs and invoke it synchronously. ## Parameters instruction type: str | None = None Optional instruction guiding input generation. retry_on_mcp_error type: bool = False Whether to correct arguments and retry once after the MCP server rejects a call. **kwargs type: str | int | float | bool Additional values passed to LLM generation. ## Returns type: object The converted result returned by the MCP tool. # MCPTool.__call__ ``` __call__( *args, **kwargs, ) → object ``` Validate arguments and invoke the remote MCP tool. ## Parameters *args type: object = () Positional values in imported schema-property order. **kwargs type: object Named values matching the generated MCP input structure. ## Returns type: object The converted Python result. ## Raises TypeError If the positional and keyword arguments cannot be bound. ValueError If the arguments do not satisfy the imported schema. MCPToolCallError If the remote server reports tool failure. ## Submodules result_block section spinner --- Source: https://yera-labs.io/docs/yera/reference/implementation/typing/ # yera.typing Utilities for type handling in Yera. Used by app and tools. Includes the following * validation: allowed types and function signature validation * type coersion for python types and json strings * serialisation and deserialsation for supported types ## Submodules coerce serialisation utils validate --- Source: https://yera-labs.io/docs/yera/reference/implementation/typing/coerce/ # yera.typing.coerce Coercion utilities to convert raw input values and python objects into their annotated types. ## Symbols def coerce_input — Coerce an app input value to its declared type. # coerce_input ``` coerce_input( value: object, type_hint: type, mode: Literal['json', 'python'], ) → object ``` Coerce an app input value to its declared type. ## Parameters value type: object The input value. type_hint type: type The resolved annotation to coerce to. mode type: Literal['json', 'python'] Whether `value` arrived as a wire string or a Python object. ## Returns type: object The coerced value. ## Raises TypeError If `type_hint` is not an allowed type. ValueError If `value` cannot be coerced. --- Source: https://yera-labs.io/docs/yera/reference/implementation/typing/serialisation/ # yera.typing.serialisation Pydantic-based serialization utilities for enhanced type support. ## Symbols def canonicalise_json — Normalize a JSON payload into Yera's canonical representation. def deserialise — Deserialise a JSON string or bytes into a Python object per the type hint. def serialise — Serialise a value to JSON using the given type hint. def serialise_runtime_value — Serialize a heterogeneous runtime value to JSON. def serialise_value — Derive and serialize a supported runtime value. class SerialisedValue — A runtime value serialized with its derived type information. def type_schema — Return the serialization schema for a supported declared type. # canonicalise_json ``` canonicalise_json( payload: bytes | str, ) → str ``` Normalize a JSON payload into Yera's canonical representation. ## Parameters payload type: bytes | str JSON text to parse and normalize. ## Returns type: str Compact JSON with deterministic object-key ordering. ## Raises ValueError If the payload is not valid finite JSON. # deserialise ``` deserialise( raw: bytes | str, type_hint: type, ) → object ``` Deserialise a JSON string or bytes into a Python object per the type hint. ## Parameters raw type: bytes | str The JSON-encoded data (bytes or str). type_hint type: type The target type annotation. ## Returns type: object The deserialised Python object. ## Raises TypeError If `type_hint` is not supported. ValueError If deserialisation fails. # serialise ``` serialise( value: object, type_hint: type, ) → bytes | str ``` Serialise a value to JSON using the given type hint. ## Parameters value type: object The Python object to serialise. type_hint type: type The type annotation guiding serialisation. ## Returns type: bytes | str A JSON-encoded byte string. ## Raises TypeError If `type_hint` is not supported. # serialise_runtime_value ``` serialise_runtime_value( value: object, ) → str ``` Serialize a heterogeneous runtime value to JSON. Unlike type-derived serialization, this function supports empty and heterogeneous nested collections whose complete type cannot be inferred from their runtime contents. Supported leaf values are serialized through Yera's normal typing infrastructure. This representation is intended for display and model-context transport. It does not retain sufficient type information for deserialization back into every original Python container type. ## Parameters value type: object A runtime value containing Yera-supported leaves. ## Returns type: str Compact JSON containing the normalized runtime value. ## Raises TypeError If the value contains a leaf unsupported by Yera's typing infrastructure. ValueError If a supported leaf cannot be serialized. # serialise_value ``` serialise_value( value: object, ) → SerialisedValue ``` Derive and serialize a supported runtime value. ## Parameters value type: object A populated runtime value accepted by Yera's typing system. ## Returns type: SerialisedValue The derived type information, serialized payload, and JSON Schema. ## Raises TypeError If the value's supported type cannot be derived. ValueError If the value does not conform to its derived type. # SerialisedValue A runtime value serialized with its derived type information. ## Attributes type_hint type: type The supported Yera type derived from the runtime object. type_name type: str Human-readable rendering of the derived type. payload type: str JSON produced by Yera's serialization infrastructure. schema type: dict[str, object] Serialization-mode JSON Schema for the derived type. # type_schema ``` type_schema( type_hint: type, ) → dict[str, object] ``` Return the serialization schema for a supported declared type. ## Parameters type_hint type: type The declared type whose schema should be generated. ## Returns type: dict[str, object] A JSON Schema describing the serialized representation. ## Raises TypeError If the declared type is not supported. --- Source: https://yera-labs.io/docs/yera/reference/implementation/typing/utils/ # yera.typing.utils Helpers for the app module's typing infrastructure. ## Symbols def derive_type — Derive a supported Yera type hint from a runtime value. def get_type_name — Render a type hint as a human-readable string. # derive_type ``` derive_type( value: object, ) → type ``` Derive a supported Yera type hint from a runtime value. ## Parameters value type: object A runtime value accepted by Yera's typing system. ## Returns type: type A concrete or recursively parameterized supported Yera type. ## Raises TypeError If the value is unsupported or its type is under-specified. # get_type_name ``` get_type_name( type_hint: type, ) → str ``` Render a type hint as a human-readable string. ## Parameters type_hint type: type the type hint to convert. ## Returns type: str str representing the type. --- Source: https://yera-labs.io/docs/yera/reference/implementation/typing/validate/ # yera.typing.validate Validation: checking that an app's annotations are drawn from the supported set. ## Symbols def is_allowed_type — Check whether a type hint is supported for validation and serialization. def validate_signature — Validate a function's parameters and return type against supported types. # is_allowed_type ``` is_allowed_type( type_hint: type | None, ) → bool ``` Check whether a type hint is supported for validation and serialization. ## Parameters type_hint type: type | None A Python type (e.g., `int`, `list[str]`, `MyEnum`, `pd.DataFrame`). ## Returns type: bool `True` if the type is in the allowed set; `False` otherwise. # validate_signature ``` validate_signature( fn: Callable, type_hints: dict[str, type], identifier: str | None = None, ) → None ``` Validate a function's parameters and return type against supported types. ## Parameters fn type: Callable The function to inspect. type_hints type: dict[str, type] The resolved type hints (as from `typing.get_type_hints()`). identifier type: str | None = None Optional human-readable name for error messages. ## Raises TypeError If unsupported parameter kinds are found, or if required parameters lack type hints, or if any type hint is not supported. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/ # yera.ui Provides the infrastructure underlying the local Yera UI. ## Submodules apps_sidebar default_navigation fastapi_app fastapi_routes navigation rendering run server session_runtime sessions_sidebar sessions_store settings_state utils --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/apps_sidebar/ # yera.ui.apps_sidebar Utils for the rendering the app tree sidebar panel. ## Symbols def app_icon — Generates an HTML badge for an application. class AppTreeFile — A Python source file containing one or more app functions. class AppTreeFolder — A directory containing folders or Python source files. class AppTreeLeaf — A selectable app function within a source file. def build_app_tree — Build a tree that preserves source files above app functions. def render_app_tree — Recursively renders a compacted app tree as HTML. # app_icon ``` app_icon( app_id: str, app: AppFunctionWrapper, ) → str ``` Generates an HTML badge for an application. ## Parameters app_id type: str The unique identifier of the app used to determine its color. app type: AppFunctionWrapper The application wrapper containing the display name. ## Returns type: str An HTML string representing the app's icon badge. # AppTreeFile A Python source file containing one or more app functions. # AppTreeFolder A directory containing folders or Python source files. # AppTreeLeaf A selectable app function within a source file. # build_app_tree ``` build_app_tree( apps: dict[str, AppFunctionWrapper], ) → list[AppTreeFolder | AppTreeFile] ``` Build a tree that preserves source files above app functions. # render_app_tree ``` render_app_tree( nodes: list[AppTreeLeaf | AppTreeFolder | AppTreeFile], depth: int = 0, selected_app_id: str | None = None, ) → str ``` Recursively renders a compacted app tree as HTML. Indentation comes entirely from the nested .app-tree__children wrapper (border + margin, in CSS) — rows use fixed padding regardless of depth; depth here only controls whether a folder starts expanded. ## Parameters nodes type: list[AppTreeLeaf | AppTreeFolder | AppTreeFile] Tree nodes at this level, from _build_app_tree. depth type: int = 0 Current nesting depth — default-open state only. selected_app_id type: str | None = None Optional app identifier to mark as the current selection. ## Returns type: str HTML string of the rendered tree. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/default_navigation/ # yera.ui.default_navigation Default top-level navigation for the Yera browser UI. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/fastapi_app/ # yera.ui.fastapi_app Local FastAPI application construction. ## Symbols def create_fastapi_app — Create FastAPI and apply its route registrars in order. # create_fastapi_app ``` create_fastapi_app( route_registrars: Iterable[RouteRegistrar], ) → FastAPI ``` Create FastAPI and apply its route registrars in order. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/fastapi_routes/ # yera.ui.fastapi_routes FastAPI route registration for the Yera UI. ## Submodules health sessions settings shell sidebar streaming --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/fastapi_routes/health/ # yera.ui.fastapi_routes.health FastAPI health routes. ## Symbols def register_health_routes — Register the server liveness endpoint. # register_health_routes ``` register_health_routes( app: FastAPI, ) → None ``` Register the server liveness endpoint. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/fastapi_routes/sessions/ # yera.ui.fastapi_routes.sessions FastAPI routes for session creation and status. ## Symbols def register_session_routes — Register session routes with explicit runtime capabilities. # register_session_routes ``` register_session_routes( app: FastAPI, launch_session: LaunchSession, is_running: IsRunning, ) → None ``` Register session routes with explicit runtime capabilities. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/fastapi_routes/settings/ # yera.ui.fastapi_routes.settings Module containing the infra for adding settings page API routes. ## Symbols def register_settings_routes — Register settings page API routes on the UI server app. # register_settings_routes ``` register_settings_routes( app: FastAPI, load_state: _LoadSettingsState = load_settings_state, save_defaults: _SaveDefaults = save_default_models, save_profile_settings_fn: Callable[..., None] = save_profile_settings, save_provider_connection_fn: Callable[..., None] = save_provider_connection, save_model_inference_fn: Callable[..., None] = save_model_inference, ) → None ``` Register settings page API routes on the UI server app. ## Parameters app type: FastAPI FastAPI application that will receive the Settings routes. load_state type: _LoadSettingsState = load_settings_state Function used to load the current configuration state. save_defaults type: _SaveDefaults = save_default_models Function used to persist model defaults for the active profile. save_profile_settings_fn type: Callable[..., None] = save_profile_settings Function used to persist editable settings belonging to the active profile. save_provider_connection_fn type: Callable[..., None] = save_provider_connection Function used to persist an existing provider connection. save_model_inference_fn type: Callable[..., None] = save_model_inference Function used to persist default inference parameters for a model. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/fastapi_routes/shell/ # yera.ui.fastapi_routes.shell FastAPI routes for canonical UI screens. ## Symbols def register_shell_routes — Register canonical shell routes with explicit dependencies. # register_shell_routes ``` register_shell_routes( app: FastAPI, apps: dict[str, AppFunctionWrapper], session_store: BaseSessionStore, enter_server: EnterServer, session_requires_replay: SessionRequiresReplay, ) → None ``` Register canonical shell routes with explicit dependencies. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/fastapi_routes/sidebar/ # yera.ui.fastapi_routes.sidebar FastAPI routes for contextual sidebar fragments. ## Symbols def register_sidebar_routes — Register sidebar fragment routes with explicit dependencies. # register_sidebar_routes ``` register_sidebar_routes( app: FastAPI, apps: dict[str, AppFunctionWrapper], session_store: BaseSessionStore, ) → None ``` Register sidebar fragment routes with explicit dependencies. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/fastapi_routes/streaming/ # yera.ui.fastapi_routes.streaming FastAPI routes for session streaming and input. ## Symbols def register_streaming_routes — Register streaming and input routes with explicit capabilities. # register_streaming_routes ``` register_streaming_routes( app: FastAPI, resolve_session: ResolveSession, launch_runtime: LaunchRuntime, sse_stream: SSEStream, validate_request: ValidateRequest, session_store: BaseSessionStore, ) → None ``` Register streaming and input routes with explicit capabilities. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/navigation/ # yera.ui.navigation Declarative definitions for UI screens and contextual sidebars. ## Symbols class ScreenDefinition — A navigable top-level UI screen. class ScreenRegistry — Ordered collection of uniquely keyed UI screens. class SidebarDefinition — A contextual sidebar associated with a screen. # ScreenDefinition A navigable top-level UI screen. # ScreenRegistry Ordered collection of uniquely keyed UI screens. ## Methods __post_init__ — Build the immutable screen lookup and reject duplicate keys. __iter__ — Iterate over screens in navigation order. __len__ — Return the number of registered screens. __getitem__ — Look up a screen by its stable key. available — Return screens that are currently available. mobile_menu_screens — Return screens assigned to the mobile menu in display order. # ScreenRegistry.__post_init__ ``` __post_init__() → None ``` Build the immutable screen lookup and reject duplicate keys. # ScreenRegistry.__iter__ ``` __iter__() → Iterator[ScreenDefinition] ``` Iterate over screens in navigation order. # ScreenRegistry.__len__ ``` __len__() → int ``` Return the number of registered screens. # ScreenRegistry.__getitem__ ``` __getitem__( key: str, ) → ScreenDefinition ``` Look up a screen by its stable key. # ScreenRegistry.available ``` available() → tuple[ScreenDefinition, ...] ``` Return screens that are currently available. # ScreenRegistry.mobile_menu_screens ``` mobile_menu_screens() → tuple[ScreenDefinition, ...] ``` Return screens assigned to the mobile menu in display order. # SidebarDefinition A contextual sidebar associated with a screen. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/ # yera.ui.rendering HTML rendering for the local web UI. ## Submodules context forms listener renderer views --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/context/ # yera.ui.rendering.context Typed rendering context for the web UI shell. ## Symbols class ShellContext — Values used to render one instance of the web UI shell. # ShellContext Values used to render one instance of the web UI shell. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/forms/ # yera.ui.rendering.forms Render and parse reusable forms backed by Pydantic models. ## Symbols def inference_form_policy — Derive inference-field behaviour from model capabilities. class InferenceFormPolicy — Runtime form policy derived from model capabilities. def parse_model_form — Parse submitted form values into a validated Pydantic model. def render_model_fields — Render editable fields declared by a Pydantic model. def render_schema_fields — Render editable fields described by a form schema. # inference_form_policy ``` inference_form_policy( capabilities: LLMCapabilities | None, ) → InferenceFormPolicy ``` Derive inference-field behaviour from model capabilities. ## Parameters capabilities type: LLMCapabilities | None Capabilities advertised by the selected model. ## Returns type: InferenceFormPolicy Disabled fields and runtime-restricted choices for its inference form. # InferenceFormPolicy Runtime form policy derived from model capabilities. # parse_model_form ``` parse_model_form( model_type: type[ModelT], form: Mapping[str, object], exclude: frozenset[str] = frozenset(), disabled: frozenset[str] = frozenset(), existing: ModelT | None = None, ) → ModelT ``` Parse submitted form values into a validated Pydantic model. ## Parameters model_type type: type[ModelT] Pydantic model class defining the expected fields. form type: Mapping[str, object] Submitted form values keyed by schema field name. exclude type: frozenset[str] = frozenset() Field names that must not be read from the form. disabled type: frozenset[str] = frozenset() Field names that must ignore submitted values. existing type: ModelT | None = None Existing model whose disabled values must be preserved. ## Returns type: ModelT A validated instance of `model_type`. ## Raises TypeError If a submitted value or schema annotation is unsupported. pydantic.ValidationError If the parsed values fail model validation. # render_model_fields ``` render_model_fields( model: BaseModel, id_prefix: str, exclude: frozenset[str] = frozenset(), disabled: frozenset[str] = frozenset(), choices: Mapping[str, tuple[object, ...]] | None = None, ) → TrustedHTML ``` Render editable fields declared by a Pydantic model. ## Parameters model type: BaseModel Model instance containing the current field values. id_prefix type: str Prefix used to create unique HTML control identifiers. exclude type: frozenset[str] = frozenset() Field names that must not be rendered. disabled type: frozenset[str] = frozenset() Field names that remain visible but cannot be edited or submitted. choices type: Mapping[str, tuple[object, ...]] | None = None Optional per-field choice subsets supplied by runtime capabilities. ## Returns type: TrustedHTML Trusted HTML containing the generated form fields. ## Raises ValueError If an included field lacks a title or description. TypeError If an included field uses an unsupported annotation. # render_schema_fields ``` render_schema_fields( schema: Mapping[str, JsonValue], values: Mapping[str, JsonValue], id_prefix: str, exclude: frozenset[str] = frozenset(), disabled: frozenset[str] = frozenset(), choices: Mapping[str, tuple[object, ...]] | None = None, errors: Mapping[str, list[str]] | None = None, readonly: bool = False, ) → TrustedHTML ``` Render editable fields described by a form schema. ## Parameters schema type: Mapping[str, JsonValue] Inlined form schema, as produced by `form_schema`. values type: Mapping[str, JsonValue] Current JSON-compatible values keyed by field name. Fields without a value use their schema default. id_prefix type: str Prefix used to create unique HTML control identifiers. exclude type: frozenset[str] = frozenset() Field names that must not be rendered. disabled type: frozenset[str] = frozenset() Field names that remain visible but cannot be edited or submitted. choices type: Mapping[str, tuple[object, ...]] | None = None Optional per-field choice subsets supplied by runtime capabilities. errors type: Mapping[str, list[str]] | None = None Validation messages keyed by dotted field path. readonly type: bool = False Show the values as a record, with no row controls, and secrets shown only as set or not set. ## Returns type: TrustedHTML Trusted HTML containing the generated form fields. ## Raises TypeError If a field's widget has no reusable control yet. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/listener/ # yera.ui.rendering.listener Rendering for the session SSE listener. ## Symbols def render_session_listener — Render the SSE listener for a session transcript. # render_session_listener ``` render_session_listener( session_id: str, replay: bool = True, ) → str ``` Render the SSE listener for a session transcript. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/renderer/ # yera.ui.rendering.renderer Rendering helpers for the web UI shell. ## Symbols def render_shell — Render the web UI shell from a validated context. # render_shell ``` render_shell( context: ShellContext, ) → str ``` Render the web UI shell from a validated context. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/views/ # yera.ui.rendering.views Screen-specific UI renderers. ## Submodules apps sessions settings --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/views/apps/ # yera.ui.rendering.views.apps Rendering for the app-selection screen. ## Symbols class AppInspectorField — Declarative metadata field displayed in an app inspector. def build_app_inspector_fields — Build ordered inspector fields from available app metadata. def render_app_inspector_fields — Render escaped declarative metadata fields for the sidebar. def render_app_sidebar — Render metadata and explicit session creation for an app. def render_apps_home — Render the app-selection main screen. def render_mobile_app_detail — Render app metadata as a pushed mobile detail screen. # AppInspectorField Declarative metadata field displayed in an app inspector. # build_app_inspector_fields ``` build_app_inspector_fields( app_id: str, metadata: AppMetadata, ) → list[AppInspectorField] ``` Build ordered inspector fields from available app metadata. # render_app_inspector_fields ``` render_app_inspector_fields( fields: list[AppInspectorField], ) → TrustedHTML ``` Render escaped declarative metadata fields for the sidebar. # render_app_sidebar ``` render_app_sidebar( app_name: str, app_icon: TrustedHTML, new_session_url: str, fields: list[AppInspectorField], ) → TrustedHTML ``` Render metadata and explicit session creation for an app. # render_apps_home ``` render_apps_home( apps: dict[str, AppFunctionWrapper], selected_app_id: str | None = None, ) → TrustedHTML ``` Render the app-selection main screen. # render_mobile_app_detail ``` render_mobile_app_detail( app_name: str, app_icon: TrustedHTML, new_session_url: str, fields: list[AppInspectorField], ) → TrustedHTML ``` Render app metadata as a pushed mobile detail screen. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/views/sessions/ # yera.ui.rendering.views.sessions Rendering for the Sessions exploration screen. ## Symbols def classify_sessions — Classify ordered session records without changing their order. def render_live_sessions — Render active sessions for the canonical Live screen. def render_mobile_session_detail — Render persisted session metadata as a pushed mobile screen. def render_session_sidebar — Render persisted metadata and navigation for one selected session. def render_sessions_home — Render persisted sessions as main-screen navigation. class SessionGroups — Sessions grouped for live, historical, and offline presentation. class SessionViewMode — Supported Sessions history presentations. # classify_sessions ``` classify_sessions( records: list[SessionRecord], available_app_ids: Collection[str], ) → SessionGroups ``` Classify ordered session records without changing their order. ## Parameters records type: list[SessionRecord] Session records in their intended display order. available_app_ids type: Collection[str] Apps currently available on this server. ## Returns type: SessionGroups Session records grouped by availability and persisted lifecycle state. # render_live_sessions ``` render_live_sessions( apps: dict[str, AppFunctionWrapper], live_by_app: dict[str, list[SessionRecord]], ) → TrustedHTML ``` Render active sessions for the canonical Live screen. # render_mobile_session_detail ``` render_mobile_session_detail( record: SessionRecord, app_name: str, app_available: bool, ) → TrustedHTML ``` Render persisted session metadata as a pushed mobile screen. # render_session_sidebar ``` render_session_sidebar( record: SessionRecord, app_name: str, app_available: bool, ) → TrustedHTML ``` Render persisted metadata and navigation for one selected session. ## Parameters record type: SessionRecord Persisted session being inspected. app_name type: str Human-readable app name or its stored identifier. app_available type: bool Whether the app is currently registered on this server. ## Returns type: TrustedHTML Contextual session-inspector HTML. # render_sessions_home ``` render_sessions_home( records: list[SessionRecord], apps: dict[str, AppFunctionWrapper], selected_session_id: str = '', mode: SessionViewMode = SessionViewMode.CHRONOLOGICAL, ) → TrustedHTML ``` Render persisted sessions as main-screen navigation. ## Parameters records type: list[SessionRecord] Sessions ordered for display. apps type: dict[str, AppFunctionWrapper] Apps currently available on this server. selected_session_id type: str = '' Session to mark as selected, if any. mode type: SessionViewMode = SessionViewMode.CHRONOLOGICAL History ordering and grouping presentation. ## Returns type: TrustedHTML Main-screen HTML for session exploration. # SessionGroups Sessions grouped for live, historical, and offline presentation. # SessionViewMode Inherits: `StrEnum` Supported Sessions history presentations. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/rendering/views/settings/ # yera.ui.rendering.views.settings Render the pages, forms, and navigation used by Yera Settings. ## Symbols def render_appearance_settings — Render browser-local appearance settings. def render_default_models_settings — Render model defaults for the active profile. def render_model_settings — Render discovered model data and editable inference defaults. def render_models_settings — Render the model catalogue available to the active profile. def render_profile_settings — Render editable settings for the active profile. def render_provider_connection_form — Render an editor for an existing provider connection. def render_provider_connection_settings — Render one existing provider connection. def render_providers_settings — Render existing provider connections. def render_settings_home — Render the top-level Settings navigation. def render_settings_sidebar — Render Settings navigation in the shell sidebar. # render_appearance_settings ``` render_appearance_settings( state: SettingsState, ) → TrustedHTML ``` Render browser-local appearance settings. # render_default_models_settings ``` render_default_models_settings( state: SettingsState, ) → TrustedHTML ``` Render model defaults for the active profile. # render_model_settings ``` render_model_settings( state: SettingsState, model_type: str, model_id: str, ) → TrustedHTML ``` Render discovered model data and editable inference defaults. # render_models_settings ``` render_models_settings( state: SettingsState, ) → TrustedHTML ``` Render the model catalogue available to the active profile. ## Parameters state type: SettingsState Current Settings configuration state. ## Returns type: TrustedHTML Trusted HTML containing the filterable model catalogue. # render_profile_settings ``` render_profile_settings( state: SettingsState, ) → TrustedHTML ``` Render editable settings for the active profile. ## Parameters state type: SettingsState Settings state containing the active profile and its available provider connections. ## Returns type: TrustedHTML Trusted HTML containing the active-profile settings form. # render_provider_connection_form ``` render_provider_connection_form( state: SettingsState, provider_type: str, connection_name: str, active: bool, error: str | None = None, ) → TrustedHTML ``` Render an editor for an existing provider connection. ## Parameters state type: SettingsState Current Settings configuration state. provider_type type: str Provider key containing the connection. connection_name type: str Name of the connection to edit. active type: bool Whether the active profile selects this connection. error type: str | None = None Optional validation or configuration conflict message. ## Returns type: TrustedHTML Trusted HTML containing the provider connection form. # render_provider_connection_settings ``` render_provider_connection_settings( state: SettingsState, provider_type: str, connection_name: str, ) → TrustedHTML ``` Render one existing provider connection. # render_providers_settings ``` render_providers_settings( state: SettingsState, open_provider: str | None = None, open_connection: str | None = None, ) → TrustedHTML ``` Render existing provider connections. # render_settings_home ``` render_settings_home( state: SettingsState, ) → TrustedHTML ``` Render the top-level Settings navigation. # render_settings_sidebar ``` render_settings_sidebar( state: SettingsState, current: str | None, ) → TrustedHTML ``` Render Settings navigation in the shell sidebar. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/run/ # yera.ui.run Entry point for launching Yera applications via a local server. ## Symbols def discover_apps — Discover all apps in a directory. def extract_apps_from_py_file — Extract AppFunctionWrapper instances from a Python file. def start_server_process — Start the YeraServer for the given apps and open the UI in a browser. # discover_apps ``` discover_apps( directory: Path | str, ) → dict[str, AppFunctionWrapper] ``` Discover all apps in a directory. Scans the directory tree for `.py` files and loads all apps from each file. Hidden directories (names starting with `.`) are not entered, so typical trees like `.venv` or `.git` are skipped. Files that fail to load are logged and skipped rather than aborting the scan. Keys are produced by `extract_apps_from_py_file` and embed the file path verbatim, so they follow the form of *directory*: pass a relative path and the keys are relative. ## Parameters directory type: Path | str Directory to scan for app files. ## Returns type: dict[str, AppFunctionWrapper] Mapping of app key to wrapper, across every file scanned. ## Raises FileNotFoundError If the directory does not exist. ValueError If the path is not a directory. # extract_apps_from_py_file ``` extract_apps_from_py_file( file_path: Path | str, ) → dict[str, AppFunctionWrapper] ``` Extract AppFunctionWrapper instances from a Python file. ## Parameters file_path type: Path | str Path to the Python file containing apps. ## Returns type: dict[str, AppFunctionWrapper] Mapping of app identifiers to wrappers. Keys embed *file_path* verbatim, so they follow the form the caller supplied. ## Raises FileNotFoundError If the specified file does not exist. ImportError If the module cannot be loaded. # start_server_process ``` start_server_process( apps: dict[str, AppFunctionWrapper], host: str, port: int, open_browser: bool, launch_config: ServerLaunchConfig | None = None, ) → None ``` Start the YeraServer for the given apps and open the UI in a browser. Runs until SIGINT or SIGTERM, then shuts the server down cleanly. ## Parameters apps type: dict[str, AppFunctionWrapper] The applications to be served. host type: str The hostname or IP address to bind the server to. port type: int The TCP port to listen on. open_browser type: bool Whether to open a browser window on server start. launch_config type: ServerLaunchConfig | None = None Configuration controlling server entry behavior. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/server/ # yera.ui.server Local server for running Yera apps with the web UI. ## Symbols class ServerLaunchConfig — Configure behavior when entering a Yera server. class YeraServer — ASGI server wrapper that handles event routing and HTTP interfaces for Yera apps. # ServerLaunchConfig Configure behavior when entering a Yera server. # YeraServer Inherits: `uvicorn.Server` ASGI server wrapper that handles event routing and HTTP interfaces for Yera apps. ## Methods handle_exit — Handles server exit signals by stopping all active session executors. __aenter__ — Asynchronous context manager entry point. Starts the uvicorn server. __aexit__ — Asynchronous context manager exit point. Shuts down the server and logs. # YeraServer.handle_exit ``` handle_exit( sig: int, frame: FrameType | None, ) → None ``` Handles server exit signals by stopping all active session executors. ## Parameters sig type: int The signal number. frame type: FrameType | None The current stack frame. # YeraServer.__aenter__ ``` __aenter__() → YeraServer ``` Asynchronous context manager entry point. Starts the uvicorn server. ## Returns type: YeraServer The initialised YeraServer instance. # YeraServer.__aexit__ ``` __aexit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) → None ``` Asynchronous context manager exit point. Shuts down the server and logs. ## Parameters exc_type type: type[BaseException] | None Exception type if an error occurred. exc_val type: BaseException | None Exception value if an error occurred. exc_tb type: TracebackType | None Traceback if an error occurred. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/session_runtime/ # yera.ui.session_runtime Runtime state for one Yera UI session. ## Symbols class ServerRuntime — Represents a single user session, tracking the executor. # ServerRuntime Represents a single user session, tracking the executor. ## Attributes id type: str Unique identifier for the session. executor type: PyRuntimeExecutor The runtime executor for this session. publisher type: Publisher | None Publisher for streaming events to the UI. stream type: EventStream | None The current event stream. router_task type: asyncio.Future | None Task managing the event router. ## Methods recorded_input — Return the form of an input event that is safe to persist. # ServerRuntime.recorded_input ``` recorded_input( event: InputEvent, ) → InputEvent ``` Return the form of an input event that is safe to persist. ## Parameters event type: InputEvent Input submitted for the pending request. ## Returns type: InputEvent The event with secret form values masked, or the event itself when it answers no pending form. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/sessions_sidebar/ # yera.ui.sessions_sidebar Functions for rendering the sessions sidebar HTML. ## Symbols def live_sessions_sidebar_html — Render the global sidebar containing only active sessions. # live_sessions_sidebar_html ``` live_sessions_sidebar_html( apps: dict[str, AppFunctionWrapper], live_by_app: dict[str, list[SessionRecord]], ) → str ``` Render the global sidebar containing only active sessions. ## Parameters apps type: dict[str, AppFunctionWrapper] Apps currently available on this server. live_by_app type: dict[str, list[SessionRecord]] Running and waiting sessions grouped by app ID. ## Returns type: str The complete Live sidebar HTML. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/sessions_store/ # yera.ui.sessions_store Session store implementations for Yera UI. ## Submodules base sqlite_store --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/sessions_store/base/ # yera.ui.sessions_store.base Module for managing and persisting Yera app session data. ## Symbols class BaseSessionStore — Abstract base class for storing and retrieving chat sessions. class SessionRecord — Represents a record of a user session, including its metadata. class SessionRecordUpdate — Metadata changes to apply while recording a session event. # BaseSessionStore Inherits: `ABC` Subclasses: `SQLiteSessionStore` Abstract base class for storing and retrieving chat sessions. ## Methods create — Creates a new session in the store. has — Checks if a session exists in the store. has_events — Checks whether a session already has any recorded events. get — Retrieves a session record by its ID. list — Lists all stored session records. update — Updates the metadata of an existing session. append_event — Appends an event to a session's history. read_events — Reads all events associated with a session. __enter__ — Enter the session store context. __exit__ — Exit the session store context. # BaseSessionStore.create ``` create( app_id: str, ) → SessionRecord ``` Creates a new session in the store. ## Parameters app_id type: str The ID of the application associated with the session. ## Returns type: SessionRecord The created SessionRecord. # BaseSessionStore.has ``` has( session_id: str, ) → bool ``` Checks if a session exists in the store. ## Parameters session_id type: str The unique identifier of the session. ## Returns type: bool True if the session exists, False otherwise. # BaseSessionStore.has_events ``` has_events( session_id: str, ) → bool ``` Checks whether a session already has any recorded events. Used to distinguish a brand-new session (safe to launch live) from a historical one (should only ever be replayed). ## Parameters session_id type: str The unique identifier of the session. ## Returns type: bool True if the session has one or more recorded events. # BaseSessionStore.get ``` get( session_id: str, ) → SessionRecord ``` Retrieves a session record by its ID. ## Parameters session_id type: str The unique identifier of the session. ## Returns type: SessionRecord The requested SessionRecord. # BaseSessionStore.list ``` list() → list[SessionRecord] ``` Lists all stored session records. ## Returns type: list[SessionRecord] A list of all SessionRecords. # BaseSessionStore.update ``` update( session_id: str, title: str | None = None, status: SessionStatus | None = None, ) → None ``` Updates the metadata of an existing session. ## Parameters session_id type: str The unique identifier of the session. title type: str | None = None An optional new title for the session. status type: SessionStatus | None = None An optional new lifecycle status for the session. # BaseSessionStore.append_event ``` append_event( session_id: str, event: OutputEvent | InputEvent, update: SessionRecordUpdate | None = None, ) → None ``` Appends an event to a session's history. ## Parameters session_id type: str The unique identifier of the session. event type: OutputEvent | InputEvent The input or output event to store. update type: SessionRecordUpdate | None = None Optional session metadata changes to apply atomically. # BaseSessionStore.read_events ``` read_events( session_id: str, ) → Iterator[OutputEvent | InputEvent] ``` Reads all events associated with a session. ## Parameters session_id type: str The unique identifier of the session. ## Returns type: Iterator[OutputEvent | InputEvent] An iterator over the session's events. # BaseSessionStore.__enter__ ``` __enter__() → Self ``` Enter the session store context. # BaseSessionStore.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) → None ``` Exit the session store context. # SessionRecord Inherits: `BaseModel` Represents a record of a user session, including its metadata. ## Methods new — Creates a new session record. # SessionRecord.new ``` new( app_id: str, title: str | None = None, ) → SessionRecord ``` Creates a new session record. ## Parameters app_id type: str The ID of the application associated with the session. title type: str | None = None optional title to assign to the session. Defaults to new chat. ## Returns type: SessionRecord A new SessionRecord instance. # SessionRecordUpdate Inherits: `BaseModel` Metadata changes to apply while recording a session event. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/sessions_store/sqlite_store/ # yera.ui.sessions_store.sqlite_store Module for the SQLite-based session store. ## Symbols class SQLiteSessionStore — SQLite-based implementation of BaseSessionStore. # SQLiteSessionStore Inherits: `BaseSessionStore` SQLite-based implementation of BaseSessionStore. The store creates a tiny SQLite database (WAL mode, foreign keys enabled) in the user's home directory unless another path is supplied. It provides CRUD operations for session metadata and an event log stored as JSON strings. ## Methods create — Create a new session record for *app_id*. has — Return ``True`` if a session with *session_id* exists in the store. has_events — Check whether any events are stored for *session_id*. get — Retrieve the :class:`SessionRecord` for *session_id*. list — Return all stored sessions ordered by most recent update time. update — Update metadata for *session_id*. append_event — Append an event to the log of *session_id*. read_events — Yield all events for *session_id* in chronological order. __enter__ — Enter a runtime context and initialise the SQLite store. __exit__ — Exit the runtime context, resetting the opened flag. # SQLiteSessionStore.create ``` create( app_id: str, ) → SessionRecord ``` Create a new session record for *app_id*. ## Parameters app_id type: str Identifier of the application that owns the session. ## Returns type: SessionRecord The newly created :class:`SessionRecord`. # SQLiteSessionStore.has ``` has( session_id: str, ) → bool ``` Return `True` if a session with *session_id* exists in the store. ## Parameters session_id type: str The UUID of the session to look up. ## Returns type: bool `True` if the session is present, otherwise `False`. # SQLiteSessionStore.has_events ``` has_events( session_id: str, ) → bool ``` Check whether any events are stored for *session_id*. ## Parameters session_id type: str The UUID of the session whose event log is queried. ## Returns type: bool `True` if at least one event exists, otherwise `False`. # SQLiteSessionStore.get ``` get( session_id: str, ) → SessionRecord ``` Retrieve the :class:`SessionRecord` for *session_id*. ## Parameters session_id type: str The UUID of the desired session. ## Returns type: SessionRecord The corresponding :class:`SessionRecord`. ## Raises KeyError If no such session exists. # SQLiteSessionStore.list ``` list() → list[SessionRecord] ``` Return all stored sessions ordered by most recent update time. ## Returns type: list[SessionRecord] A list of :class:`SessionRecord` objects sorted descending by `updated_at`. # SQLiteSessionStore.update ``` update( session_id: str, title: str | None = None, status: SessionStatus | None = None, ) → None ``` Update metadata for *session_id*. ## Parameters session_id type: str The UUID of the session to modify. title type: str | None = None Optional new title. If omitted, only the `updated_at` timestamp is refreshed. status type: SessionStatus | None = None An optional new lifecycle status for the session. ## Raises KeyError If the specified session does not exist. # SQLiteSessionStore.append_event ``` append_event( session_id: str, event: OutputEvent | InputEvent, update: SessionRecordUpdate | None = None, ) → None ``` Append an event to the log of *session_id*. ## Parameters session_id type: str The UUID of the target session. event type: OutputEvent | InputEvent An event to store. update type: SessionRecordUpdate | None = None Optional session metadata changes to apply atomically. ## Raises KeyError If the session does not exist. # SQLiteSessionStore.read_events ``` read_events( session_id: str, ) → Iterator[OutputEvent | InputEvent] ``` Yield all events for *session_id* in chronological order. ## Parameters session_id type: str The UUID of the session whose events should be streamed. ## Raises KeyError If the session does not exist. Raised eagerly when `read_events` is called. ValueError If an unknown event type is encountered. Raised lazily during iteration, not at call time. # SQLiteSessionStore.__enter__ ``` __enter__() → Self ``` Enter a runtime context and initialise the SQLite store. ## Returns type: Self `self` the open `SQLiteSessionStore` instance. # SQLiteSessionStore.__exit__ ``` __exit__( exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) → None ``` Exit the runtime context, resetting the opened flag. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/settings_state/ # yera.ui.settings_state Load and persist the configuration state exposed through Yera Settings. ## Symbols class InvalidSettingsState — Invalid global configuration state shown by Settings. def load_settings_state — Load the configuration state required by the Settings UI. def save_default_models — Persist model defaults for the active profile. def save_model_inference — Persist default inference parameters for an existing model. def save_profile_settings — Persist editable settings belonging to the active profile. def save_provider_connection — Persist changes to an existing provider connection. class SettingsConflictError — Configuration changed while a Settings form was open. class SettingsState — Configuration state required by the Settings UI. class UnconfiguredSettingsState — Global configuration state before a profile has been configured. # InvalidSettingsState Invalid global configuration state shown by Settings. # load_settings_state ``` load_settings_state() → SettingsState | InvalidSettingsState | UnconfiguredSettingsState ``` Load the configuration state required by the Settings UI. ## Returns type: SettingsState | InvalidSettingsState | UnconfiguredSettingsState A complete editable Settings state when configuration is valid, an invalid state containing diagnostics when the TOML is malformed or schema-invalid, or an unconfigured state when no profiles exist. ## Raises ProfileNotSpecifiedError If profiles exist but no active profile can be resolved. # save_default_models ``` save_default_models( state: SettingsState, model_defaults: ProfileModelDefaults, ) → None ``` Persist model defaults for the active profile. ## Parameters state type: SettingsState Settings state containing the active profile and available model catalogue. model_defaults type: ProfileModelDefaults Model identifiers to store as defaults for each model type. ## Returns type: None None. ## Raises SettingsConflictError If the configuration changed after the state was loaded. ValueError If a selected model is unavailable to the active profile. # save_model_inference ``` save_model_inference( state: SettingsState, model_type: str, model_id: str, inference: LLMInference, ) → None ``` Persist default inference parameters for an existing model. ## Parameters state type: SettingsState Settings state containing the active model catalogue. model_type type: str Catalogue type containing the model. model_id type: str Yera identifier of the model to update. inference type: LLMInference Validated inference configuration to persist. ## Returns type: None None. ## Raises SettingsConflictError If the configuration changed after the state was loaded. ValueError If the model type or model is unavailable, the model has no editable inference settings, or the inference type is incorrect. # save_profile_settings ``` save_profile_settings( state: SettingsState, description: str | None, providers: ProfileProviderConnections, ) → None ``` Persist editable settings belonging to the active profile. ## Parameters state type: SettingsState Settings state containing the active profile and configured providers. description type: str | None Optional description to store on the active profile. providers type: ProfileProviderConnections Provider connections selected by the active profile. ## Returns type: None None. ## Raises SettingsConflictError If the configuration changed after the state was loaded. ValueError If a selected provider connection does not exist. # save_provider_connection ``` save_provider_connection( state: SettingsState, provider_type: str, connection_name: str, connection: BaseConnection, ) → None ``` Persist changes to an existing provider connection. ## Parameters state type: SettingsState Settings state containing the configured provider connection. provider_type type: str Provider key containing the connection. connection_name type: str Name of the connection to update. connection type: BaseConnection Validated connection configuration to persist. ## Returns type: None None. ## Raises SettingsConflictError If the configuration changed after the state was loaded. ValueError If the connection does not exist or its configuration type differs from the existing connection. # SettingsConflictError Inherits: `RuntimeError` Configuration changed while a Settings form was open. # SettingsState Configuration state required by the Settings UI. # UnconfiguredSettingsState Global configuration state before a profile has been configured. --- Source: https://yera-labs.io/docs/yera/reference/implementation/ui/utils/ # yera.ui.utils Utility functions for the local UI server. ## Symbols def fmt_relative — Formats a timestamp as a compact relative label for session rows. # fmt_relative ``` fmt_relative( t: datetime, now: datetime | None = None, ) → str ``` Formats a timestamp as a compact relative label for session rows. Buckets match the sidebar design: minutes within the last hour, hours within the last day, a lowercase weekday within the last week, then an abbreviated `mon d` date. Names come from fixed English tables so output is stable regardless of the server's locale. ## Parameters t type: datetime Timestamp to format. Coerced to UTC if naive (see below). now type: datetime | None = None Reference time, for testing. Defaults to `datetime.now(UTC)`. ## Returns type: str A lowercase relative-time string such as `"5m ago"`, `"2h ago"`, `"tue"`, or `"jun 30"`. --- Source: https://yera-labs.io/docs/yera/reference/ # References Coming soon. API Python parts you use CLI CLI commands Library Implementation Internals of the lib