Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/prompt-template/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/.gitattributes export-ignore
/.gitignore export-ignore
/phpstan.dist.neon export-ignore
/phpunit.xml.dist export-ignore
/tests export-ignore
/AGENTS.md export-ignore
/CLAUDE.md export-ignore
96 changes: 96 additions & 0 deletions src/prompt-template/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# AGENTS.md

AI agent guidance for the Prompt Template component.

## Component Overview

Extensible prompt templating system with pluggable rendering strategies. Provides simple variable substitution by default and optional Symfony Expression Language integration for advanced use cases.

## Architecture

### Core Classes
- **PromptTemplate**: Main implementation with renderer injection
- **PromptTemplateInterface**: Core contract for template implementations
- **RendererInterface**: Strategy interface for rendering implementations
- **StringRenderer**: Default renderer using simple {variable} replacement (zero dependencies)
- **ExpressionRenderer**: Optional renderer using Symfony Expression Language for advanced expressions

### Key Features
- **Zero Core Dependencies**: Only requires PHP 8.2+
- **Strategy Pattern**: Pluggable renderer system for extensibility
- **Simple by Default**: Basic {variable} replacement out of the box
- **Advanced Optional**: Expression Language for power users
- **Immutable**: readonly classes ensure thread-safety

### Key Directories
- `src/`: Source code with main classes
- `src/Renderer/`: Renderer implementations
- `src/Exception/`: Component-specific exceptions (factory pattern)
- `tests/`: Comprehensive test suite mirroring src structure
- `tests/Renderer/`: Tests for each renderer

## Essential Commands

### Testing
```bash
vendor/bin/phpunit
vendor/bin/phpunit tests/PromptTemplateTest.php
vendor/bin/phpunit --coverage-html coverage
```

### Code Quality
```bash
vendor/bin/phpstan analyse
cd ../../.. && vendor/bin/php-cs-fixer fix src/prompt-template/
```

### Dependencies
```bash
composer install
composer require symfony/expression-language # For ExpressionRenderer
```

## Usage Patterns

### Default Renderer
```php
$template = new PromptTemplate('Hello {name}!');
echo $template->format(['name' => 'World']);
```

### Expression Renderer
```php
$renderer = new ExpressionRenderer();
$template = new PromptTemplate('Total: {price * quantity}', $renderer);
echo $template->format(['price' => 10, 'quantity' => 5]);
```

### Custom Renderer
```php
class MyRenderer implements RendererInterface {
public function render(string $template, array $values): string {
// Custom implementation
}
}

$template = new PromptTemplate($template, new MyRenderer());
```

## Testing Patterns

- PHPUnit 11.5+ with strict configuration
- Test fixtures follow monorepo patterns
- Each renderer has dedicated test class
- Integration tests verify renderer injection
- Component-specific exception testing using factory pattern
- Prefer `self::assert*` over `$this->assert*`

## Development Notes

- Add `@author` tags to new classes
- Use component-specific exceptions from `src/Exception/` with factory pattern
- Follow Symfony coding standards with `@Symfony` PHP CS Fixer rules
- Component is experimental (BC breaks possible)
- StringRenderer must remain dependency-free
- ExpressionRenderer requires symfony/expression-language
- All classes use readonly for immutability
12 changes: 12 additions & 0 deletions src/prompt-template/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# CHANGELOG

## 0.1.0

**Initial release**

- Introduced `PromptTemplate` for prompt template management
- Added `StringRenderer` for simple {variable} replacement (zero dependencies)
- Added `ExpressionRenderer` for Symfony Expression Language integration
- Implemented extensible renderer strategy pattern via `RendererInterface`
- Added comprehensive exception hierarchy
- Provides static factory methods for convenient template creation
116 changes: 116 additions & 0 deletions src/prompt-template/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this component.

## Component Overview

This is the Prompt Template component of the Symfony AI monorepo - an extensible prompt templating system with pluggable rendering strategies. It provides simple variable substitution by default and optional Symfony Expression Language integration for advanced use cases.

## Architecture

### Core Classes

- **PromptTemplate**: Main implementation with renderer injection
- **PromptTemplateInterface**: Core contract for template implementations
- **RendererInterface**: Strategy interface for rendering implementations
- **StringRenderer**: Default renderer using simple {variable} replacement (zero dependencies)
- **ExpressionRenderer**: Optional renderer using Symfony Expression Language for advanced expressions

### Key Features

- **Zero Core Dependencies**: Only requires PHP 8.2+
- **Strategy Pattern**: Pluggable renderer system for extensibility
- **Simple by Default**: Basic {variable} replacement out of the box
- **Advanced Optional**: Expression Language for power users
- **Immutable**: readonly classes ensure thread-safety

### Key Directories

- `src/`: Source code with main classes
- `src/Renderer/`: Renderer implementations
- `src/Exception/`: Component-specific exceptions
- `tests/`: Comprehensive test suite mirroring src structure
- `tests/Renderer/`: Tests for each renderer

## Development Commands

### Testing

```bash
# Run all tests
vendor/bin/phpunit

# Run specific test
vendor/bin/phpunit tests/PromptTemplateTest.php

# Run with coverage
vendor/bin/phpunit --coverage-html coverage
```

### Code Quality

```bash
# Run PHPStan static analysis
vendor/bin/phpstan analyse

# Fix code style (run from project root)
cd ../../.. && vendor/bin/php-cs-fixer fix src/prompt-template/
```

### Installing Dependencies

```bash
# Install dependencies
composer install

# Install with expression language
composer require symfony/expression-language
```

## Testing Architecture

- Uses PHPUnit 11.5+ with strict configuration
- Test fixtures follow monorepo patterns
- Each renderer has dedicated test class
- Integration tests verify renderer injection
- Component-specific exception testing
- Prefer `self::assert*` over `$this->assert*`

## Usage Patterns

### Default Renderer

```php
$template = new PromptTemplate('Hello {name}!');
echo $template->format(['name' => 'World']);
```

### Expression Renderer

```php
$renderer = new ExpressionRenderer();
$template = new PromptTemplate('Total: {price * quantity}', $renderer);
echo $template->format(['price' => 10, 'quantity' => 5]);
```

### Custom Renderer

```php
class MyRenderer implements RendererInterface {
public function render(string $template, array $values): string {
// Custom implementation
}
}

$template = new PromptTemplate($template, new MyRenderer());
```

## Development Notes

- All new classes should have `@author` tags
- Use component-specific exceptions from `src/Exception/`
- Follow Symfony coding standards with `@Symfony` PHP CS Fixer rules
- Component is marked as experimental (BC breaks possible)
- StringRenderer must remain dependency-free
- ExpressionRenderer requires symfony/expression-language
- All classes use readonly for immutability
19 changes: 19 additions & 0 deletions src/prompt-template/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2025-present Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
142 changes: 142 additions & 0 deletions src/prompt-template/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# Symfony AI Prompt Template Component

**This Component is [experimental](https://github.com/symfony/ai?tab=readme-ov-file#component-status). Expect breaking changes in minor and patch versions.**

PHP library for prompt template management with extensible rendering strategies.

## Installation

```bash
composer require symfony/ai-prompt-template
```

For advanced expression-based rendering:

```bash
composer require symfony/expression-language
```

## Basic Usage

### Simple Variable Replacement (Default)

```php
use Symfony\AI\PromptTemplate\PromptTemplate;

$template = new PromptTemplate('Hello {name}!');
echo $template->format(['name' => 'World']); // "Hello World!"

// Using static factory
$template = PromptTemplate::fromString(<<<'PROMPT'
You are a helpful assistant.

User: {user}
Query: {query}
PROMPT);

echo $template->format([
'user' => 'Alice',
'query' => 'What is AI?',
]);
```

The default `StringRenderer` performs simple `{variable}` replacement with zero external dependencies.

### Advanced Expression-Based Rendering

Install `symfony/expression-language` to use the `ExpressionRenderer`:

```php
use Symfony\AI\PromptTemplate\PromptTemplate;
use Symfony\AI\PromptTemplate\Renderer\ExpressionRenderer;

$renderer = new ExpressionRenderer();
$template = new PromptTemplate('Total: {price * quantity}', $renderer);
echo $template->format(['price' => 10, 'quantity' => 5]); // "Total: 50"

// Conditional expressions
$template = PromptTemplate::fromStringWithRenderer(
'Status: {age >= 18 ? "adult" : "minor"}',
new ExpressionRenderer()
);
echo $template->format(['age' => 25]); // "Status: adult"

// Object property access
$template = new PromptTemplate('Name: {user.name}', $renderer);
echo $template->format(['user' => $userObject]); // "Name: Alice"
```

### Custom Renderers

Implement `RendererInterface` to create custom rendering strategies:

```php
use Symfony\AI\PromptTemplate\Renderer\RendererInterface;

class MustacheRenderer implements RendererInterface
{
public function render(string $template, array $values): string
{
foreach ($values as $key => $value) {
$template = str_replace('{{'.$key.'}}', (string) $value, $template);
}
return $template;
}
}

$template = new PromptTemplate('Hello {{name}}!', new MustacheRenderer());
echo $template->format(['name' => 'World']); // "Hello World!"
```

## Available Renderers

### StringRenderer (Default)

- Simple `{variable}` placeholder replacement
- Validates variable names and values
- Zero external dependencies
- Supports strings, numbers, and `\Stringable` objects

### ExpressionRenderer (Optional)

Requires `symfony/expression-language`

- Variable access: `{user.name}`
- Math operations: `{price * quantity}`
- Conditionals: `{age > 18 ? "adult" : "minor"}`
- String concatenation: `{firstName ~ " " ~ lastName}`
- Array access: `{items[0]}`
- Custom functions via `ExpressionLanguage`

## API Reference

### PromptTemplate

```php
// Constructor
new PromptTemplate(string $template, ?RendererInterface $renderer = null)

// Methods
$template->format(array $values = []): string
$template->getTemplate(): string
(string) $template // Returns template string

// Static factories
PromptTemplate::fromString(string $template): self
PromptTemplate::fromStringWithRenderer(string $template, RendererInterface $renderer): self
```

### RendererInterface

```php
interface RendererInterface
{
public function render(string $template, array $values): string;
}
```

## Resources

- [Main Repository](https://github.com/symfony/ai)
- [Report Issues](https://github.com/symfony/ai/issues)
- [Submit Pull Requests](https://github.com/symfony/ai/pulls)
Loading
Loading