{"id":21174646,"url":"https://github.com/llm-agents-php/prompt-generator","last_synced_at":"2025-07-09T21:31:01.119Z","repository":{"id":255445748,"uuid":"852343234","full_name":"llm-agents-php/prompt-generator","owner":"llm-agents-php","description":"Prompt generator for LLM agents with interceptors","archived":false,"fork":false,"pushed_at":"2024-09-15T18:48:50.000Z","size":25,"stargazers_count":7,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-06T15:46:39.901Z","etag":null,"topics":["llm-agent","llm-prompting","llm-tools","php"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/llm-agents-php.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-09-04T16:36:53.000Z","updated_at":"2024-12-31T17:55:34.000Z","dependencies_parsed_at":"2024-09-04T18:39:32.787Z","dependency_job_id":"c8946536-0d7f-4939-85d7-09ab0f48a734","html_url":"https://github.com/llm-agents-php/prompt-generator","commit_stats":null,"previous_names":["llm-agents-php/prompt-generator"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/llm-agents-php/prompt-generator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llm-agents-php%2Fprompt-generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llm-agents-php%2Fprompt-generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llm-agents-php%2Fprompt-generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llm-agents-php%2Fprompt-generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/llm-agents-php","download_url":"https://codeload.github.com/llm-agents-php/prompt-generator/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llm-agents-php%2Fprompt-generator/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":264503949,"owners_count":23618762,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["llm-agent","llm-prompting","llm-tools","php"],"created_at":"2024-11-20T16:55:31.977Z","updated_at":"2025-07-09T21:31:00.850Z","avatar_url":"https://github.com/llm-agents-php.png","language":"PHP","funding_links":[],"categories":["LLMs \u0026 AI APIs","Natural Language Processing"],"sub_categories":["Recommended core stack","Utilities \u0026 Tools"],"readme":"# LLM Agents Prompt Generator\n\n[![PHP](https://img.shields.io/packagist/php-v/llm-agents-php/prompt-generator.svg?style=flat-square)](https://packagist.org/packages/llm-agents/prompt-generator)\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/llm-agents/prompt-generator.svg?style=flat-square)](https://packagist.org/packages/llm-agents/prompt-generator)\n[![Total Downloads](https://img.shields.io/packagist/dt/llm-agents/prompt-generator.svg?style=flat-square)](https://packagist.org/packages/llm-agents/prompt-generator)\n\nThis package provides a flexible and extensible system for generating chat prompts with all required system and user\nmessages for LLM agents. It uses an interceptor-based approach to expand generator abilities.\n\n### Installation\n\nYou can install the package via Composer:\n\n```bash\ncomposer require llm-agents/prompt-generator\n```\n\n### Setup in Spiral Framework\n\nTo get the Site Status Checker Agent up and running in your Spiral Framework project, you need to register its\nbootloader.\n\n**Here's how:**\n\n1. Open up your `app/src/Application/Kernel.php` file.\n2. Add the bootloader like this:\n   ```php\n   public function defineBootloaders(): array\n   {\n       return [\n           // ... other bootloaders ...\n           \\LLM\\Agents\\PromptGenerator\\Integration\\Spiral\\PromptGeneratorBootloader::class,\n       ];\n   }\n   ```\n3. Create a bootloader for the prompt generator. Create a file named `PromptGeneratorBootloader.php`\n   in your `app/src/Application/Bootloader` directory:\n\n```php\nnamespace App\\Application\\Bootloader;\n\nuse Spiral\\Boot\\Bootloader\\Bootloader;\n\nuse LLM\\Agents\\PromptGenerator\\Interceptors\\AgentMemoryInjector;\nuse LLM\\Agents\\PromptGenerator\\Interceptors\\InstructionGenerator;\nuse LLM\\Agents\\PromptGenerator\\Interceptors\\LinkedAgentsInjector;\nuse LLM\\Agents\\PromptGenerator\\Interceptors\\UserPromptInjector;\nuse LLM\\Agents\\PromptGenerator\\PromptGeneratorPipeline;\n\nclass PromptGeneratorBootloader extends Bootloader\n{\n    public function defineSingletons(): array\n    {\n        return [\n            PromptGeneratorPipeline::class =\u003e static function (\n                LinkedAgentsInjector $linkedAgentsInjector,\n            ): PromptGeneratorPipeline {\n                $pipeline = new PromptGeneratorPipeline();\n\n                return $pipeline-\u003ewithInterceptor(\n                    new InstructionGenerator(),\n                    new AgentMemoryInjector(),\n                    $linkedAgentsInjector,\n                    new UserPromptInjector(),\n                    // ...\n                );\n            },\n        ];\n    }\n}\n```\n\nAnd that's it! Your Spiral app is now ready to use the agent.\n\n## Usage\n\nHere's an example of how to initialize the prompt generator and generate a prompt:\n\n```php\nuse App\\Domain\\Chat\\PromptGenerator\\SessionContextInjector;\nuse LLM\\Agents\\PromptGenerator\\Interceptors\\AgentMemoryInjector;\nuse LLM\\Agents\\PromptGenerator\\Interceptors\\InstructionGenerator;\nuse LLM\\Agents\\PromptGenerator\\Interceptors\\LinkedAgentsInjector;\nuse LLM\\Agents\\PromptGenerator\\Interceptors\\UserPromptInjector;\nuse LLM\\Agents\\PromptGenerator\\PromptGeneratorPipeline;\n\n$generator = new PromptGeneratorPipeline();\n\n$generator = $generator-\u003ewithInterceptor(\n    new InstructionGenerator(),\n    new AgentMemoryInjector(),\n    new LinkedAgentsInjector($agents, $schemaMapper),\n    new SessionContextInjector(),\n    new UserPromptInjector()\n);\n\n$prompt = $generator-\u003egenerate($agent, $userPrompt, $context, $initialPrompt);\n```\n\n## Interceptors\n\nThe package comes with several built-in interceptors:\n\n### InstructionGenerator\n\nThis interceptor adds the agent's instruction to the prompt. It includes important rules like responding in markdown\nformat and thinking before responding to the user.\n\n### AgentMemoryInjector\n\nThis interceptor adds the agent's memory to the prompt. It includes both static memory (defined when creating the agent)\nand dynamic memory (which can be updated during the conversation).\n\n### LinkedAgentsInjector\n\nThis interceptor adds information about linked agents to the prompt. It provides details about other agents that the\ncurrent agent can call for help, including their keys, descriptions, and output schemas.\n\n### UserPromptInjector\n\nThis interceptor adds the user's input to the prompt as a user message.\n\n## Creating Custom Interceptors\n\nYou can create custom interceptors by implementing the `LLM\\Agents\\PromptGenerator\\PromptInterceptorInterface`:\n\nLet's create a `ContextAwarePromptInjector` that adds relevant context to the prompt based on the current time of day\nand\nuser preferences. This example will demonstrate how to create a more sophisticated interceptor that interacts with\nexternal services and modifies the prompt accordingly.\n\n```php\nnamespace App\\PromptGenerator\\Interceptors;\n\nuse LLM\\Agents\\LLM\\Prompt\\Chat\\MessagePrompt;\nuse LLM\\Agents\\LLM\\Prompt\\Chat\\Prompt;\nuse LLM\\Agents\\LLM\\Prompt\\Chat\\PromptInterface;\nuse LLM\\Agents\\PromptGenerator\\InterceptorHandler;\nuse LLM\\Agents\\PromptGenerator\\PromptGeneratorInput;\nuse LLM\\Agents\\PromptGenerator\\PromptInterceptorInterface;\nuse App\\Services\\UserPreferenceService;\nuse App\\Services\\WeatherService;\n\nclass ContextAwarePromptInjector implements PromptInterceptorInterface\n{\n    public function __construct(\n        private UserPreferenceService $userPreferenceService,\n        private WeatherService $weatherService,\n    ) {}\n\n    public function generate(PromptGeneratorInput $input, InterceptorHandler $next): PromptInterface\n    {\n        $userId = $input-\u003econtext-\u003egetUserId(); // Assuming we have this method in our context\n        $userPreferences = $this-\u003euserPreferenceService-\u003egetPreferences($userId);\n        $currentTime = new \\DateTime();\n        $currentWeather = $this-\u003eweatherService-\u003egetCurrentWeather($userPreferences-\u003egetLocation());\n\n        $contextMessage = $this-\u003egenerateContextMessage($currentTime, $userPreferences, $currentWeather);\n\n        $modifiedPrompt = $input-\u003eprompt;\n        if ($modifiedPrompt instanceof Prompt) {\n            $modifiedPrompt = $modifiedPrompt-\u003ewithAddedMessage(\n                MessagePrompt::system($contextMessage),\n            );\n        }\n\n        return $next($input-\u003ewithPrompt($modifiedPrompt));\n    }\n\n    private function generateContextMessage(\\DateTime $currentTime, $userPreferences, $currentWeather): string\n    {\n        $timeOfDay = $this-\u003egetTimeOfDay($currentTime);\n        $greeting = $this-\u003egetGreeting($timeOfDay);\n\n        return \u003c\u003c\u003cPROMPT\n{$greeting} Here's some context for this conversation:\n- It's currently {$timeOfDay}.\n- The weather is {$currentWeather-\u003egetDescription()} with a temperature of {$currentWeather-\u003egetTemperature()}°C.\n- The user prefers {$userPreferences-\u003egetCommunicationStyle()} communication.\n- The user's interests include: {$this-\u003eformatInterests($userPreferences-\u003egetInterests())}.\n\nPlease take this context into account when generating responses.\nPROMPT;\n    }\n\n    private function getTimeOfDay(\\DateTime $time): string\n    {\n        $hour = (int) $time-\u003eformat('G');\n        return match (true) {\n            $hour \u003e= 5 \u0026\u0026 $hour \u003c 12 =\u003e 'morning',\n            $hour \u003e= 12 \u0026\u0026 $hour \u003c 18 =\u003e 'afternoon',\n            $hour \u003e= 18 \u0026\u0026 $hour \u003c 22 =\u003e 'evening',\n            default =\u003e 'night',\n        };\n    }\n\n    private function getGreeting(string $timeOfDay): string\n    {\n        return match ($timeOfDay) {\n            'morning' =\u003e 'Good morning!',\n            'afternoon' =\u003e 'Good afternoon!',\n            'evening' =\u003e 'Good evening!',\n            'night' =\u003e 'Hello!',\n        };\n    }\n\n    private function formatInterests(array $interests): string\n    {\n        return \\implode(', ', \\array_map(fn($interest) =\u003e \\strtolower($interest), $interests));\n    }\n}\n```\n\nThen, add your custom interceptor to the pipeline:\n\n```php\n$generator = $generator-\u003ewithInterceptor(new ContextAwarePromptInjector(...));\n```\n\nCheck out this UML sequence diagram to see how the prompt generation process works with the interceptors:\n\n```mermaid\nsequenceDiagram\n    participant AE as AgentExecutor\n    participant PGP as PromptGeneratorPipeline\n    participant IG as InstructionGenerator\n    participant AMI as AgentMemoryInjector\n    participant LAI as LinkedAgentsInjector\n    participant UPI as UserPromptInjector\n    participant P as Prompt\n\n    AE-\u003e\u003ePGP: generate(agent, userPrompt, context)\n    activate PGP\n    PGP-\u003e\u003eIG: generate(input, next)\n    activate IG\n    IG-\u003e\u003eP: add system instruction message to prompt\n    P--\u003e\u003eIG: updatedPrompt\n    IG--\u003e\u003ePGP: updatedInput\n    deactivate IG\n\n    PGP-\u003e\u003eAMI: generate(input, next)\n    activate AMI\n    AMI-\u003e\u003eP: add agent memory message to prompt\n    P--\u003e\u003eAMI: updatedPrompt\n    AMI--\u003e\u003ePGP: updatedInput\n    deactivate AMI\n\n    PGP-\u003e\u003eLAI: generate(input, next)\n    activate LAI\n    LAI-\u003e\u003eP: add linked agents info message to prompt\n    P--\u003e\u003eLAI: updatedPrompt\n    LAI--\u003e\u003ePGP: updatedInput\n    deactivate LAI\n\n    PGP-\u003e\u003eUPI: generate(input, next)\n    activate UPI\n    UPI-\u003e\u003eP: add user message to prompt\n    P--\u003e\u003eUPI: updatedPrompt\n    UPI--\u003e\u003ePGP: updatedInput\n    deactivate UPI\n\n    PGP--\u003e\u003eAE: finalGeneratedPrompt\n    deactivate PGP\n```\n\n## Implementing PromptContextInterface\n\nThe `PromptGeneratorInput` includes a `context` property of type `PromptContextInterface`. This interface allows you to\npass custom context data to your interceptors. To use it effectively, you need to create your own implementation of this\ninterface.\n\nHere's an example of how you might implement the `PromptContextInterface`:\n\n```php\nuse LLM\\Agents\\LLM\\PromptContextInterface;\n\nclass ChatContext implements PromptContextInterface\n{\n    public function __construct(\n        private string $userId,\n        private array $sessionData = [],\n    ) {}\n\n    public function getUserId(): string\n    {\n        return $this-\u003euserId;\n    }\n\n    public function getSessionData(): array\n    {\n        return $this-\u003esessionData;\n    }\n\n    // Add any other methods you need for your specific use case\n}\n```\n\nThen, when generating a prompt, you would pass an instance of your custom context:\n\n```php\n$context = new ChatContext($userId, $sessionData);\n$prompt = $generator-\u003egenerate($agent, $userPrompt, $context);\n```\n\nIn your custom interceptors, you can then access this context data:\n\n```php\nclass ContextAwarePromptInjector implements PromptInterceptorInterface\n{\n    public function generate(PromptGeneratorInput $input, InterceptorHandler $next): PromptInterface\n    {\n        $userId = $input-\u003econtext-\u003egetUserId();\n        $sessionData = $input-\u003econtext-\u003egetSessionData();\n\n        // Use this data to customize your prompt\n        // ...\n\n        return $next($input);\n    }\n}\n```\n\nBy implementing your own `PromptContextInterface`, you can pass any necessary data from your application to your\ninterceptors, allowing for highly customized and context-aware prompt generation.\n\n## Want to help out? 🤝\n\nWe love contributions! If you've got ideas to make this agent even cooler, here's how you can chip in:\n\n1. Fork the repo\n2. Make your changes\n3. Create a new Pull Request\n\nJust make sure your code is clean, well-commented, and follows PSR-12 coding standards.\n\n## License 📄\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n---\n\nThat's all, folks! If you've got any questions or run into any trouble, don't hesitate to open an issue.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fllm-agents-php%2Fprompt-generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fllm-agents-php%2Fprompt-generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fllm-agents-php%2Fprompt-generator/lists"}