### Define Main Prompt Template Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Example of a prompt file using the mustache partial syntax. ```mustache --- name: main --- This is the main prompt. Here is the partial: {{> my_partial }} ``` -------------------------------- ### Run Dart Example Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Execute the example application provided within the Dart project. This is useful for demonstrating package functionality. ```bash dart run example/main.dart ``` -------------------------------- ### Load and Render Prompts from File in Dart Source: https://context7.com/csells/dotprompt_dart/llms.txt This example demonstrates loading a `.prompt` file using `DotPrompt.stream` and accessing its front-matter configuration. It shows how to render the prompt with both minimal and full input, including optional fields and custom system prompts. ```yaml # File: prompts/assistant.prompt --- name: ai-assistant variant: production model: gemini-2.0-pro tools: - webSearch - codeExecution - fileManager config: temperature: 0.7 maxOutputTokens: 4096 topK: 40 topP: 0.95 stopSequences: - "END" - "STOP" input: schema: properties: user_message: string, The user's input message context?: string, Optional conversation context system_prompt?: string, Custom system instructions output_format(enum): [text, json, markdown], Desired output format max_length?: integer, Maximum response length include_sources?: boolean, Whether to cite sources default: output_format: text include_sources: false output: schema: type: object properties: response: type: string description: The assistant's response sources: type: array items: type: object properties: title: type: string url: type: string required: [response] format: json metadata: author: AI Team version: 2.1.0 lastUpdated: 2024-01-15 tags: - production - general-purpose mycompany.department: engineering mycompany.costCenter: AI-001 --- {{#system_prompt}} {{system_prompt}} {{/system_prompt}} {{^system_prompt}} You are a helpful AI assistant. Respond in {{output_format}} format. {{/system_prompt}} {{#context}} Previous context: {{context}} {{/context}} User: {{user_message}} {{#include_sources}} Please include sources for any factual claims. {{/include_sources}} ``` ```dart import 'dart:io'; import 'package:dotprompt_dart/dotprompt_dart.dart'; void main() async { final prompt = await DotPrompt.stream( File('prompts/assistant.prompt').openRead(), name: 'prompts/assistant.prompt', ); // Access all configuration for model execution final fm = prompt.frontMatter; print('Using model: ${fm.model}'); print('Tools available: ${fm.tools}'); print('Config: ${fm.config}'); // Render with minimal input (uses defaults) final basicResult = prompt.render({ 'user_message': 'What is machine learning?', }); // Render with full input final fullResult = prompt.render({ 'user_message': 'Explain neural networks', 'context': 'We discussed supervised learning earlier.', 'system_prompt': 'You are an ML expert. Be concise.', 'output_format': 'markdown', 'include_sources': true, }); print('Rendered prompt:\n$fullResult'); // Use this with your LLM execution library // Example with dartantic_ai: // final response = await agent.run(fullResult, config: fm.config); } ``` -------------------------------- ### Define a .prompt file structure Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Create a prompt file with YAML front-matter defining input/output schemas and model configuration. ```yaml --- name: greet model: gemini-2.0-pro input: schema: properties: name: string, The name of the person to greet output: schema: type: object properties: greeting: type: string description: The generated greeting required: [greeting] myext.description: A simple greeting prompt myext.temperature: 0.7 --- Hello {{name}}! How are you today? ``` -------------------------------- ### Load and Render Prompt from File and String Source: https://context7.com/csells/dotprompt_dart/llms.txt Demonstrates loading a prompt from a file using a stream and from a string directly. Accesses front matter metadata and renders the template with input data. Recommended for web compatibility. ```dart import 'dart:io'; import 'package:dotprompt_dart/dotprompt_dart.dart'; void main() async { // Load prompt from a file using stream (recommended for web compatibility) const filename = 'prompts/greet.prompt'; final prompt = await DotPrompt.stream( File(filename).openRead(), name: filename, ); // Access front matter metadata print('Name: ${prompt.frontMatter.name}'); // greet print('Model: ${prompt.frontMatter.model}'); // gemini-2.0-pro print('Input schema: ${prompt.frontMatter.input.schema}'); print('Output schema: ${prompt.frontMatter.output.schema}'); // Render the template with input data final result = prompt.render({'name': 'Chris'}); print(result); // Hello Chris! How are you today? // Alternative: Load from string directly final promptString = ''' --- name: summarize model: gpt-4 input: schema: properties: text: string, The text to summarize --- Please summarize the following text: {{text}} '''; final summaryPrompt = DotPrompt(promptString); final output = summaryPrompt.render({'text': 'A long article about AI...'}); print(output); } ``` -------------------------------- ### Migrate DotPrompt loading from 0.2.0 to 0.3.0 Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Update file loading logic to use stream-based constructors for improved platform compatibility. ```dart // Old code (0.2.0) const filename = 'example/prompts/greet.prompt'; final prompt = await DotPrompt.file(filename); // New code (0.3.0+) const filename = 'example/prompts/greet.prompt'; final prompt = await DotPrompt.stream(File(filename).openRead(), name: filename); ``` -------------------------------- ### Configuring Input and Output Schemas Source: https://context7.com/csells/dotprompt_dart/llms.txt Shows how to define input and output schemas using both the simplified PicoSchema syntax and standard JSON Schema, including automatic validation during rendering. ```dart import 'package:dotprompt_dart/dotprompt_dart.dart'; void main() { // Using PicoSchema (simplified syntax) final picoSchemaPrompt = DotPrompt(''' --- name: user-form input: schema: properties: name: string, User's full name age?: integer, Age in years (optional) email: string, Contact email role(enum): [admin, user, guest], User role tags(array): string, List of tags preferences(object): theme: [light, dark], UI theme preference notifications: boolean (*): any default: role: user preferences: theme: light notifications: true output: schema: properties: success: boolean userId?: string format: json --- Create user: {{name}} '''); final input = picoSchemaPrompt.frontMatter.input; print('Input schema type: ${input.schema?.runtimeType}'); // JsonSchema print('Defaults: ${input.defaults}'); final output = picoSchemaPrompt.frontMatter.output; print('Output format: ${output.format}'); // json print('Output schema: ${output.schema?.schemaMap}'); // Using standard JSON Schema final jsonSchemaPrompt = DotPrompt(''' --- name: api-call input: schema: type: object properties: endpoint: type: string description: API endpoint URL method: type: string enum: [GET, POST, PUT, DELETE] body: type: ["object", "null"] required: [endpoint, method] --- Call {{method}} {{endpoint}} '''); // Schema validation happens automatically on render try { jsonSchemaPrompt.render({ 'endpoint': '/api/users', 'method': 'GET', }); } on ValidationException catch (e) { print('Validation error: $e'); } } ``` -------------------------------- ### Load and render prompts in Dart Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Demonstrates loading prompts from files or strings, rendering templates, and accessing front-matter metadata. ```dart import 'package:dotprompt_dart/dotprompt_dart.dart'; import 'dart:io'; void main() async { // Load from file (0.3.0+) final greet = await DotPrompt.stream(File('prompts/greet.prompt').openRead(), name: 'prompts/greet.prompt'); // Or load from string final promptString = '...'; final greetFromString = DotPrompt(promptString); // Render the template final output = greet.render({'name': 'Chris'}); print(output); // Hello Chris! How are you today? // Access front-matter metadata print(greet.frontMatter.name); // greet print(greet.frontMatter.model); // gemini-2.0-pro // Use this info to feed your prompt execution library of choice ... } ``` -------------------------------- ### Load and render a prompt using DotPrompt.stream Source: https://github.com/csells/dotprompt_dart/blob/main/PRD.md Use DotPrompt.stream to load a prompt from a file stream, resolve partials, and render it with input data. This method is recommended for web and WASM compatibility as of version 0.3.0. ```dart final greet = await DotPrompt.stream( File('prompts/greet.prompt').openRead(), name: 'prompts/greet.prompt', partialResolver: PathPartialResolver([Directory('prompts/partials')]), // optional, for partials support ); final meta = greet.frontMatter; // the model info, settings, etc. final prompt = greet.render({'name': 'Chris'}); // validates input and expands the prompt string // TODO: use something like dartantic_ai to create an Agent and run the prompt ``` -------------------------------- ### Web-Compatible Prompt Loading with Stream Source: https://context7.com/csells/dotprompt_dart/llms.txt Utilizes `DotPrompt.stream` for loading prompts from byte streams, ensuring compatibility with web and WASM environments. Supports optional defaults and custom partial resolvers. ```dart import 'dart:io'; import 'package:dotprompt_dart/dotprompt_dart.dart'; import 'package:dotprompt_dart/src/path_partial_resolver.dart'; void main() async { // Basic stream loading final prompt = await DotPrompt.stream( File('prompts/chat.prompt').openRead(), name: 'prompts/chat.prompt', ); // With defaults and partial resolver final advancedPrompt = await DotPrompt.stream( File('prompts/assistant.prompt').openRead(), name: 'prompts/assistant.prompt', defaults: { 'language': 'English', 'tone': 'professional', }, partialResolver: PathPartialResolver([ Directory('prompts/partials'), ]), ); // Web-compatible: Load from HTTP response // final response = await http.get(Uri.parse('https://example.com/prompt.txt')); // final webPrompt = await DotPrompt.stream( // Stream.value(response.bodyBytes), // name: 'remote-prompt', // ); } ``` -------------------------------- ### Template Rendering with Input Validation Source: https://context7.com/csells/dotprompt_dart/llms.txt Demonstrates rendering a prompt template with provided input data, including merging defaults and validating against an input schema. Catches `ValidationException` for invalid inputs. ```dart import 'package:dotprompt_dart/dotprompt_dart.dart'; void main() { final promptContent = ''' --- name: greeting input: schema: properties: name: string, The user's name greeting?: string, Optional custom greeting default: greeting: Hello --- {{greeting}}, {{name}}! Welcome to our service. '''; final prompt = DotPrompt(promptContent); // Basic rendering with required field only (uses default greeting) final result1 = prompt.render({'name': 'Alice'}); print(result1); // Hello, Alice! Welcome to our service. // Override the default value final result2 = prompt.render({ 'name': 'Bob', 'greeting': 'Hi there', }); print(result2); // Hi there, Bob! Welcome to our service. // Validation error handling try { prompt.render({}); // Missing required 'name' field } on ValidationException catch (e) { print('Validation failed: ${e.message}'); print('Errors: ${e.errors}'); } } ``` -------------------------------- ### Accessing Prompt Metadata with DotPromptFrontMatter Source: https://context7.com/csells/dotprompt_dart/llms.txt Demonstrates how to parse a prompt string and access various front-matter fields, including standard properties, configuration, metadata, and custom extension fields. ```dart import 'package:dotprompt_dart/dotprompt_dart.dart'; void main() { final promptContent = ''' --- name: analyzer variant: v2 model: gemini-2.0-pro tools: - webSearch - calculator config: temperature: 0.7 maxOutputTokens: 2048 topP: 0.9 input: schema: properties: query: string, The analysis query output: schema: type: object properties: analysis: type: string confidence: type: number required: [analysis] format: json metadata: author: Team AI version: 1.0 myext.customField: custom value myext.nested: key: value --- Analyze: {{query}} '''; final prompt = DotPrompt(promptContent); final fm = prompt.frontMatter; // Access standard fields print('Name: ${fm.name}'); // analyzer print('Variant: ${fm.variant}'); // v2 print('Model: ${fm.model}'); // gemini-2.0-pro print('Tools: ${fm.tools}'); // [webSearch, calculator] // Access config settings print('Temperature: ${fm.config['temperature']}'); // 0.7 print('Max tokens: ${fm.config['maxOutputTokens']}'); // 2048 // Access input/output configuration print('Input schema: ${fm.input.schema}'); print('Input defaults: ${fm.input.defaults}'); print('Output format: ${fm.output.format}'); // json print('Output schema: ${fm.output.schema}'); // Access metadata print('Author: ${fm.metadata['author']}'); // Team AI // Access namespaced extension fields print('Custom: ${fm.ext['myext']['customField']}'); // custom value print('Nested: ${fm.ext['myext']['nested']['key']}'); // value // Index operator access print('Via index: ${fm['name']}'); // analyzer } ``` -------------------------------- ### Instantiate DotPrompt from String Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Create a DotPrompt instance by parsing a string containing YAML front-matter and a Handlebars template. Use this for in-memory prompt definitions. ```dart final prompt = DotPrompt(""" --- name: example --- Hello {{name}}! """); ``` -------------------------------- ### Load DotPrompt from Stream Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Load a DotPrompt instance from a stream of bytes, suitable for web/WASM compatibility. Provide a name for the prompt, and optionally default values. ```dart final prompt = await DotPrompt.stream(stream, name: 'my_prompt.prompt', defaults: {'name': 'World'}); ``` -------------------------------- ### Render Templates with Validation Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Demonstrates how DotPrompt handles input, defaults, and validation exceptions. ```dart final prompt = DotPrompt(promptString); // Uses default greeting "Hello" prompt.render({'name': 'World'}); // => "Hello World!" // Overrides default greeting prompt.render({'name': 'World', 'greeting': 'Hi'}); // => "Hi World!" // Throws ValidationException - missing required 'name' prompt.render({'greeting': 'Hi'}); ``` -------------------------------- ### Publish Dart Package to pub.dev Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Publish the Dart package to the official pub.dev repository. Ensure the package is ready and meets all requirements before publishing. ```bash dart pub publish ``` -------------------------------- ### View Partial Resolution Output Source: https://github.com/csells/dotprompt_dart/blob/main/README.md The expected output after rendering a template with resolved partials. ```txt This is the main prompt. Here is the partial: Here is the content from the partial file! ``` -------------------------------- ### Define Partial Template Source: https://github.com/csells/dotprompt_dart/blob/main/README.md A reusable snippet file for use within main prompts. ```mustache This is the content from the partial file! ``` -------------------------------- ### Define Schema with Pico Schema Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Use YAML-friendly syntax for readable schema definitions that automatically convert to JSON Schema. ```yaml input: schema: properties: name: string, The name of the user age?: integer, The age in years # Optional field with ? settings(object): # Type annotation with () theme: [light, dark], Theme preference # Enum using [] notifications: boolean tags(array): string, List of user tags # Array type (*): any # Wildcard for additional properties ``` -------------------------------- ### Parse YAML Front-Matter Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Parse YAML front-matter from a .prompt file, which can include model configuration, input/output schemas, and custom extensions. ```dart final frontMatter = DotPromptFrontMatter.parse(yamlContent); ``` -------------------------------- ### Add dotprompt_dart dependency Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Include the package in your project's pubspec.yaml file. ```yaml dependencies: dotprompt_dart: ^VERSION ``` -------------------------------- ### Use File Stream for DotPrompt Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Create a stream from a file's content to load into DotPrompt, ensuring web/WASM compatibility. Replaces the older DotPrompt.file(filename) method. ```dart final fileStream = File(filename).openRead(); final prompt = await DotPrompt.stream(fileStream, name: filename); ``` -------------------------------- ### Run Tests with Verbose Output in Dart Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Execute tests and display detailed output for each test case. Helpful for diagnosing test failures. ```bash dart test --reporter=expanded ``` -------------------------------- ### Implement PathPartialResolver Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Use PathPartialResolver to load partials from the filesystem in Dart applications. ```dart import 'dart:io'; import 'package:dotprompt_dart/dotprompt_dart.dart'; import 'package:dotprompt_dart/src/path_partial_resolver.dart'; void main() async { final mainPromptContent = await File('prompts/main.prompt').readAsString(); // Create a resolver that looks in the 'prompts/partials' directory. final resolver = PathPartialResolver([Directory('prompts/partials')]); final prompt = DotPrompt( mainPromptContent, partialResolver: resolver, ); final output = prompt.render({}); print(output); // This is the main prompt. // Here is the partial: This is the content from the partial file! } ``` -------------------------------- ### Configure Input Validation and Defaults Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Define required fields and default values that are merged with input during template rendering. ```yaml input: schema: type: object properties: name: type: string greeting: type: ["string", "null"] # Optional field that can be null age: type: integer minimum: 0 required: [name] # Only name is required default: greeting: "Hello" # Used when greeting is not provided ``` -------------------------------- ### PicoSchema YAML to JSON Schema Conversion Source: https://context7.com/csells/dotprompt_dart/llms.txt Demonstrates how PicoSchema converts a simplified YAML syntax into a standard JSON Schema. Supports optional fields, type annotations, enums, arrays, wildcards, and descriptions. ```dart import 'package:dotprompt_dart/dotprompt_dart.dart'; void main() { // PicoSchema features demonstration final prompt = DotPrompt(''' --- name: pico-demo input: schema: properties: # Simple type with description name: string, The user name # Optional field (marked with ?) nickname?: string, Optional nickname # Enum using bracket syntax status: [active, inactive, pending], Account status # Enum with (enum) annotation priority(enum): [low, medium, high], Task priority # Array of strings tags(array): string, User tags # Array of objects addresses(array): street: string city: string zip?: string # Nested object with (object) annotation settings(object, User preferences): theme: [light, dark] language: string # Wildcard for additional properties (*): any --- User: {{name}} '''); // The PicoSchema is automatically converted to JSON Schema final schema = prompt.frontMatter.input.schema; print('JSON Schema output:'); print(schema?.schemaMap); // Render with all field types final result = prompt.render({ 'name': 'John Doe', 'nickname': 'Johnny', 'status': 'active', 'priority': 'high', 'tags': ['developer', 'admin'], 'addresses': [ {'street': '123 Main St', 'city': 'NYC', 'zip': '10001'}, ], 'settings': { 'theme': 'dark', 'language': 'en', }, 'customField': 'extra data', // Allowed by (*): any }); print(result); } ``` -------------------------------- ### PathPartialResolver for Template Partials Source: https://context7.com/csells/dotprompt_dart/llms.txt Enables reusable template snippets (partials) by searching specified directories. Partials are referenced with `{{> partialName }}` and must be named with an underscore prefix. ```dart import 'dart:io'; import 'package:dotprompt_dart/dotprompt_dart.dart'; import 'package:dotprompt_dart/src/path_partial_resolver.dart'; // File: prompts/partials/_header.prompt // --- // name: header-partial // --- // === System Instructions === // You are a helpful AI assistant. // File: prompts/partials/_footer.mustache // === End of Instructions === // File: prompts/main.prompt // --- // name: main-prompt // model: gpt-4 // --- // {{> header }} // // User query: {{query}} // // {{> footer }} void main() async { // Create resolver with search directories final resolver = PathPartialResolver([ Directory('prompts/partials'), Directory('prompts/shared'), // Multiple directories supported ]); // Load prompt with partial resolver final prompt = await DotPrompt.stream( File('prompts/main.prompt').openRead(), name: 'prompts/main.prompt', partialResolver: resolver, ); // Partials are automatically resolved during rendering final result = prompt.render({'query': 'What is the weather?'}); print(result); // Output: // === System Instructions === // You are a helpful AI assistant. // // User query: What is the weather? // // === End of Instructions === // Alternative: Load from string with partials final mainContent = await File('prompts/main.prompt').readAsString(); final promptFromString = DotPrompt( mainContent, partialResolver: resolver, ); print(promptFromString.render({'query': 'Hello!'})); } ``` -------------------------------- ### Run All Tests in Dart Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Execute all tests within the Dart project. Ensure tests are silent on success and report failures via expect(). ```bash dart test ``` -------------------------------- ### Define Schema with JSON Schema Source: https://github.com/csells/dotprompt_dart/blob/main/README.md Use standard JSON Schema syntax by including a top-level type field to bypass Pico Schema parsing. ```yaml input: schema: type: object properties: name: type: string description: The name of the user age: type: [integer, "null"] # Optional field using union type settings: type: object properties: theme: type: string enum: [light, dark] notifications: type: boolean tags: type: array items: type: string additionalProperties: true # Equivalent to (*): any ``` -------------------------------- ### Format Dart Code Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Automatically format the Dart codebase according to standard style guidelines. Ensures consistent code style across the project. ```bash dart format . ``` -------------------------------- ### Run Single Test File in Dart Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Execute a specific test file. Useful for targeted debugging and development. ```bash dart test test/pico_schema_test.dart ``` -------------------------------- ### Dry Run Dart Package Publish Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Check the Dart package for publish readiness without actually publishing to pub.dev. This helps catch potential issues before a real release. ```bash dart pub publish --dry-run ``` -------------------------------- ### Render and Validate DotPrompt Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Render a DotPrompt template with provided input data, validating the input against the schema. Merges default values before validation. ```dart final rendered = await prompt.render({'name': 'Claude'}); ``` -------------------------------- ### Create JsonSchema from PicoSchema Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Generate a JsonSchema object from Pico Schema definitions, including support for optional fields, type annotations, enums, wildcards, and inline descriptions. ```dart final jsonSchema = InputOutputConfig.createSchema(picoSchemaDefinition); ``` -------------------------------- ### Analyze Dart Code Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Perform static analysis on the Dart codebase to identify potential issues and enforce code quality standards. ```bash dart analyze ``` -------------------------------- ### Detect PicoSchema Schema Type Source: https://github.com/csells/dotprompt_dart/blob/main/CLAUDE.md Determine if a schema is in Pico Schema or JSON Schema format. The presence of a top-level 'type' property indicates JSON Schema mode. ```dart final type = picoSchema.schemaType(); ``` -------------------------------- ### Handle ValidationException in Dart Source: https://context7.com/csells/dotprompt_dart/llms.txt This snippet shows how to catch `ValidationException` when rendering a prompt with invalid input. It demonstrates handling multiple validation errors for schema violations like incorrect patterns, out-of-range numbers, and invalid enum values, as well as missing required fields. ```dart import 'package:dotprompt_dart/dotprompt_dart.dart'; void main() { final prompt = DotPrompt(''' --- name: strict-input input: schema: type: object properties: email: type: string pattern: "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+" age: type: integer minimum: 18 maximum: 120 role: type: string enum: [admin, user, guest] required: [email, age, role] --- User {{email}} with role {{role}} '''); // Valid input try { final result = prompt.render({ 'email': 'user@example.com', 'age': 25, 'role': 'user', }); print('Success: $result'); } on ValidationException catch (e) { print('Unexpected error: $e'); } // Invalid input - multiple errors try { prompt.render({ 'email': 'invalid-email', // Missing @ 'age': 15, // Below minimum 'role': 'superadmin', // Not in enum }); } on ValidationException catch (e) { print('Validation failed: ${e.message}'); for (final error in e.errors) { print(' - $error'); } // Output: // Validation failed: Input data failed schema validation // - pattern: does not match pattern... // - minimum: 15 is less than minimum 18 // - enum: superadmin is not one of [admin, user, guest] } // Missing required fields try { prompt.render({'email': 'test@test.com'}); // Missing age and role } on ValidationException catch (e) { print('Missing fields: ${e.errors}'); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.