### Quick Start Source: https://prompty.ai/implementation/csharp A quick example demonstrating how to invoke a .prompty file using the Pipeline class. Remember to register providers before invocation. ```APIDOC ## Quick Start ```csharp using Prompty.Core; // All-in-one execution var result = await Pipeline.InvokeAsync("greeting.prompty", new Dictionary { ["name"] = "Jane" }); Console.WriteLine(result); ``` You must register providers before calling `Pipeline.InvokeAsync`. Reference the provider NuGet package and register its executor and processor at startup. ``` -------------------------------- ### Quick Start: Initialize and Invoke Prompty Source: https://prompty.ai/implementation/rust This example demonstrates the basic setup for using Prompty in Rust. It involves registering default providers and then invoking a Prompty file with specific inputs. ```rust use prompty; use prompty_openai; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { // 1. Register providers (once at startup) prompty::register_defaults(); prompty_openai::register(); // 2. Load and invoke let result = prompty::invoke_from_path( "greeting.prompty", Some(&json!({ "userName": "Jane" })), ).await?; println!("{result}"); Ok(()) } ``` -------------------------------- ### Quick Start Source: https://prompty.ai/implementation/python A basic example demonstrating how to invoke a prompt using the Prompty Python library. ```APIDOC ## Quick Start ```python import prompty # All-in-one execution result = prompty.invoke("greeting.prompty", inputs={"name": "Jane"}) print(result) ``` ``` -------------------------------- ### Installation Source: https://prompty.ai/implementation/python Instructions for installing Prompty and its optional extras using uv. ```APIDOC ## Installation Prompty v2 requires **Python ≥ 3.11**. We recommend uv for environment management. ```python # Create a virtual environment uv venv source .venv/bin/activate # or .venv\Scripts\activate on Windows # Install with the extras you need uv pip install "prompty[jinja2,openai]" ``` ### Available Extras Extra| Packages Installed| What it enables ---|---|--- `jinja2`| `jinja2`| Jinja2 template rendering `mustache`| `chevron`| Mustache template rendering `openai`| `openai`| OpenAI provider `azure`| `openai`, `azure-identity`| Azure OpenAI provider (deprecated alias for `foundry`) `anthropic`| `anthropic`| Anthropic provider `foundry`| `openai`, `azure-identity`| Microsoft Foundry / Azure OpenAI provider `otel`| `opentelemetry-api`| OpenTelemetry tracing `all`| All of the above| Everything ```python # Install everything uv pip install "prompty[all]" ``` ``` -------------------------------- ### Install Prompty with Extras Source: https://prompty.ai/implementation/python Install Prompty with specific extras for desired functionalities like Jinja2 templating or OpenAI integration. Use `[all]` to install all available extras. ```bash # Create a virtual environment uv venv source .venv/bin/activate # or .venv\Scripts\activate on Windows # Install with the extras you need uv pip install "prompty[jinja2,openai]" ``` ```bash # Install everything uv pip install "prompty[all]" ``` -------------------------------- ### Python Runtime Environment Setup Source: https://prompty.ai/contributing/code-guidelines Sets up a Python virtual environment using uv and installs development dependencies. Ensure Python version is 3.11 or higher. ```bash cd runtime/python/prompty uv venv uv pip install -e ".[dev,all]" ``` -------------------------------- ### Install all Prompty features (Python) Source: https://prompty.ai/getting-started Install the core Prompty library with all available features and providers using pip. ```bash uv pip install "prompty[all]" ``` -------------------------------- ### ToolCallStartPayload YAML Example Source: https://prompty.ai/reference/toolcallstartpayload This YAML example demonstrates the structure of a ToolCallStartPayload, specifying the tool name and its arguments. ```yaml name: get_weather arguments: '{"city": "Paris"}' ``` -------------------------------- ### Install Prompty Packages (Alpha) Source: https://prompty.ai/implementation/typescript Install the core Prompty runtime along with specific provider packages using the @alpha tag. Ensure you install the desired provider (e.g., OpenAI, Microsoft Foundry, Anthropic) alongside the core package. ```bash # Core + OpenAI npm install @prompty/core@alpha @prompty/openai@alpha # Core + Microsoft Foundry npm install @prompty/core@alpha @prompty/foundry@alpha # Core + Anthropic npm install @prompty/core@alpha @prompty/anthropic@alpha ``` -------------------------------- ### Start Development Server Source: https://prompty.ai/contributing/docs-guidelines Start the local development server to preview documentation changes. View the site at http://localhost:4321. The site will hot-reload. ```bash npm run dev ``` -------------------------------- ### Installation Source: https://prompty.ai/implementation/csharp Install the necessary Prompty NuGet packages for your C# project. Core is required, and you can choose one or more provider packages. ```APIDOC ## Installation All packages are available on NuGet at version **2.0.0-alpha.6**. ``` # Core — required dotnet add package Prompty.Core --prerelease # Pick one or more providers dotnet add package Prompty.OpenAI --prerelease dotnet add package Prompty.Foundry --prerelease dotnet add package Prompty.Anthropic --prerelease ``` Package| Description ---|--- `Prompty.Core`| Core pipeline, loader, tracing, types `Prompty.OpenAI`| OpenAI provider (executor + processor) `Prompty.Foundry`| Azure OpenAI / Microsoft Foundry provider `Prompty.Anthropic`| Anthropic provider ``` -------------------------------- ### Basic Chat Completion with OpenAI (Python) Source: https://prompty.ai/getting-started This Python example demonstrates a basic chat completion by loading a .prompty file and invoking it with inputs. Ensure the OpenAI package is installed. ```python from __future__ import annotations from prompty import invoke, load agent = load("chat-basic.prompty") result = invoke(agent, inputs={"question": "What is Prompty?"}) print(result) ``` -------------------------------- ### Install Prompty with Pip (v1) vs. uv (v2) Source: https://prompty.ai/migration v1 used pip for installation. v2 recommends uv and requires specifying extras like jinja2 and openai. ```bash # v1 pip install prompty # v2 uv pip install "prompty[jinja2,openai]" ``` -------------------------------- ### Install Prompty with Jinja2 and Foundry (Python) Source: https://prompty.ai/getting-started Install the core Prompty library with Jinja2 templating and Microsoft Foundry support using pip. ```bash uv pip install "prompty[jinja2,foundry]" ``` -------------------------------- ### OpenAI Connection Example Source: https://prompty.ai/vscode/connections Example input for setting up an OpenAI connection. The endpoint can be left as default if using the standard OpenAI API. ```text Connection name: my-openai API key: sk-... Endpoint: (leave default) Model: gpt-4o-mini ``` -------------------------------- ### Install Prompty for Foundry (Python, Entra ID) Source: https://prompty.ai/how-to/foundry Install Prompty with Foundry support and azure-identity for Microsoft Entra ID authentication. ```bash uv pip install "prompty[jinja2,foundry]" azure-identity ``` -------------------------------- ### Install Prompty Core and OpenAI (C#) Source: https://prompty.ai/getting-started Install the core Prompty library and the OpenAI provider package for C# using dotnet. Note: C# packages are in alpha preview and require the --prerelease flag. ```bash dotnet add package Prompty.Core --prerelease dotnet add package Prompty.OpenAI --prerelease # or Prompty.Foundry, Prompty.Anthropic ``` -------------------------------- ### TraceFile Yaml Example Source: https://prompty.ai/reference/tracefile Example of the TraceFile structure in YAML format, specifying runtime and version. ```yaml runtime: python version: 2.0.0 ``` -------------------------------- ### AudioPart YAML Example Source: https://prompty.ai/reference/audiopart Example of how to define an AudioPart in YAML format, specifying the source URL and media type. ```yaml source: https://example.com/audio.wav mediaType: audio/wav ``` -------------------------------- ### Yaml Example for DoneEventPayload Source: https://prompty.ai/reference/doneeventpayload This YAML example demonstrates the structure of a DoneEventPayload, showing a sample response from the LLM. ```yaml response: The weather in Paris is 72°F and sunny. ``` -------------------------------- ### Install Prompty with Jinja2 and OpenAI (Python) Source: https://prompty.ai/getting-started Install the core Prompty library with Jinja2 templating and OpenAI provider support using pip. ```bash uv pip install "prompty[jinja2,openai]" ``` -------------------------------- ### Install Dependencies Source: https://prompty.ai/contributing/docs-guidelines Install project dependencies using npm. Ensure you are in the `web` directory. Node.js 18+ is recommended. ```bash npm install ``` -------------------------------- ### Install Prompty Core and Foundry (TypeScript) Source: https://prompty.ai/getting-started Install the core Prompty library and the Microsoft Foundry provider package for TypeScript using npm. ```bash npm install @prompty/core @prompty/foundry ``` -------------------------------- ### Install OpenTelemetry Package (C#) Source: https://prompty.ai/core-concepts/tracing Adds the Prompty.Core package with OTel support for C# projects. ```bash dotnet add package Prompty.Core --prerelease # OTel support is built into Prompty.Core ``` -------------------------------- ### YAML Example for TextPart Source: https://prompty.ai/reference/textpart This YAML snippet shows a basic example of how to define a TextPart, specifying its value. ```yaml value: Hello, world! ``` -------------------------------- ### Install Prompty Core and OpenAI (TypeScript) Source: https://prompty.ai/getting-started Install the core Prompty library and the OpenAI provider package for TypeScript using npm. ```bash npm install @prompty/core @prompty/openai ``` -------------------------------- ### Install OpenTelemetry Package (Python) Source: https://prompty.ai/core-concepts/tracing Installs the OpenTelemetry package for Python, required for using the OTel tracer backend. ```bash pip install prompty[otel] ``` -------------------------------- ### Install Prompty Core and Anthropic (TypeScript) Source: https://prompty.ai/getting-started Install the core Prompty library and the Anthropic provider package for TypeScript using npm. ```bash npm install @prompty/core @prompty/anthropic ``` -------------------------------- ### Install Prompty with Jinja2 and Anthropic (Python) Source: https://prompty.ai/getting-started Install the core Prompty library with Jinja2 templating and Anthropic provider support using pip. ```bash uv pip install "prompty[jinja2,anthropic]" ``` -------------------------------- ### Install Prompty Extension from Marketplace Source: https://prompty.ai/vscode Install the v1 version of the Prompty VS Code extension directly from the VS Code Marketplace. Search for 'Prompty' by 'ms-toolsai'. ```bash code --install-extension ms-toolsai.prompty ``` -------------------------------- ### Microsoft Foundry Connection Example Source: https://prompty.ai/vscode/connections Example input for setting up a Microsoft Foundry connection. Uses Azure Entra ID authentication, requiring a project endpoint. ```text Connection name: my-foundry Project endpoint: https://my-project.services.ai.azure.com Foundry connection name: (leave blank for default) Tenant ID: (leave blank for default) ``` -------------------------------- ### Install Prompty C# Packages Source: https://prompty.ai/implementation/csharp Installs the core Prompty package and one or more provider packages using the .NET CLI. Ensure you are targeting .NET 9+. ```bash # Core — required dotnet add package Prompty.Core --prerelease # Pick one or more providers dotnet add package Prompty.OpenAI --prerelease dotnet add package Prompty.Foundry --prerelease dotnet add package Prompty.Anthropic --prerelease ``` -------------------------------- ### Tool Yaml Example Source: https://prompty.ai/reference/tool Example of how to define a tool in YAML format. This is useful for configuring tools with specific names, kinds, descriptions, and input bindings. ```yaml name: my-tool kind: function description: A description of the tool bindings: input: value ``` -------------------------------- ### Metadata Configuration in .prompty Source: https://prompty.ai/core-concepts/file-format Example of how to define arbitrary key-value pairs for metadata, such as authors, tags, and version. ```yaml metadata: authors: [alice, bob] tags: [customer-support, v2] version: "1.0" ``` -------------------------------- ### Install and Build Schema Emitter Source: https://prompty.ai/contributing/publishing-rubric Install dependencies and build the schema emitter. This is a prerequisite for regenerating model code and reference docs. ```bash cd schema npm install npm run build ``` -------------------------------- ### Install Prompty with Anthropic Support Source: https://prompty.ai/how-to/anthropic Install the Prompty library with Anthropic integration for your chosen language. Ensure you have the necessary dependencies for your package manager. ```bash uv pip install "prompty[jinja2,anthropic]" ``` ```bash npm install @prompty/core @prompty/anthropic ``` ```bash dotnet add package Prompty.Core --prerelease dotnet add package Prompty.Anthropic --prerelease ``` ```bash cargo add prompty prompty-anthropic ``` -------------------------------- ### Anthropic Connection Example Source: https://prompty.ai/vscode/connections Example input for setting up an Anthropic connection. The endpoint can be left as default if using the standard Anthropic API. ```text Connection name: my-anthropic API key: sk-ant-... Endpoint: (leave default) Model: claude-sonnet-4-6 ``` -------------------------------- ### Install Prompty Extension from VSIX Source: https://prompty.ai/vscode Install the v2 build of the Prompty VS Code extension manually using a .vsix file. This method is recommended for accessing the latest features. ```bash code --install-extension prompty-0.0.0.vsix ``` -------------------------------- ### TypeScript Runtime Environment Setup Source: https://prompty.ai/contributing/code-guidelines Installs npm dependencies and builds the TypeScript monorepo. Requires Node.js version 18 or higher. ```bash cd runtime/typescript npm install npm run build ``` -------------------------------- ### Provider Configuration Source: https://prompty.ai/implementation/csharp Examples of configuring different LLM providers (OpenAI, Foundry, Anthropic) in the .prompty frontmatter. ```APIDOC ## Providers Each provider ships as a separate NuGet package with an executor and processor. Package| Provider Key| SDK| Connection ---|---|---|--- `Prompty.OpenAI`| `openai`| OpenAI .NET SDK| `ApiKeyConnection` `Prompty.Foundry`| `foundry`| Azure OpenAI / Foundry SDK| `FoundryConnection`, `ApiKeyConnection` `Prompty.Anthropic`| `anthropic`| Anthropic .NET SDK| `ApiKeyConnection` Configure the provider in your `.prompty` frontmatter: * OpenAI * Foundry (Azure) * Anthropic ```yaml model: id: gpt-4o provider: openai connection: kind: key apiKey: ${env:OPENAI_API_KEY} ``` ```yaml model: id: gpt-4o provider: foundry connection: kind: key endpoint: ${env:AZURE_OPENAI_ENDPOINT} apiKey: ${env:AZURE_OPENAI_API_KEY} ``` ```yaml model: id: claude-sonnet-4-20250514 provider: anthropic connection: kind: key apiKey: ${env:ANTHROPIC_API_KEY} ``` ``` -------------------------------- ### Activate Prompty Extension API Source: https://prompty.ai/vscode/reference Example of how to activate the Prompty extension and access its API from another VS Code extension. Ensure the extension is installed and activated. ```typescript const promptyExt = vscode.extensions.getExtension('ms-toolsai.prompty'); const api = await promptyExt?.activate(); ``` -------------------------------- ### TraceTime YAML Example Source: https://prompty.ai/reference/tracetime Represents timing information for a trace span in YAML format. Use this to define the start time, end time, and duration of a span. ```yaml start: 2026-04-04T12:00:00Z end: 2026-04-04T12:00:01Z duration: 1000 ``` -------------------------------- ### Load, Prepare, and Run a Prompty Agent (C#) Source: https://prompty.ai/getting-started This C# example demonstrates loading a .prompty file, rendering the template with inputs, parsing the result into messages, and executing the LLM call. ```csharp using Prompty.Core; // 1. Load the .prompty file → Prompty var agent = PromptyLoader.Load("greeting.prompty"); // 2. Render template + parse → messages var rendered = await Pipeline.RenderAsync(agent, new() { ["userName"] = "Jane" }); var messages = await Pipeline.ParseAsync(agent, rendered); // 3. Call the LLM + process → clean result var response = await Pipeline.ExecuteAsync(agent, messages); var result = await Pipeline.ProcessAsync(agent, response); ``` -------------------------------- ### Define a .prompty file with model configuration and prompt instructions Source: https://prompty.ai/getting-started This example shows a `.prompty` file with YAML frontmatter for model configuration (name, description, model ID, provider, connection) and a markdown body for system and user messages, including input variable interpolation. ```yaml --- name: greeting description: A friendly greeting prompt model: id: gpt-4o-mini provider: openai connection: kind: key apiKey: ${env:OPENAI_API_KEY} inputs: - name: userName kind: string default: World --- system: You are a friendly assistant who greets people warmly. user: Say hello to {{userName}} and ask how their day is going. ``` -------------------------------- ### Complete Prompty file example Source: https://prompty.ai/core-concepts/file-format A full `.prompty` file demonstrating various features including metadata, model configuration, inputs, outputs, tools, and templating. ```yaml --- name: customer-support displayName: Customer Support Agent description: Answers customer questions using context from their account. metadata: authors: [support-team] tags: [production, customer-facing] version: "2.1" model: id: gpt-4o provider: foundry apiType: chat connection: kind: key endpoint: ${env:AZURE_OPENAI_ENDPOINT} apiKey: ${env:AZURE_OPENAI_API_KEY} options: temperature: 0.3 maxOutputTokens: 2000 inputs: - name: customerName kind: string description: Full name of the customer required: true - name: question kind: string description: The customer's question required: true - name: orderHistory kind: array description: Recent orders for context default: [] outputs: - name: answer kind: string - name: sentiment kind: string enumValues: [positive, neutral, negative] tools: - name: lookup_order kind: function description: Look up an order by ID parameters: - name: orderId kind: string required: true template: format: jinja2 --- system: You are a customer support agent for Contoso. Be helpful, concise, and empathetic. Always greet the customer by name. You have access to the following order history: {% for order in orderHistory %} - Order #{{ order.id }}: {{ order.status }} ({{ order.date }}) {% endfor %} user: Hi, my name is {{customerName}}. {{question}} ``` -------------------------------- ### Few-Shot Prompting for Sentiment Analysis Source: https://prompty.ai/how-to/cookbook Embed examples within the prompt to guide the model's output format for classification tasks. The input text is classified as positive, negative, or neutral. ```prompty --- name: few-shot model: id: gpt-4o-mini apiType: chat inputs: - name: text kind: string default: The movie was absolutely fantastic and I loved every minute. --- system: Classify the sentiment of the text as positive, negative, or neutral. Examples: - "I love this product!" → positive - "Terrible experience, never again." → negative - "It was okay, nothing special." → neutral user: {{text}} ``` ```python result = run(agent, prepare(agent, {"text": "The food was cold and bland."})) ``` ```typescript const result = await invoke("few-shot.prompty", { text: "The food was cold and bland." }); ``` ```csharp var result = await Pipeline.InvokeAsync(agent, new Dictionary { ["text"] = "The food was cold and bland." }); ``` ```rust let inputs = serde_json::json!({ "text": "The food was cold and bland." }); let result = prompty::invoke_from_path("few-shot.prompty", Some(&inputs)).await?; ``` -------------------------------- ### Generate Embeddings with OpenAI (.prompty file) (C#) Source: https://prompty.ai/how-to/embeddings Loads an embedding .prompty file and invokes the pipeline to get vector embeddings. The .prompty file should specify `apiType: embedding`. One-time setup for the Prompty builder is required. ```csharp // Copyright (c) Microsoft. All rights reserved. using Prompty.Core; using Prompty.OpenAI; namespace DocsExamples.Examples; /// /// Generate text embeddings using an embedding .prompty file. /// public static class Embeddings { /// /// Load an embedding .prompty and invoke to get vector embeddings. /// The prompty file sets apiType: embedding. /// public static async Task RunAsync( string promptyPath, Dictionary? inputs = null) { // One-time setup new PromptyBuilder() .AddOpenAI(); // Full pipeline — executor dispatches on apiType: embedding var result = await Pipeline.InvokeAsync(promptyPath, inputs); return result; } } ``` -------------------------------- ### Pipeline Functions: Step-by-Step and All-in-One Source: https://prompty.ai/implementation/typescript Demonstrates two ways to run a prompt: step-by-step using 'load', 'prepare', and 'run', or all-in-one using 'invoke'. Ensure the provider is imported before use. ```typescript import { load, prepare, run, invoke } from "@prompty/core"; import "@prompty/openai"; // Step by step const agent = await load("chat.prompty"); const messages = await prepare(agent, { question: "Hi" }); const result = await run(agent, messages); // All-in-one const result2 = await invoke("chat.prompty", { question: "Hi" }); ``` -------------------------------- ### Example connections.json Configuration Source: https://prompty.ai/vscode/connections This JSON file shows how to configure multiple connections for different providers. The 'isDefault' flag determines the default connection for a provider. ```json { "openai-dev": { "provider": "openai", "endpoint": "https://api.openai.com/v1", "isDefault": true }, "azure-prod": { "provider": "foundry", "endpoint": "https://my-resource.services.ai.azure.com/api/projects/my-project", "isDefault": false } } ``` -------------------------------- ### ToolResult Yaml Example Source: https://prompty.ai/reference/toolresult An example of how a ToolResult can be represented in YAML format. ```APIDOC ## Yaml Example ```yaml parts: - kind: text value: 72°F and sunny ``` ``` -------------------------------- ### Quick Start: Invoke Prompty Pipeline Source: https://prompty.ai/implementation/csharp Executes a .prompty file with given inputs using the all-in-one pipeline invocation. Providers must be registered at startup. ```csharp using Prompty.Core; // All-in-one execution var result = await Pipeline.InvokeAsync("greeting.prompty", new Dictionary { ["name"] = "Jane" }); Console.WriteLine(result); ``` -------------------------------- ### ValidationResult Yaml Example Source: https://prompty.ai/reference/validationresult Example of a successful validation result with no errors. ```yaml valid: true errors: [] ``` -------------------------------- ### AnthropicToolResultBlock Yaml Example Source: https://prompty.ai/reference/anthropictoolresultblock Example of AnthropicToolResultBlock in YAML format, showing the tool_use_id and content. ```yaml tool_use_id: toolu_01A09q90qw90lq917835lq9 content: 72°F and sunny in Paris ``` -------------------------------- ### AnthropicMessagesRequest Yaml Example Source: https://prompty.ai/reference/anthropicmessagesrequest An example of the Anthropic Messages API request body in YAML format. ```APIDOC ## Yaml Example ```yaml model: claude-sonnet-4-20250514 max_tokens: 4096 system: You are a helpful assistant. temperature: 0.7 top_p: 0.9 top_k: 40 stop_sequences: - |- Human: ``` ``` -------------------------------- ### ToolResult Yaml Example Source: https://prompty.ai/reference/toolresult Example of how a ToolResult can be represented in YAML format, showing a single text part. ```yaml parts: - kind: text value: 72°F and sunny ``` -------------------------------- ### Call Agent Turn with Tools (Rust) Source: https://prompty.ai/api-reference/agent-turns This Rust example shows how to set up and execute an agent turn. Tools are registered using `prompty::register_tool`, and the `prompty::turn_from_path` function initiates the agent's process. ```rust use prompty::{self, TurnOptions}; use serde_json::json; prompty::register_tool("get_weather", |args| { Box::pin(async move { let loc = args["location"].as_str().unwrap_or("unknown"); Ok(json!(format!("Sunny in {loc}"))) }) }); let result = prompty::turn_from_path( "agent.prompty", Some(&json!({ "question": "Weather in Seattle?" })), Some(TurnOptions { max_iterations: Some(10), ..Default::default() }), ).await?; ``` -------------------------------- ### ToolResultPayload YAML Example Source: https://prompty.ai/reference/toolresultpayload An example of a ToolResultPayload in YAML format, demonstrating the structure for a 'get_weather' tool result. ```yaml name: get_weather result: parts: - kind: text value: 72°F and sunny ``` -------------------------------- ### InvokerError Example Source: https://prompty.ai/reference/invokererror This YAML example shows the structure of an InvokerError, indicating a missing renderer for the 'jinja2' key. ```yaml message: "No renderer registered for key: jinja2" component: renderer key: jinja2 ``` -------------------------------- ### ErrorEventPayload YAML Example Source: https://prompty.ai/reference/erroreventpayload Example of an ErrorEventPayload in YAML format, showing a rate limit exceeded message. ```yaml message: Rate limit exceeded ``` -------------------------------- ### Load, Prepare, and Run LLM Call (C#) Source: https://prompty.ai/tutorials/chat-assistant This C# example shows how to load a Prompty agent, prepare messages, and run an asynchronous LLM call. It utilizes the Prompty.Core namespace. ```csharp using Prompty.Core; // 1. Load — parse the .prompty file into a Prompty var agent = PromptyLoader.Load("assistant.prompty"); // 2. Prepare — render the template + parse role markers → messages var messages = await Pipeline.PrepareAsync( agent, new() { ["question"] = "Explain async/await" } ); // 3. Run — call the LLM + process the response → clean string var result = await Pipeline.RunAsync(agent, messages); Console.WriteLine(result); ``` -------------------------------- ### Running a Prompty File Source: https://prompty.ai/vscode/running Press F5 or click the play button to run a `.prompty` file. This process loads environment variables, bridges connections, renders templates, parses roles, sends messages to the LLM, and generates a trace file. ```markdown ``` ``` ``` -------------------------------- ### Load, Prepare, and Run a Prompty Agent (Rust) Source: https://prompty.ai/getting-started This Rust snippet shows how to register default and OpenAI providers, load a .prompty file, prepare messages with inputs, and run the agent. ```rust use prompty; use prompty_openai; use serde_json::json; prompty::register_defaults(); prompty_openai::register(); // 1. Load the .prompty file → typed agent let agent = prompty::load("greeting.prompty")?; // 2. Render template + parse → messages let messages = prompty::prepare( &agent, Some(&json!({ "userName": "Jane" })) ).await?; // 3. Call the LLM + process → clean result let result = prompty::run(&agent, &messages).await?; ``` -------------------------------- ### Minimal Prompty Example for Debugging Source: https://prompty.ai/how-to/troubleshooting Use this minimal configuration to verify basic functionality and isolate issues. Ensure your environment variables are correctly set. ```yaml --- name: debug model: id: gpt-4o-mini provider: openai apiType: chat connection: kind: key apiKey: ${env:OPENAI_API_KEY} --- system: Say hello. ``` -------------------------------- ### Install Prompty with OpenAI support (.NET) Source: https://prompty.ai/how-to/openai Add the Prompty Core and Prompty OpenAI packages as pre-release dependencies using the dotnet CLI. ```bash dotnet add package Prompty.Core --prerelease dotnet add package Prompty.OpenAI --prerelease ``` -------------------------------- ### Example Nonce String Source: https://prompty.ai/specification/rendering Provides a concrete example of a nonce string used for the 'conversation' property within a thread. ```plaintext __PROMPTY_THREAD_a1b2c3d4e5f6a7b8_conversation__ ``` -------------------------------- ### ValidationError Yaml Example Source: https://prompty.ai/reference/validationerror This example shows the structure of a ValidationError in YAML format, indicating a missing required input. ```yaml message: "Missing required input: firstName" property: firstName constraint: required ``` -------------------------------- ### TraceSpan YAML Example Source: https://prompty.ai/reference/tracespan Example of a TraceSpan defined in YAML format, showing its name, signature, and error status. ```yaml name: prompty.core.pipeline.run signature: prompty.core.pipeline.run error: Connection refused ``` -------------------------------- ### ExecuteError Yaml Example Source: https://prompty.ai/reference/executeerror This YAML example shows the structure of an ExecuteError, including the error message and the conversation state. ```yaml message: "LLM call failed after 3 retries: rate limit exceeded" messages: - role: system parts: - kind: text value: You are a helpful assistant. - role: user parts: - kind: text value: Hello ``` -------------------------------- ### Load, Prepare, and Run a Prompty Agent (JavaScript) Source: https://prompty.ai/getting-started Use this snippet to load a .prompty file, prepare messages with inputs, and run the agent. Ensure you have installed the core and OpenAI packages. ```javascript import { load, prepare, run } from "@prompty/core"; import "@prompty/openai"; const agent = await load("greeting.prompty"); const messages = await prepare(agent, { userName: "Jane" }); const result = await run(agent, messages); ``` -------------------------------- ### CompactionCompletePayload YAML Example Source: https://prompty.ai/reference/compactioncompletepayload Example of the CompactionCompletePayload in YAML format, showing the number of messages removed and remaining after compaction. ```yaml removed: 5 remaining: 3 ``` -------------------------------- ### Install Missing npm Package Source: https://prompty.ai/how-to/troubleshooting Install the necessary npm package for Prompty's OpenAI integration in a TypeScript project. ```bash npm install @prompty/openai ``` -------------------------------- ### Install Missing Python Dependency Source: https://prompty.ai/how-to/troubleshooting Use this command to install optional Python dependencies for Prompty, such as renderers or specific integrations. ```bash uv pip install "prompty[openai]" ``` ```bash uv pip install "prompty[jinja2]" ``` ```bash uv pip install "prompty[mustache]" ``` ```bash uv pip install "prompty[foundry]" ``` -------------------------------- ### Register and Get Connection Source: https://prompty.ai/specification/registries Demonstrates how to register a pre-configured LLM client with a name and retrieve it later. Ensure thread-safety for registry operations. ```python register_connection(name, client) get_connection(name) → client clear_connections() ``` -------------------------------- ### Install OpenTelemetry Package (TypeScript) Source: https://prompty.ai/core-concepts/tracing Installs the OpenTelemetry API package for TypeScript, required for using the OTel tracer backend. ```bash npm install @opentelemetry/api ``` -------------------------------- ### Install Prompty for Foundry (C#) Source: https://prompty.ai/how-to/foundry Add the Prompty Core and Prompty Foundry packages as prerelease versions to your C# project. ```bash dotnet add package Prompty.Core --prerelease dotnet add package Prompty.Foundry --prerelease ``` -------------------------------- ### ToolContext Metadata Example Source: https://prompty.ai/reference/toolcontext This YAML example demonstrates how to define metadata within a ToolContext, such as a userId for user session information. ```yaml metadata: userId: user-123 ``` -------------------------------- ### GuardrailError Reason Example Source: https://prompty.ai/reference/guardrailerror This YAML example shows the structure of the 'reason' field within a GuardrailError, explaining why content was denied. ```yaml reason: Content contains personally identifiable information ``` -------------------------------- ### Load Prompt Agent Algorithm Source: https://prompty.ai/specification/loading Illustrates the step-by-step process for loading a prompt agent, including path resolution, file reading, frontmatter parsing, reference resolution, shorthand expansion, and type injection. ```python function load(path): 1. path ← resolve_to_absolute(path) 2. If file at path does not exist: RAISE FileNotFoundError("File not found: {path}") 3. contents ← read_file_utf8(path) 4. data ← parse_frontmatter(contents): a. If contents does not start with "---" or "+++" (ignoring leading whitespace): RETURN {instructions: contents} b. Apply reference regex (§2.2) to contents c. If regex does not match: RAISE ValueError("Malformed frontmatter in {path}") d. frontmatter_yaml ← regex group 1 e. body ← regex group 2 f. parsed ← yaml_parse(frontmatter_yaml) g. If parsed is not a dict: RAISE ValueError("Frontmatter must be a YAML mapping") h. parsed["instructions"] ← body i. RETURN parsed 5. data ← resolve_references(data, base_dir=parent(path)): Walk every value in data recursively: For each string value matching ${protocol:content}: protocol ← lowercase text before first ":" content ← text after first ":" SWITCH protocol: CASE "env": var_name, _, default ← content.partition(":") value ← environment_variable(var_name) IF value is not set: IF default is not empty: REPLACE with default ELSE: RAISE ValueError("Environment variable '{var_name}' not set") ELSE: REPLACE with value CASE "file": file_path ← resolve(base_dir / content) IF file does not exist: RAISE FileNotFoundError("Referenced file '{content}' not found") extension ← file_path.suffix.lower() IF extension == ".json": REPLACE with json_parse(read_file(file_path)) ELIF extension in (".yaml", ".yml"): REPLACE with yaml_parse(read_file(file_path)) ELSE: REPLACE with read_file_text(file_path) DEFAULT: Leave value unchanged (unknown protocol) 6. Apply shorthand expansions: a. IF data["model"] is a string: data["model"] ← {id: data["model"]} b. IF data["template"] is missing: data["template"] ← {format: {kind: "jinja2"}, parser: {kind: "prompty"}} c. IF data["template"] is a string: data["template"] ← {format: {kind: data["template"]}, parser: {kind: "prompty"}} d. For each property in data["inputs"] (if dict form): IF value is a scalar (not a dict): Convert to Property(kind: infer_kind(value), default: value) 7. Inject kind: data["kind"] ← "prompt" // .prompty files always produce PromptAgents 8. agent ← load_typed_agent(data) // Use the generated model loader for the target language // This validates types and produces a PromptAgent instance 9. RETURN agent ``` -------------------------------- ### Build Documentation Source: https://prompty.ai/contributing/docs-guidelines Test a production build of the documentation. Check for errors and warnings before submitting changes. ```bash npm run build npm run start ``` -------------------------------- ### ImagePart YAML Configuration Source: https://prompty.ai/reference/imagepart Example of how to configure an ImagePart using YAML, specifying the image source URL, detail level, and media type. ```yaml source: https://example.com/image.png detail: auto mediaType: image/png ``` -------------------------------- ### Register Production Connection Client (Rust) Source: https://prompty.ai/tutorials/production Register a pre-configured client with Prompty for production environments. This example shows configuration via environment variables and the Azure SDK's DefaultAzureCredential equivalent. ```rust use prompty; use serde_json::json; prompty::register_connection("prod-client", json!({ "kind": "key", "endpoint": std::env::var("AZURE_ENDPOINT")?, "apiKey": std::env::var("AZURE_API_KEY")?, })); // For managed identity, configure via environment variables // and use the Azure SDK's DefaultAzureCredential equivalent. ``` -------------------------------- ### Invoke Prompty Pipeline in C# Source: https://prompty.ai/core-concepts/pipeline Set up the Prompty builder and add the desired provider. Then, use `Pipeline.InvokeAsync` to run the Prompty file with inputs. ```csharp using Prompty.Core; using MyPackage.Anthropic; // provides .AddAnthropic() new PromptyBuilder().AddAnthropic(); var result = await Pipeline.InvokeAsync("claude-chat.prompty", new() { ["question"] = "Hello!" }); ``` -------------------------------- ### Basic Chat Completion with OpenAI (C#) Source: https://prompty.ai/getting-started This C# example demonstrates a basic chat completion by loading a .prompty file and invoking it. It sets up the Prompty builder with OpenAI support. ```csharp // Copyright (c) Microsoft. All rights reserved. using Prompty.Core; using Prompty.OpenAI; namespace DocsExamples.Examples; /// /// Basic chat completion — load a .prompty file and invoke it. /// public static class ChatBasic { /// /// Load a .prompty file and run the full pipeline (render → parse → execute → process). /// public static async Task RunAsync(string promptyPath, Dictionary? inputs = null) { // One-time setup — registers renderers, parser, and OpenAI provider new PromptyBuilder() .AddOpenAI(); // Full pipeline: load → prepare → run var result = await Pipeline.InvokeAsync(promptyPath, inputs); return result; } } ``` -------------------------------- ### Tool Dispatch Order Example Source: https://prompty.ai/specification/registries Illustrates the dispatch order for tool execution, prioritizing name registry lookups over kind handlers. Raises an error if no handler is found. ```python handler = get_tool(N) → if found, execute handler(args) and return result handler = get_tool_handler(K) → if found, execute handler(tool_def, args, agent, inputs) and return result raise ValueError("No handler registered for tool: " + N + " (kind: " + K + ")") ``` -------------------------------- ### Connection Registry Source: https://prompty.ai/implementation/python Shows how to pre-configure SDK clients for production use by registering them with Prompty, demonstrated with an Azure OpenAI client. ```APIDOC ## Connection Registry Pre-configure SDK clients for production use: ```python from openai import AzureOpenAI from azure.identity import DefaultAzureCredential, get_bearer_token_provider client = AzureOpenAI( azure_endpoint=os.environ["AZURE_ENDPOINT"], azure_ad_token_provider=get_bearer_token_provider( DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default", ), ) prompty.register_connection("azure-prod", client=client) ``` ``` -------------------------------- ### FileNotFoundError Yaml Example Source: https://prompty.ai/reference/filenotfounderror This example shows the structure of a FileNotFoundError when a .prompty file is not found. It includes the error message and the problematic file path. ```yaml message: "Prompty file not found: ./chat.prompty" path: ./chat.prompty ``` -------------------------------- ### Install Prompty Core and OpenAI (Rust) Source: https://prompty.ai/getting-started Add the core Prompty library and the OpenAI provider crate to your Rust project using cargo. ```bash cargo add prompty prompty-openai ```