### Quick Start Source: https://microsoft.github.io/poml/stable/typescript A quick start guide demonstrating how to use the POML TypeScript API to parse and render prompts. ```APIDOC ## Quick Start ```typescript import { Paragraph, Image } from 'poml/essentials'; import { read, write } from 'poml'; const prompt = Hello, world! Here is an image: A beautiful scenery ; // Parse the prompt components into an intermediate representation (IR) const ir = await read(prompt); // Render it to different formats const markdown = write(ir); ``` ``` -------------------------------- ### Using the Hint Component Source: https://microsoft.github.io/poml/stable/language/components Demonstrates how to use the hint component to provide a guiding statement for the LLM. This example shows a simple arithmetic problem to illustrate the concept. ```markdown Alice first purchased 4 apples and then 3 more, so she has 7 apples in total. ``` -------------------------------- ### Example with Task and Captions Source: https://microsoft.github.io/poml/stable/language/components This example demonstrates how to use and tags together, with captions for input and output, to illustrate a specific task like summarization. ```xml Summarize the following passage in a single sentence. The sun provides energy for life on Earth through processes like photosynthesis. The sun is essential for energy and life processes on Earth. ``` -------------------------------- ### Basic Prompt Example Source: https://microsoft.github.io/poml/stable/python/reference/prompt Demonstrates a basic usage of the `example` function for creating a prompt with a caption. ```python from prompt import example example(caption='This is a sample caption') ``` -------------------------------- ### Example Set Function Source: https://microsoft.github.io/poml/stable/python/reference/prompt Use this function to set up an example with optional captioning and chat configurations. Ensure all parameters are correctly passed. ```python example_set( chat=chat, introducer=introducer, captionStyle=captionStyle, captionTextTransform=captionTextTransform, captionEnding=captionEnding, **kwargs, ) ``` -------------------------------- ### Install LangChain and OpenAI Packages Source: https://microsoft.github.io/poml/stable/python/integration/langchain Install the necessary libraries for LangChain and OpenAI integration. ```bash pip install langchain langchain-openai ``` -------------------------------- ### ExampleSet Source: https://microsoft.github.io/poml/stable/typescript/reference/components Manages a collection of examples, allowing for a shared title, introducer, and chat format for multiple examples. ```APIDOC ## ExampleSet() ### Description Example set (``) is a collection of examples that are usually presented in a list. With the example set, you can manage multiple examples under a single title and optionally an introducer, as well as the same `chat` format. You can also choose to use `` purely without example set. ### Parameters #### props `PropsWithChildren` ### Returns `Element` ### Example ```html What is the capital of France? Paris What is the capital of Germany? Berlin ``` ``` -------------------------------- ### LangChain FewShotPromptTemplate Example Source: https://microsoft.github.io/poml/stable/python/integration/langchain Demonstrates how to create a FewShotPromptTemplate in LangChain using predefined examples and templates. This is useful for providing context and examples to language models. ```python from langchain.prompts import FewShotPromptTemplate, PromptTemplate examples = [ {"input": "2+2", "output": "4"}, {"input": "3*3", "output": "9"} ] example_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}" ) few_shot_prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, prefix="Solve these math problems:", suffix="Input: {input}\nOutput:", input_variables=["input"] ) ``` -------------------------------- ### Basic Example Structure Source: https://microsoft.github.io/poml/stable/language/components Use the tag to provide context and demonstrate expected input/output pairs. This helps clarify the desired response style and structure. ```xml What is the capital of France? Paris ``` -------------------------------- ### Use ExampleSet for Multiple Examples Source: https://microsoft.github.io/poml/stable/typescript/reference/components The ExampleSet component is used to manage a collection of examples, typically presented in a list. It allows for a shared title, introducer, and chat format for all contained examples. Use `` elements within `` to define individual examples with inputs and outputs. ```typescript What is the capital of France? Paris What is the capital of Germany? Berlin ``` -------------------------------- ### Quick Start: POML TypeScript API Source: https://microsoft.github.io/poml/stable/typescript Demonstrates parsing prompt components into an intermediate representation (IR) and rendering it to markdown using the POML TypeScript API. Ensure 'poml/essentials' and 'poml' are installed. ```typescript import { Paragraph, Image } from 'poml/essentials'; import { read, write } from 'poml'; const prompt = Hello, world! Here is an image: A beautiful scenery ; // Parse the prompt components into an intermediate representation (IR) const ir = await read(prompt); // Render it to different formats const markdown = write(ir); ``` -------------------------------- ### example_set Source: https://microsoft.github.io/poml/stable/python/reference/prompt Manages a collection of examples, allowing for a title, introducer, and chat format rendering. This can be used to group multiple `` tags under a single heading. ```APIDOC ## example_set ### Description Manages a collection of examples, allowing for a title, introducer, and chat format rendering. This can be used to group multiple `` tags under a single heading. ### Method Signature `example_set(caption=None, captionSerialized=None, chat=None, introducer=None, captionStyle=None, captionTextTransform=None, captionEnding=None, **kwargs)` ### Parameters #### Parameters - **caption** (Optional[str]) - The title or label for the example set paragraph. Default is `Examples`. - **captionSerialized** (Optional[str]) - The serialized version of the caption when using "serializer" syntaxes. Default is `examples`. - **chat** (Optional[bool]) - Indicates whether the examples should be rendered in chat format. By default, it's `true` for "markup" syntaxes and `false` for "serializer" syntaxes. - **introducer** (Optional[str]) - An optional introducer text to be displayed before the examples. For example, `Here are some examples:`. - **captionStyle** (Optional[str]) - Determines the style of the caption, applicable only for "markup" syntaxes. Default is `header`. Choices: `"header"`, `"bold"`, `"plain"`, `"hidden"`. - **captionTextTransform** (Optional[str]) - Specifies text transformation for the caption, applicable only for "markup" syntaxes. Default is `none`. Choices: `"upper"`, `"level"`, `"capitalize"`, `"none"`. - **captionEnding** (Optional[str]) - A caption can ends with a colon, a newline or simply nothing. If not specified, it defaults to `colon` for `bold` or `plain` captionStyle, and `none` otherwise. Choices: `"colon"`, `"newline"`, `"colon-newline"`, `"none"`. ### Example ```xml What is the capital of France? Paris What is the capital of Germany? Berlin ``` ``` -------------------------------- ### example Source: https://microsoft.github.io/poml/stable/python/reference/prompt This function is used to create an example within the prompt, potentially with a caption and specific styling. It accepts various optional arguments to customize its appearance and behavior. ```APIDOC ## `example(caption=None, captionSerialized=None, captionStyle=None, chat=None, captionTextTransform=None, captionColon=None, **kwargs)` ### Description Used to create an example within the prompt. Allows for customization of captions, styling, and text transformation. ### Parameters - **caption** (any) - Optional - The caption for the example. - **captionSerialized** (any) - Optional - Serialized caption for the example. - **captionStyle** (any) - Optional - Style for the caption. - **chat** (any) - Optional - Represents chat-related content. - **captionTextTransform** (any) - Optional - Transformation for the caption text. - **captionColon** (any) - Optional - Controls the display of a colon in the caption. - **kwargs** (any) - Additional keyword arguments. ``` -------------------------------- ### POML Approach for Structured Examples Source: https://microsoft.github.io/poml/stable/python/integration/langchain Illustrates how to represent structured few-shot examples using the POML format. This approach defines tasks, examples, and human messages within an XML-like structure. ```xml Solve these math problems: {{ ex.input }} {{ ex.output }} {{ input }} ``` -------------------------------- ### Google Gemini Configuration Example Source: https://microsoft.github.io/poml/stable/vscode/configuration Example configuration for using Google Gemini, including provider, model, and API key. ```json { "poml.languageModel.provider": "google", "poml.languageModel.model": "gemini-1.5-pro", "poml.languageModel.apiKey": "your-google-api-key" } ``` -------------------------------- ### Install POML with Weave Support Source: https://microsoft.github.io/poml/stable/python/integration/weave Install the POML library with agent support, which includes Weave integration. Alternatively, install Weave separately if needed. ```bash pip install poml[agent] ``` ```bash pip install weave ``` -------------------------------- ### example() Source: https://microsoft.github.io/poml/stable/python/reference/prompt The `example` tag is used to provide context and demonstrate expected inputs and outputs for a model. It helps clarify the desired structure, tone, or level of detail in the response. ```APIDOC ## example() ### Description Provides context for model inputs and outputs, demonstrating desired response style. ### Method Signature ```python example( caption: Optional[str] = None, captionSerialized: Optional[str] = None, captionStyle: Optional[str] = None, chat: Optional[bool] = None, captionTextTransform: Optional[str] = None, captionColon: Optional[bool] = None, **kwargs: Any ) ``` ### Parameters #### Parameters - **caption** (Optional[str]) - The title or label for the example paragraph. Defaults to `"Example"`. - **captionSerialized** (Optional[str]) - The serialized version of the caption when using "serializer" syntaxes. Defaults to `"example"`. - **captionStyle** (Optional[str]) - Determines the style of the caption for "markup" syntaxes. Options: `header`, `bold`, `plain`, `hidden`. Defaults to `"hidden"`. - **chat** (Optional[bool]) - Indicates if the example should be rendered in chat format. Defaults to `false` for "serializer" syntaxes and `true` for "markup" syntaxes when not inherited. - **captionTextTransform** (Optional[str]) - Specifies text transformation for the caption for "markup" syntaxes. Options: `upper`, `lower`, `capitalize`, `none`. Defaults to `"none"`. - **captionColon** (Optional[bool]) - Indicates whether to append a colon after the caption. Defaults to `true` for `bold` or `plain` captionStyle, and `false` otherwise. ### Example ```xml What is the capital of France? Paris ``` ```xml Summarize the following passage in a single sentence. The sun provides energy for life on Earth through processes like photosynthesis. The sun is essential for energy and life processes on Earth. ``` ``` -------------------------------- ### ExampleSet with Chat Enabled Source: https://microsoft.github.io/poml/stable/language/components Use the ExampleSet component with the 'chat' attribute enabled to manage a list of input-output examples for a chat-like interaction. Each tag contains an and an tag. ```html What is the capital of France? Paris What is the capital of Germany? Berlin ``` -------------------------------- ### Example() Source: https://microsoft.github.io/poml/stable/typescript/reference/components Provides context and demonstrates expected inputs and outputs, helping to clarify desired response styles and structures. ```APIDOC ## Example() ### Description Example is useful for providing a context, helping the model to understand what kind of inputs and outputs are expected. It can also be used to demonstrate the desired output style, clarifying the structure, tone, or level of detail in the response. ### Signature `const Example: (props) => Element` ### Parameters #### props `PropsWithChildren` ### Returns `Element` ### See Paragraph for other props available. ### Example ```html What is the capital of France? Paris ``` ```html Summarize the following passage in a single sentence. The sun provides energy for life on Earth through processes like photosynthesis. The sun is essential for energy and life processes on Earth. ``` ``` -------------------------------- ### Install POML Python SDK Source: https://microsoft.github.io/poml/stable/tutorial/expense_part1 Install the necessary Python packages for POML, OpenAI, and Pydantic. Ensure you have Python 3.9+ installed. ```bash pip install poml openai pydantic ``` -------------------------------- ### Install MCP Package Source: https://microsoft.github.io/poml/stable/python/integration/mcp Install the MCP package using pip. ```bash pip install mcp ``` -------------------------------- ### Prompt with Serialized Caption Source: https://microsoft.github.io/poml/stable/python/reference/prompt Shows how to use `example` with a serialized caption, useful for complex caption structures. ```python from prompt import example example(captionSerialized='{"text": "Serialized Caption"}') ``` -------------------------------- ### POML Example with Variables and Schema Source: https://microsoft.github.io/poml/stable/vscode/features This example demonstrates defining variables, performing calculations, and defining an output schema using POML syntax. It shows how to use let bindings for variables and expressions within template tags. ```poml

We have {{ count }} items: {{ items.join(', ') }}

z.object({ total: z.number().max(count), items: z.array(z.enum(items)) })
``` -------------------------------- ### Azure OpenAI Configuration Example Source: https://microsoft.github.io/poml/stable/vscode/configuration Example configuration for using Azure OpenAI, including provider, model deployment name, API key, URL, and API version. ```json { "poml.languageModel.provider": "microsoft", "poml.languageModel.model": "my-gpt4-deployment", "poml.languageModel.apiKey": "your-azure-api-key", "poml.languageModel.apiUrl": "https://your-resource.openai.azure.com/", "poml.languageModel.apiVersion": "2024-02-15-preview" } ``` -------------------------------- ### Chat Prompt Example Source: https://microsoft.github.io/poml/stable/python/reference/prompt Provides an example of creating a prompt intended for chat interactions using the `chat` parameter. ```python from prompt import example example(caption='Chat Prompt', chat=True) ``` -------------------------------- ### Jinja2/f-string Prompt Template Example Source: https://microsoft.github.io/poml/stable/python/integration/langchain Example of a basic prompt template using Langchain's PromptTemplate, suitable for string interpolation and simple logic. ```python from langchain.prompts import PromptTemplate prompt_template = PromptTemplate.from_template( "Answer the question as if you are {person}, fully embodying their style, " "wit, personality, and habits of speech. The question is: {question}" ) ``` -------------------------------- ### ExampleOutput() Source: https://microsoft.github.io/poml/stable/typescript/reference/components Represents an example output, typically spoken by an AI in a chat context. Can be customized with a caption. ```APIDOC ## ExampleOutput() ### Description ExampleOutput (``) is a paragraph that represents an example output. By default, it's spoken by a AI speaker in a chat context, but you can manually specify the speaker. ### Signature `const ExampleOutput: (props) => Element` ### Parameters #### props `PropsWithChildren` ### Returns `Element` ### See Paragraph for other props available. ### Example ```html The capital of France is Paris. ``` When used with a template: ```html The capital of {{country}} is {{capital}}. ``` ``` -------------------------------- ### Install POML Python SDK (Nightly Build) Source: https://microsoft.github.io/poml/stable/python Install the latest nightly build of the POML Python SDK from the test PyPI repository. This is useful for testing pre-release versions. ```bash pip install --upgrade --pre --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ poml ``` -------------------------------- ### Install POML TypeScript API (Nightly) Source: https://microsoft.github.io/poml/stable/typescript Install the nightly build of the POML TypeScript API using npm. ```bash npm install pomljs@nightly ``` -------------------------------- ### example_input Source: https://microsoft.github.io/poml/stable/python/reference/prompt Represents an example input within a prompt. It can be spoken by a specified speaker and has customizable caption properties. ```APIDOC ## example_input ### Description Represents an example input paragraph. By default, it's spoken by a human speaker in a chat context, but you can manually specify the speaker. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **caption** (Optional[str]) - The title or label for the example input paragraph. Default is `Input`. - **captionSerialized** (Optional[str]) - The serialized version of the caption when using "serializer" syntaxes. Default is `input`. - **speaker** (Optional[str]) - The speaker for the example input. Default is `human` if chat context is enabled. - **captionStyle** (Optional[str]) - Determines the style of the caption, applicable only for "markup" syntaxes. Default is `hidden` if chat context is enabled. Otherwise, it's `bold`. Choices: `"header"`, `"bold"`, `"plain"`, `"hidden"`. - **captionTextTransform** (Optional[str]) - Specifies text transformation for the caption, applicable only for "markup" syntaxes. Default is `none`. Choices: `"upper"`, `"level"`, `"capitalize"`, `"none"`. - **captionColon** (Optional[bool]) - Indicates whether to append a colon after the caption. By default, this is true for `bold` or `plain` captionStyle, and false otherwise. ### Request Example ```xml What is the capital of France? ``` When used with a template: ```xml What is the capital of {{country}}? ``` ### Response #### Success Response (200) None explicitly documented. #### Response Example None explicitly documented. ``` -------------------------------- ### POML Template Syntax Example Source: https://microsoft.github.io/poml/stable/python/integration/langchain Illustrates POML's structured template syntax, including system messages, human messages, and conditional inclusion of examples. ```xml You are {{ person }}, answer in their unique style and personality. {{ question }}
``` -------------------------------- ### example_output Source: https://microsoft.github.io/poml/stable/python/reference/prompt Represents an example output, which can be spoken by an AI speaker or customized with various caption and speaker options. ```APIDOC ## example_output ### Description ExampleOutput (``) is a paragraph that represents an example output. By default, it's spoken by a AI speaker in a chat context, but you can manually specify the speaker. ### Parameters #### Path Parameters - `caption` (Optional[str]) - Optional - The title or label for the example output paragraph. Default is `Output`. - `captionSerialized` (Optional[str]) - Optional - The serialized version of the caption when using "serializer" syntaxes. Default is `output`. - `speaker` (Optional[str]) - Optional - The speaker for the example output. Default is `ai` if chat context is enabled. - `captionStyle` (Optional[str]) - Optional - Determines the style of the caption, applicable only for "markup" syntaxes. Default is `hidden` if chat context is enabled. Otherwise, it's `bold`. Choices: `"header"`, `"bold"`, `"plain"`, `"hidden"`. - `captionTextTransform` (Optional[str]) - Optional - Specifies text transformation for the caption, applicable only for "markup" syntaxes. Default is `none`. Choices: `"upper"`, `"level"`, `"capitalize"`, `"none"`. - `captionColon` (Optional[bool]) - Optional - Indicates whether to append a colon after the caption. By default, this is true for `bold` or `plain` captionStyle, and false otherwise. ### Request Example ```xml The capital of France is Paris. ``` When used with a template: ```xml The capital of {{country}} is {{capital}}. ``` ``` -------------------------------- ### Anthropic Claude Configuration Example Source: https://microsoft.github.io/poml/stable/vscode/configuration Example configuration for using Anthropic Claude, specifying the provider, model, and API key. ```json { "poml.languageModel.provider": "anthropic", "poml.languageModel.model": "claude-3-5-sonnet-20241022", "poml.languageModel.apiKey": "your-anthropic-api-key" } ``` -------------------------------- ### ExampleInput() Source: https://microsoft.github.io/poml/stable/typescript/reference/components Represents an example input, typically spoken by a human in a chat context. Can be customized with a caption. ```APIDOC ## ExampleInput() ### Description ExampleInput (``) is a paragraph that represents an example input. By default, it's spoken by a human speaker in a chat context, but you can manually specify the speaker. ### Signature `const ExampleInput: (props) => Element` ### Parameters #### props `PropsWithChildren` ### Returns `Element` ### See Paragraph for other props available. ### Example ```html What is the capital of France? ``` When used with a template: ```html What is the capital of {{country}}? ``` ``` -------------------------------- ### Install POML TypeScript API (Stable) Source: https://microsoft.github.io/poml/stable/typescript Install the stable release of the POML TypeScript API using npm. ```bash npm install pomljs ``` -------------------------------- ### Installation Source: https://microsoft.github.io/poml/stable/typescript Install the POML TypeScript API package via npm. You can choose between the stable release or the nightly build. ```APIDOC ## Installation ### Stable Release To use the POML TypeScript API, install the package via npm: ```bash npm install pomljs ``` ### Nightly Build ```bash npm install pomljs@nightly ``` ``` -------------------------------- ### POML Output for Structured Examples Source: https://microsoft.github.io/poml/stable/python/integration/langchain Shows the resulting structured output from the POML approach for few-shot examples, formatted as a list of message objects suitable for AI interactions. ```json [ { "speaker": "system", "content": "# Task\n\nSolve these math problems:" }, { "speaker": "human", "content": "2+2" }, { "speaker": "ai", "content": "4" }, { "speaker": "human", "content": "3*3" }, { "speaker": "ai", "content": "9" }, { "speaker": "human", "content": "5-4" } ] ``` -------------------------------- ### Example Output Component Source: https://microsoft.github.io/poml/stable/typescript/reference/components Represents an example output, typically spoken by an AI in a chat context. Can be used with templates for dynamic content. ```html The capital of France is Paris. ``` ```html The capital of {{country}} is {{capital}}. ``` -------------------------------- ### Install POML with AgentOps Support Source: https://microsoft.github.io/poml/stable/python/integration/agentops Install the POML library with the necessary AgentOps integration package. This command ensures all dependencies for AgentOps tracing are included. ```bash pip install poml[agent] ``` -------------------------------- ### Example Input Component Source: https://microsoft.github.io/poml/stable/typescript/reference/components Represents an example input, typically spoken by a human in a chat context. Can be used with templates for dynamic content. ```html What is the capital of France? ``` ```html What is the capital of {{country}}? ``` -------------------------------- ### Basic Input Component Usage Source: https://microsoft.github.io/poml/stable/language/components Use the `` component to define a simple example input. This is useful for demonstrating user prompts or queries. ```html What is the capital of France? ``` -------------------------------- ### Install POML Python SDK (Stable Release) Source: https://microsoft.github.io/poml/stable/python Use this command to install the latest stable version of the POML Python SDK. Ensure pip is up-to-date for the best experience. ```bash pip install --upgrade poml ``` -------------------------------- ### Basic Output Component Usage Source: https://microsoft.github.io/poml/stable/language/components Use the `` component to represent an example output. This is typically used to show the result of a process or query. ```html The capital of France is Paris. ``` -------------------------------- ### Enable POML Tracing Source: https://microsoft.github.io/poml/stable/python/trace Start tracing all POML calls by specifying a directory to store the trace files. ```python import poml # Start tracing all POML calls poml.set_trace(trace_dir="pomlruns") ``` -------------------------------- ### introducer Source: https://microsoft.github.io/poml/stable/python/reference/prompt The introducer tag is used to provide a paragraph that sets the context before a list of examples, steps, or instructions. ```APIDOC ## introducer(caption=None, captionSerialized=None, captionStyle=None, captionTextTransform=None, captionEnding=None, **kwargs) ### Description Introducer is a paragraph before a long paragraph (usually a list of examples, steps, or instructions). It serves as a context introducing what is expected to follow. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **caption** (Optional[str]) - Optional - The title or label for the introducer paragraph. Default is `Introducer`. - **captionSerialized** (Optional[str]) - Optional - The serialized version of the caption when using "serializer" syntaxes. Default is `introducer`. - **captionStyle** (Optional[str]) - Optional - Determines the style of the caption, applicable only for "markup" syntaxes. Default is `hidden`. Choices: `"header"`, `"bold"`, `"plain"`, `"hidden"`. - **captionTextTransform** (Optional[str]) - Optional - Specifies text transformation for the caption, applicable only for "markup" syntaxes. Default is `none`. Choices: `"upper"`, `"level"`, `"capitalize"`, `"none"`. - **captionEnding** (Optional[str]) - Optional - A caption can ends with a colon, a newline or simply nothing. If not specified, it defaults to `colon` for `bold` or `plain` captionStyle, and `none` otherwise. Choices: `"colon"`, `"newline"`, `"colon-newline"`, `"none"`. ### Request Example ```xml Here are some examples. ``` ### Response #### Success Response (200) - **None** - No specific response fields documented. #### Response Example None ``` -------------------------------- ### Complete POML Configuration Source: https://microsoft.github.io/poml/stable/vscode/configuration A comprehensive example of POML settings, including language model provider, model, API key, URL, and editor behavior. ```json { "poml.languageModel.provider": "openai", "poml.languageModel.model": "gpt-4o", "poml.languageModel.apiKey": "sk-your-api-key-here", "poml.languageModel.apiUrl": "https://api.openai.com/v1/", "poml.languageModel.temperature": 0.7, "poml.languageModel.maxTokens": 1500, "poml.scrollPreviewWithEditor": true, "poml.markEditorSelection": true, "poml.trace": "off" } ``` -------------------------------- ### Configure MLflow Tracking Server Source: https://microsoft.github.io/poml/stable/python/integration/mlflow Set up your MLflow tracking server. You can start a local server for development or configure a remote server using an environment variable. ```bash # Start a local MLflow tracking server mlflow server --host 0.0.0.0 --port 5000 ``` ```bash # Or use a remote tracking server export MLFLOW_TRACKING_URI="http://your-mlflow-server:5000" ``` -------------------------------- ### POML Trace Environment File Example Source: https://microsoft.github.io/poml/stable/python/trace The .env file for POML traces includes environment metadata such as the source file path and any environment-specific configuration. ```text SOURCE_PATH=/home/user/project/prompts/calculator.poml POML_VERSION=1.0.0 ``` -------------------------------- ### example_set Source: https://microsoft.github.io/poml/stable/python/reference/prompt Configures a prompt with various caption and chat introduction settings. ```APIDOC ## example_set ### Description Configures a prompt with various caption and chat introduction settings. ### Signature `example_set(caption=None, captionSerialized=None, chat=None, introducer=None, captionStyle=None, captionTextTransform=None, captionEnding=None, **kwargs)` ### Parameters - **caption** (any) - Optional - The caption for the example. - **captionSerialized** (any) - Optional - A serialized version of the caption. - **chat** (any) - Optional - The chat object associated with the prompt. - **introducer** (any) - Optional - An introducer for the chat. - **captionStyle** (any) - Optional - The style of the caption. - **captionTextTransform** (any) - Optional - Text transformation for the caption. - **captionEnding** (any) - Optional - The ending for the caption. - **kwargs** - Additional keyword arguments. ### Usage Example ```python example_set(caption="This is a caption", chat=my_chat_object) ``` ``` -------------------------------- ### POML Loop Variables Example Source: https://microsoft.github.io/poml/stable/language/template Utilizes loop variables like 'loop.index' to dynamically generate captions for list items. The 'loop.index' starts from 0, so it's often incremented for user-friendly display. ```xml {{ example.input }} {{ example.output }} ``` -------------------------------- ### Python Function for Example Tag Source: https://microsoft.github.io/poml/stable/python/reference/prompt This Python function, `example`, is part of the POML library and is used to generate 'Example' tags. It accepts various parameters to control the caption, serialization, styling, and chat rendering of the example. ```python def example( self, caption: Optional[str] = None, captionSerialized: Optional[str] = None, captionStyle: Optional[str] = None, chat: Optional[bool] = None, captionTextTransform: Optional[str] = None, captionColon: Optional[bool] = None, **kwargs: Any, ): """Example is useful for providing a context, helping the model to understand what kind of inputs and outputs are expected. It can also be used to demonstrate the desired output style, clarifying the structure, tone, or level of detail in the response. Args: caption (Optional[str]): The title or label for the example paragraph. Default is `Example`. Default is `"Example"`. captionSerialized (Optional[str]): The serialized version of the caption when using "serializer" syntaxes. Default is `example`. Default is `"example"`. captionStyle (Optional[str]): Determines the style of the caption, applicable only for "markup" syntaxes. Default is `hidden`. Options include `header`, `bold`, `plain`, or `hidden`. Default is `"hidden"`. chat (Optional[bool]): Indicates whether the example should be rendered in chat format. When used in a example set (``), this is inherited from the example set. Otherwise, it defaults to `false` for "serializer" syntaxes and `true` for "markup" syntaxes. captionTextTransform (Optional[str]): Specifies text transformation for the caption, applicable only for "markup" syntaxes. Options are `upper`, `lower`, `capitalize`, or `none`. Default is `none`. Default is `"none"`. captionColon (Optional[bool]): Indicates whether to append a colon after the caption. By default, this is true for `bold` or `plain` captionStyle, and false otherwise. Example: ```xml What is the capital of France? Paris ``` ```xml Summarize the following passage in a single sentence. The sun provides energy for life on Earth through processes like photosynthesis. The sun is essential for energy and life processes on Earth. ``` """ return self.tag( tag_name="Example", caption=caption, captionSerialized=captionSerialized, captionStyle=captionStyle, chat=chat, captionTextTransform=captionTextTransform, captionColon=captionColon, ``` -------------------------------- ### Install MLflow Separately Source: https://microsoft.github.io/poml/stable/python/integration/mlflow Alternatively, install MLflow and the MLflow-GenAI package separately if POML is already installed or if you prefer managing MLflow dependencies independently. ```bash pip install mlflow mlflow-genai ``` -------------------------------- ### Install AgentOps Separately Source: https://microsoft.github.io/poml/stable/python/integration/agentops Alternatively, install the AgentOps library independently if POML is already installed or managed separately. This is useful for integrating AgentOps into existing projects. ```bash pip install agentops ``` -------------------------------- ### Basic POML Example Source: https://microsoft.github.io/poml/stable/tutorial/quickstart This snippet shows a minimal POML file structure. It defines the LLM's role, the task it should perform, an image to reference, and the desired output format. Place this in a file named 'example.poml' in the same directory as your image. ```poml You are a patient teacher explaining concepts to a 10-year-old. Explain the concept of photosynthesis using the provided image as a reference. Diagram of photosynthesis Keep the explanation simple, engaging, and under 100 words. Start with "Hey there, future scientist!". ``` -------------------------------- ### Basic POML Usage with AgentOps Tracing Source: https://microsoft.github.io/poml/stable/python/integration/agentops Initialize AgentOps and enable POML tracing to monitor LLM interactions. This example demonstrates setting up tracing and making a POML call that will be automatically logged. ```python import os import poml import agentops from openai import OpenAI # Initialize AgentOps. Trace is automatically started. agentops.init() # Enable POML tracing with AgentOps poml.set_trace("agentops", trace_dir="pomlruns") # Use POML as usual client = OpenAI() messages = poml.poml( "explain_code.poml", context={"code_path": "sample.py"}, format="openai_chat" ) response = client.chat.completions.create( model="gpt-5", **messages ) # Trace ends automatically at the end of the script. ``` -------------------------------- ### Complete MCP Integration with POML Setup Source: https://microsoft.github.io/poml/stable/python/integration/mcp This script demonstrates a complete integration of MCP with POML. It initializes the context, connects to the MCP server, and runs the conversation loop. ```python import json import asyncio from openai import OpenAI import poml from mcp import ClientSession from mcp.client.sse import sse_client async def main(): # Initialize context for POML context = { "system": "You are a helpful DM assistant. Use the dice-rolling tool when needed.", "input": "Roll 2d4+1", "tools": [], "interactions": [] } # Connect to MCP server (using public demo server) server_url = "https://dmcp-server.deno.dev/sse" async with sse_client(server_url) as (read, write): async with ClientSession(read, write) as mcp_session: await mcp_session.initialize() result = await run_mcp_conversation(mcp_session, context) print(f"Conversation completed: {result}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Reader Interface Definition Source: https://microsoft.github.io/poml/stable/deep-dive/proposals/poml_extended Defines the contract for segment readers, including methods for reading, getting hover tokens, and getting completions. ```typescript interface Reader { read(segment: Segment, context: PomlContext?): React.ReactElement; getHoverToken(segment: Segment, offset: number): PomlToken | undefined; getCompletions(offset: number): PomlToken[]; } ``` -------------------------------- ### Initialize Prompt and Add Text Source: https://microsoft.github.io/poml/stable/python/reference/prompt Demonstrates initializing a `Prompt` object and adding text content within a tag. Ensure a tag is open before adding text; otherwise, a `ValueError` will occur. ```python import xml.etree.ElementTree as ET import json import base64 class _TagLib: pass class Prompt(_TagLib): """ Builds an XML structure using ElementTree, supporting context-managed tags. """ def __init__(self): self.root_elements: list[ET.Element] = [] self.current_parent_stack: list[ET.Element] = [] # Stack of current ET.Element parents def _prepare_attrs(self, **attrs) -> dict[str, str]: """Converts attribute values to strings suitable for ElementTree.""" prepared = {} for k, v in attrs.items(): if v is None: # Skip None attributes continue key_str = str(k) # Keys are typically strings if isinstance(v, bool): val_str = str(v).lower() # XML often uses "true"/"false" elif isinstance(v, bytes): b64 = base64.b64encode(v).decode() if key_str == "buffer": prepared["base64"] = b64 continue else: val_str = base64.b64encode(v).decode("ascii") elif isinstance(v, (int, float, str)): val_str = str(v) else: val_str = json.dumps(v) # Fallback for complex types, convert to JSON string prepared[key_str] = val_str return prepared def text(self, content: str): """Adds text content to the currently open XML element.""" if not self.current_parent_stack: raise ValueError("Cannot add text: No tag is currently open. Use a 'with' block for a tag.") current_el = self.current_parent_stack[-1] # ElementTree handles XML escaping for text content automatically content_str = str(content) # Append text correctly for mixed content (text between child elements) if len(current_el) > 0: # If current element has children last_child = current_el[-1] if last_child.tail is None: last_child.tail = content_str else: last_child.tail += content_str else: # No children yet in the current element, add to its primary text if current_el.text is None: current_el.text = content_str else: current_el.text += content_str def _generate_xml_string(self, pretty: bool) -> str: """ Serializes the built XML structure to a string. Can optionally pretty-print the output. """ if self.current_parent_stack: # This warning is for cases where rendering/dumping happens with unclosed tags. print( f"Warning: Generating XML with open tags: {[el.tag for el in self.current_parent_stack]}. " "Ensure all 'with' blocks for tags are properly exited before finalizing XML." ) xml_strings = [] for root_el in self.root_elements: if pretty: # ET.indent modifies the element in-place (Python 3.9+) ET.indent(root_el, space=" ", level=0) xml_strings.append(ET.tostring(root_el, encoding="unicode", method="xml")) else: # Serialize compactly without extra whitespace xml_strings.append(ET.tostring(root_el, encoding="unicode", method="xml")) # Join the string representations of each root-level element. # If pretty printing and multiple roots, join with newlines for readability. # Otherwise, join directly to form a contiguous XML stream. joiner = "\n" if pretty and len(xml_strings) > 0 else "" # Add newline between pretty roots return joiner.join(xml_strings) def render(self, chat: bool = True, context=None, stylesheet=None) -> list | dict | str: """ Renders the final XML. Raises error if tags are still open. """ if self.current_parent_stack: raise ValueError( f"Cannot render: Open tags remaining: {[el.tag for el in self.current_parent_stack]}. " "Ensure all 'with' blocks for tags are properly exited." ) # poml likely expects a compact, single XML string. final_xml = self._generate_xml_string(pretty=False) ``` -------------------------------- ### Basic StepwiseInstructions Usage Source: https://microsoft.github.io/poml/stable/language/components Demonstrates the basic structure of the StepwiseInstructions component using an unordered list to display a sequence of actions. ```html Interpret and rewrite user's query. Think of a plan to solve the query. Generate a response based on the plan. ``` -------------------------------- ### initializeOptions Source: https://microsoft.github.io/poml/stable/typescript/reference/writer Initializes the Markdown options, applying defaults if necessary. ```APIDOC ## initializeOptions() ### Description Initializes the Markdown options. ### Parameters - **options?** (MarkdownOptions) - Optional initial options. ### Returns MarkdownOptions ``` -------------------------------- ### __enter__ Source: https://microsoft.github.io/poml/stable/python/reference/prompt Enters a context for building a prompt. The Prompt instance can be reused across multiple `with` blocks. On each entry, the stack of currently open elements is reset while preserving any previously created root elements. ```APIDOC ## __enter__() ### Description Enter a context for building a prompt. The Prompt instance can be reused across multiple `with` blocks. On each entry we simply reset the stack of currently open elements while preserving any previously created root elements so that additional tags can be appended in subsequent sessions. ### Method ```python def __enter__(self): # Reset the stack of open elements for this new session but leave any # existing root elements intact so the prompt can be extended across # multiple ``with`` blocks. self.current_parent_stack = [] return self ``` ``` -------------------------------- ### Example Component Source: https://microsoft.github.io/poml/stable/typescript/reference/components Provides context and demonstrates expected inputs and outputs. Can be used to clarify structure, tone, or detail. Supports 'input' and 'output' child elements, optionally with captions. ```html What is the capital of France? Paris ``` ```html Summarize the following passage in a single sentence. The sun provides energy for life on Earth through processes like photosynthesis. The sun is essential for energy and life processes on Earth. ``` -------------------------------- ### Enable POML Tracing with Weave Source: https://microsoft.github.io/poml/stable/python/integration/weave Initialize a Weave project and enable POML tracing. This setup allows POML to automatically log calls and publish prompts as Weave objects. ```python import poml import weave from openai import OpenAI # Initialize Weave project weave.init("my_poml_project") # Enable POML tracing with Weave poml.set_trace("weave", trace_dir="pomlruns") # Use POML as usual client = OpenAI() messages = poml.poml( "explain_code.poml", context={"code_path": "sample.py"}, format="openai_chat" ) response = client.chat.completions.create( model="gpt-5", **messages ) ``` -------------------------------- ### Markdown with Embedded POML Elements Source: https://microsoft.github.io/poml/stable/deep-dive/proposals/poml_extended Example of a markdown document with embedded POML elements like and . Use this format for primarily text-based documents with occasional POML components. ```markdown # My Analysis Document This is a regular markdown document that explains the task. Analyze the following data and provide insights. Here are some key points to consider: - Data quality - Statistical significance - Business impact Sample data point 1 Analysis result 1 ## Conclusion The analysis shows... ``` -------------------------------- ### serializeLanguage Accessor Source: https://microsoft.github.io/poml/stable/typescript/reference/writer Gets the serialization language for the JsonWriter. ```APIDOC ## serializeLanguage ### Description Gets the serialization language for the JsonWriter. ### Get Signature - **get serializeLanguage**(): `string` ### Returns - `string` - The name of the serialization language. ``` -------------------------------- ### PomlError.startIndex Source: https://microsoft.github.io/poml/stable/typescript/reference/base Optional property indicating the starting index related to an error. ```APIDOC ## startIndex ### Description An optional property that may indicate a starting index relevant to the error context. ### Property Type `number` (optional) ```