### Quick Start Example: Initialize and Create Task Source: https://github.com/cognesy/instructor-php/blob/main/packages/auxiliary/notes/TBD.md Demonstrates the initial setup by creating a JSONL file and then adding a new bug task to it. ```bash tbd init --file .beads/tasks.jsonl tbd create --file .beads/tasks.jsonl --title "Investigate latency" --description "..." --type bug --priority 1 ``` -------------------------------- ### Install Instructor Package in Laravel Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms-full.txt Run this command to publish the configuration, check API key setup, and get started with Instructor in Laravel. ```bash php artisan instructor:install # @doctest id="2ba2" ``` -------------------------------- ### Example Output: Instructor Installation Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/packages/laravel/commands/index.html Shows the expected output when installing the Instructor package for Laravel, including configuration checks and next steps. ```text Installing Instructor for Laravel... Publishing configuration... done Checking API key configuration... done Next steps: 1. Configure your API keys in .env: OPENAI_API_KEY=your-key-here 2. Create a response model: php artisan make:response-model PersonData 3. Extract structured data: $person = Instructor::with( messages: "John is 30 years old", responseModel: PersonData::class, )->get(); 4. Test your installation: php artisan instructor:test Instructor installed successfully! ``` -------------------------------- ### Install Instructor Package Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-build/packages/laravel/installation.mdx Run this command to publish the configuration, check API key setup, and view next steps. ```bash php artisan instructor:install # @doctest id="5dc7" ``` -------------------------------- ### Example Output of Instructor Install Command Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms-full.txt This output shows the typical result of running `php artisan instructor:install`, including steps for publishing configuration, checking API keys, and guidance on creating response models and testing the installation. ```text Installing Instructor for Laravel... Publishing configuration... done Checking API key configuration... done Next steps: 1. Configure your API keys in .env: OPENAI_API_KEY=your-key-here 2. Create a response model: php artisan make:response-model PersonData 3. Extract structured data: $person = StructuredOutput::with( messages: "John is 30 years old", responseModel: PersonData::class, )->get(); 4. Test your installation: php artisan instructor:test Instructor installed successfully! ``` -------------------------------- ### Quick Start Example: List Open Tasks Source: https://github.com/cognesy/instructor-php/blob/main/packages/auxiliary/notes/TBD.md Shows how to list all currently open tasks from the specified JSONL file. ```bash tbd list --file .beads/tasks.jsonl --status open ``` -------------------------------- ### Session Runtime Quick Start Example Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms/packages/agents/16-session-runtime.md A practical example demonstrating how to create a session, send a message, and retrieve the updated session state using the SessionRuntime. ```APIDOC ## Quick Start: Session Runtime Usage ### Description This example illustrates the basic workflow of using `SessionRuntime` to create a new agent session, execute a message-sending action, and access the updated session state. ### Steps 1. **Define the Agent**: Create an `AgentDefinition` specifying the agent's name, description, and system prompt. ```php use Cognesy\Agents\Template\Data\AgentDefinition; $definition = new AgentDefinition( name: 'assistant', description: 'A helpful general assistant', systemPrompt: 'You are a helpful assistant. Be concise and accurate.', ); ``` 2. **Set up Infrastructure**: Initialize the `SessionRepository` (with an in-memory store for this example) and `EventDispatcher`, then instantiate `SessionRuntime`. ```php use Cognesy\Agents\Session\SessionRepository; use Cognesy\Agents\Session\SessionRuntime; use Cognesy\Agents\Session\Store\InMemorySessionStore; use Cognesy\Events\Dispatchers\EventDispatcher; $repo = new SessionRepository(new InMemorySessionStore()); $events = new EventDispatcher('session-runtime'); $runtime = new SessionRuntime($repo, $events); ``` 3. **Create a Session**: Use the `SessionRuntime` to create a new session based on the agent definition. ```php $session = $runtime->create($definition); ``` 4. **Set up Loop Factory**: Configure the `AgentCapabilityRegistry` and `DefinitionLoopFactory` for action execution. ```php use Cognesy\Agents\Capability\AgentCapabilityRegistry; use Cognesy\Agents\Capability\Bash\UseBash; use Cognesy\Agents\Template\Factory\DefinitionLoopFactory; $capabilities = new AgentCapabilityRegistry(); $capabilities->register('use_bash', new UseBash()); $loopFactory = new DefinitionLoopFactory($capabilities, events: $events); ``` 5. **Send a Message**: Execute a `SendMessage` action on the session. ```php use Cognesy\Agents\Session\Actions\SendMessage; $updated = $runtime->execute( $session->sessionId(), new SendMessage('What is 2 + 2?', $loopFactory), ); ``` 6. **Retrieve Response**: Access the updated state from the returned session object. ```php $state = $updated->state(); // The agent's response will be in $state ``` ``` -------------------------------- ### Provide Few-Shot Examples Source: https://github.com/cognesy/instructor-php/blob/main/packages/instructor/docs/advanced/prompts.md Provide input/output examples to guide the LLM's extraction behavior, improving accuracy. Requires importing Example. ```php use Cognesy\Instructor\Extras\Example\Example; $result = (new StructuredOutput) ->withExamples([ new Example( input: 'Dr. Smith is a 45-year-old cardiologist from Boston.', output: ['name' => 'Dr. Smith', 'age' => 45, 'occupation' => 'cardiologist'], ), ]) ->with(messages: $text, responseModel: Person::class) ->get(); ``` -------------------------------- ### Run All Tutorials with Instructor Hub CLI Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms-full.txt Execute all tutorials and examples starting from a specified ID. Primarily for testing. ```bash $./bin/instructor-hub all {id} ``` -------------------------------- ### Complete New Package Setup Source: https://github.com/cognesy/instructor-php/blob/main/CONTRIBUTING.md After creating and configuring a new package, navigate to its directory and install its dependencies. ```bash cd packages/my-package composer install composer test ``` -------------------------------- ### Quick Start Examples Source: https://github.com/cognesy/instructor-php/blob/main/packages/doctools/notes/FREEZE.md Demonstrates how to generate images from files and terminal commands using the Freeze PHP API. ```APIDOC ## Quick Start ```php use Cognesy\Doctor\Freeze\Freeze; use Cognesy\Doctor\Freeze\FreezeConfig; // Generate image from file $result = Freeze::file('script.php') ->output('code.png') ->theme(FreezeConfig::THEME_DRACULA) ->window() ->run(); // Generate image from terminal command $result = Freeze::execute('ls -la') ->output('terminal.png') ->background('#1e1e2e') ->run(); ``` ``` -------------------------------- ### Run All Tutorials Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/cookbook/introduction/index.html Execute all tutorials and examples in the terminal, starting from a specified tutorial ID. This is primarily used for testing the execution of cookbooks. ```bash ./bin/instructor-hub all {id} ``` -------------------------------- ### Provide Few-Shot Examples for LLM Guidance Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-build/packages/instructor/advanced/prompts.mdx Use `withExamples()` with an array of `Example` objects to guide the LLM's extraction behavior. Few-shot examples are highly effective for improving accuracy. ```php use Cognesy\Instructor\Extras\Example\Example; $result = (new StructuredOutput) ->withExamples([ new Example( input: 'Dr. Smith is a 45-year-old cardiologist from Boston.', output: ['name' => 'Dr. Smith', 'age' => 45, 'occupation' => 'cardiologist'], ), ]) ->with(messages: $text, responseModel: Person::class) ->get(); // @doctest id="b370" ``` -------------------------------- ### Complete Example: User Object Creation Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-build/cookbook/examples/A01_Basics/basic_use_mixin.mdx This example demonstrates a full implementation of creating a `User` object from an LLM response. It includes setup, response generation, and assertions to verify the output. ```php with( messages: "Jason is 25 years old and works as an engineer.", responseModel: User::class, ) ->getObject(); dump($user); assert(isset($user->name)); assert(isset($user->age)); assert($user->name === 'Jason'); assert($user->age === 25); ?> ``` -------------------------------- ### Clone Instructor PHP Project Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/cookbook/introduction/index.html Clone the Instructor PHP project from GitHub to access its tutorials and examples. This is the first step to get started with the project. ```bash git clone https://github.com/cognesy/instructor-php.git ``` -------------------------------- ### Quick Start: Building and Running an Agent Source: https://github.com/cognesy/instructor-php/blob/main/packages/addons/notes/AGENT.md Demonstrates the basic steps to create an agent with specific capabilities, initialize its state with a user message, and run it to completion. ```php use Cognesy\Addons\AgentBuilder\AgentBuilder; use Cognesy\Addons\AgentBuilder\Capabilities\Bash\UseBash; use Cognesy\Addons\AgentBuilder\Capabilities\File\UseFileTools; use Cognesy\Addons\AgentBuilder\Capabilities\Tasks\UseTaskPlanning; use Cognesy\Addons\Agent\Core\Data\AgentState; use Cognesy\Messages\Messages; // Create agent with tools using builder $agent = AgentBuilder::base() ->withCapability(new UseBash()) ->withCapability(new UseFileTools('/path/to/project')) ->withCapability(new UseTaskPlanning()) ->build(); // Initialize state with user message $state = AgentState::empty()->withMessages( Messages::fromString('Read config.php and update the debug flag to true') ); // Run to completion $finalState = $agent->finalStep($state); echo $finalState->currentStep()->outputMessages()->toString(); ``` -------------------------------- ### GET Request Example Source: https://github.com/cognesy/instructor-php/blob/main/packages/http-client/docs/3-making-requests.md Example of creating a GET request with query parameters included directly in the URL. ```APIDOC ## GET Requests ### Description GET requests are the simplest form. Pass query parameters directly in the URL. ### Method GET ### Endpoint `https://api.example.com/users?page=1&limit=10` ### Parameters #### Path Parameters None #### Query Parameters - **page** (int) - Optional - The page number for pagination. - **limit** (int) - Optional - The number of items per page. #### Request Body None ### Request Example ```php $request = new HttpRequest( url: 'https://api.example.com/users?page=1&limit=10', method: 'GET', headers: ['Accept' => 'application/json'], body: '', options: [], ); $response = $client->send($request)->get(); ``` ### Response #### Success Response (200) Details depend on the API. #### Response Example None ``` -------------------------------- ### Use MoonshotAI API for Text Generation Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms/cookbook/examples/B04_LLMApiSupport/llm_moonshotai.md This example demonstrates how to use the MoonshotAI API via the Instructor inference client to get a response to a text-based prompt. Ensure the 'examples/boot.php' file is included for necessary setup. ```php with( messages: Messages::fromString('What is the capital of France'), options: ['max_tokens' => 64] ) ->get(); echo "USER: What is capital of France\n"; echo "ASSISTANT: $answer\n"; assert(Str::contains($answer, 'Paris')); ?> ``` -------------------------------- ### Structured Output - Examples Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms/packages/laravel/facades.md Providing few-shot examples to guide the LLM. ```APIDOC ## Structured Output - Examples ### Description Providing few-shot examples to guide the LLM. ### Method ```php Instructor::with(..., withExamples: array $examples) ``` ### Request Example ```php use Cognesy\Instructor\Laravel\Facades\Instructor; use Cognesy\Messages\Messages; $examples = [ ['user' => 'Translate "hello" to Spanish', 'assistant' => 'Hola'], ['user' => 'Translate "goodbye" to Spanish', 'assistant' => 'Adiós'], ]; $response = Instructor::with( messages: Messages::fromString('Translate "thank you" to Spanish'), withExamples: $examples, responseModel: 'string' )->get(); ``` ### Response Example ```php "Gracias" ``` ``` -------------------------------- ### ReAct Driver Quick Start Source: https://github.com/cognesy/instructor-php/blob/main/packages/addons/notes/TOOLUSE.md Demonstrates the setup and execution of the ReAct driver for tool use. It includes configuring inference, structured output, continuation criteria, and defining tools. ```php use Cognesy\Addons\StepByStep\Continuation\ContinuationCriteria; use Cognesy\Addons\StepByStep\Continuation\Criteria\StepsLimit; use Cognesy\Addons\StepByStep\Continuation\Criteria\TokenUsageLimit; use Cognesy\Addons\ToolUse\Collections\Tools; use Cognesy\Addons\ToolUse\Data\ToolUseState; use Cognesy\Addons\ToolUse\Drivers\ReAct\ContinuationCriteria\StopOnFinalDecision; use Cognesy\Addons\ToolUse\Drivers\ReAct\ReActDriver; use Cognesy\Addons\ToolUse\Tools\FunctionTool; use Cognesy\Addons\ToolUse\ToolUseFactory; use Cognesy\Events\Dispatchers\EventDispatcher; use Cognesy\Instructor\Creation\StructuredOutputConfigBuilder; use Cognesy\Instructor\StructuredOutputRuntime; use Cognesy\Messages\Messages; use Cognesy\Instructor\Enums\OutputMode; use Cognesy\Polyglot\Inference\InferenceRuntime; use Cognesy\Polyglot\Inference\LLMProvider; use Cognesy\Polyglot\Inference\Config\LLMConfig; $events = new EventDispatcher(name: 'addons.tooluse.react'); $inference = InferenceRuntime::fromProvider( LLMProvider::fromLLMConfig(LLMConfig::fromArray(['driver' => 'openai'])), events: $events, ); $structuredOutput = new StructuredOutputRuntime( inference: $inference, events: $events, config: (new StructuredOutputConfigBuilder()) ->withOutputMode(OutputMode::Json) ->withMaxRetries(2) ->create(), ); $driver = new ReActDriver( inference: $inference, structuredOutput: $structuredOutput, maxRetries: 2, finalViaInference: true ); $continuationCriteria = new ContinuationCriteria( new StepsLimit(6, fn(ToolUseState $state) => $state->stepCount()), new TokenUsageLimit(8192, fn(ToolUseState $state) => $state->usage()->total()), new StopOnFinalDecision(), ); $tools = new Tools( FunctionTool::fromCallable(add_numbers(...)), FunctionTool::fromCallable(subtract_numbers(...)) ); $toolUse = ToolUseFactory::default( tools: $tools, continuationCriteria: $continuationCriteria, driver: $driver ); $state = (new ToolUseState()) ->withMessages(Messages::fromString('Add 2455 and 3558 then subtract 4344 from the result.')); $final = $toolUse->finalStep($state); echo $final->currentStep()?->outputMessages()?->toString() ?? ''; ``` -------------------------------- ### PHP Auto-Refine Prompt Example Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-build/cookbook/examples/Z01_ZeroShot/auto_refine.mdx This PHP code implements the S2A technique to auto-refine a prompt. It first extracts relevant context and the user's query into a `RewrittenTask` object and then uses this refined information to get a final answer. Ensure you have the necessary dependencies installed. ```php rewritePrompt($problem); return StructuredOutput::using('openai') ->with( messages: "{$rewrittenPrompt->relevantContext}\nQuestion: {$rewrittenPrompt->userQuery}", responseModel: Scalar::integer('answer'), ) ->getInt(); } private function rewritePrompt(string $query) : RewrittenTask { return StructuredOutput::using('openai')->with( messages: str_replace('{query}', $query, $this->prompt), responseModel: RewrittenTask::class, model: 'gpt-4o-mini', )->get(); } } $answer = (new RefineAndSolve)(problem: <<= 15, "Expected at least 15 (3*5), full answer is 25 (3*5+10)"); ?> ``` -------------------------------- ### Session Runtime Quick Start Source: https://github.com/cognesy/instructor-php/blob/main/packages/agents/docs/16-session-runtime.md An example demonstrating how to define an agent, set up the session infrastructure, create a session, and execute a message action. ```APIDOC ## Quick Start Example ### Description This example illustrates the basic workflow of using the `SessionRuntime` to create and interact with an agent session. ### Steps 1. **Define the agent**: Create an `AgentDefinition` specifying the agent's name, description, and system prompt. ```php use Cognesy\Agents\Template\Data\AgentDefinition; $definition = new AgentDefinition( name: 'assistant', description: 'A helpful general assistant', systemPrompt: 'You are a helpful assistant. Be concise and accurate.' ); ``` 2. **Set up the infrastructure**: Initialize the `SessionRepository` (using an in-memory store for this example) and the `SessionRuntime`. ```php use Cognesy\Agents\Session\SessionRepository; use Cognesy\Agents\Session\SessionRuntime; use Cognesy\Agents\Session\Store\InMemorySessionStore; use Cognesy\Events\Dispatchers\EventDispatcher; $repo = new SessionRepository(new InMemorySessionStore()); $events = new EventDispatcher('session-runtime'); $runtime = new SessionRuntime($repo, $events); ``` 3. **Create a session**: Use the `SessionRuntime` to create a new session based on the agent definition. ```php $session = $runtime->create($definition); ``` 4. **Set up the loop factory**: Configure capabilities and create a `DefinitionLoopFactory`. ```php use Cognesy\Agents\Capability\AgentCapabilityRegistry; use Cognesy\Agents\Capability\Bash\UseBash; use Cognesy\Agents\Template\Factory\DefinitionLoopFactory; $capabilities = new AgentCapabilityRegistry(); $capabilities->register('use_bash', new UseBash()); $loopFactory = new DefinitionLoopFactory($capabilities, events: $events); ``` 5. **Send a message**: Execute an action (e.g., `SendMessage`) on the session. ```php use Cognesy\Agents\Session\Actions\SendMessage; $updated = $runtime->execute( $session->sessionId(), new SendMessage('What is 2 + 2?', $loopFactory) ); ``` 6. **Retrieve the response**: Access the updated session state to get the agent's response. ```php $state = $updated->state(); ``` ``` -------------------------------- ### List Available Tutorials with Instructor Hub CLI Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms-full.txt Use the Instructor Hub CLI to list all available tutorials and examples. ```bash $./bin/instructor-hub list ``` -------------------------------- ### Bulk Execution with Tracking (Bash) Source: https://github.com/cognesy/instructor-php/blob/main/packages/hub/README.md Execute all examples, starting from a specified example number or from the beginning. ```bash composer hub all composer hub all 50 ``` -------------------------------- ### PHP Analogical Prompting Example Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms/cookbook/examples/Z03_ThoughtGen/analogical_prompting.md Implement Analogical Prompting in PHP using Instructor. Define data models for the response and use a templated prompt to guide the LLM in recalling relevant problems and solutions before answering the main query. Ensure the 'examples/boot.php' file is included for setup. ```php {query} Relevant Problems: Recall {n} relevant and distinct problems. For each problem, describe it and explain the solution before solving the problem PROMPT; public function __invoke(string $query) : Response { return StructuredOutput::using('openai')->with( messages: str_replace(['{n}', '{query}'], [$this->n, $query], $this->prompt), responseModel: Response::class, )->get(); } } $solution = (new SolvePerAnalogy)('What is the area of the square with the four vertices at (-2, 2), (2, -2), (-2, -6), and (-6, -2)?'); dump($solution); assert($solution instanceof Response); assert(is_array($solution->relevantProblems)); assert(count($solution->relevantProblems) > 0); assert(!empty($solution->answer)); assert($solution->problemSolution instanceof Problem); ?> ``` -------------------------------- ### Quick Start: Orchestrating Tool Use Source: https://github.com/cognesy/instructor-php/blob/main/packages/addons/notes/TOOLUSE.md Demonstrates a basic setup for ToolUse, including defining a function tool, initializing the ToolUse orchestrator, and executing a tool call based on initial messages. ```php use Cognesy\Addons\ToolUse\Collections\Tools; use Cognesy\Addons\ToolUse\Data\ToolUseState; use Cognesy\Addons\ToolUse\Tools\FunctionTool; use Cognesy\Addons\ToolUse\ToolUseFactory; use Cognesy\Messages\Messages; function add_numbers(int $a, int $b): int { return $a + $b; } $tools = new Tools( FunctionTool::fromCallable(add_numbers(...)) ); $toolUse = ToolUseFactory::default(tools: $tools); $state = (new ToolUseState()) ->withMessages(Messages::fromString('Add numbers 2 and 3')); $final = $toolUse->finalStep($state); echo $final->currentStep()?->outputMessages()?->toString() ?? ''; ``` -------------------------------- ### Adding Few-Shot Examples for Demonstration Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/packages/instructor/essentials/customize_prompts/index.html Provide few-shot examples using the `Example::fromText()` method within `withExamples()` to guide the model's output style. ```php use Cognesy\Instructor\Extras\Example\Example; $result = (new StructuredOutput) ->withExamples([ Example::fromText('Jane Doe, 31', ['name' => 'Jane Doe', 'age' => 31]), ]) ->with(messages: $text, responseModel: Person::class) ->get(); ``` -------------------------------- ### Agent Setup with Structured Output and Tools Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms-full.txt Initializes an agent with console logging, registers the 'Lead' schema for extraction, and prepares to use the 'CreateLeadTool'. This setup is crucial for enabling the agent's advanced capabilities. ```php agentState === null) { return 'Error: Agent state not available'; } $leadData = $this->agentState->metadata()->get($metadataKey); if ($leadData === null) { return "Error: No lead data found at metadata key '{$metadataKey}'"; } // Extract lead info for the response $name = match (true) { is_object($leadData) && property_exists($leadData, 'name') => $leadData->name, is_array($leadData) && isset($leadData['name']) => $leadData['name'], default => 'Unknown', }; $email = match (true) { is_object($leadData) && property_exists($leadData, 'email') => $leadData->email, is_array($leadData) && isset($leadData['email']) => $leadData['email'], default => 'Unknown', }; // Simulate API call - in real implementation, call actual CRM API $leadId = 'LEAD-' . strtoupper(substr(md5((string) time()), 0, 8)); return "Lead created successfully!\n" . " ID: {$leadId}\n" . " Name: {$name}\n" . " Email: {$email}\n" . " Source: metadata key '{$metadataKey}'"; } #[\]Override public function toToolSchema(): ToolDefinition { return ToolDefinition::fromArray([ 'type' => 'function', 'function' => [ 'name' => $this->name(), 'description' => $this->description(), 'parameters' => [ 'type' => 'object', 'properties' => [ 'metadata_key' => [ 'type' => 'string', 'description' => 'The metadata key where lead data is stored (e.g., "current_lead")', ], ], 'required' => ['metadata_key'], ], ], ]); } } // ============================================================================= // 3. Build the agent with structured output and API capabilities // ============================================================================= // Create console logger for execution visibility $logger = new AgentEventConsoleObserver( useColors: true, showTimestamps: true, showContinuation: true, showToolArgs: true, ); // Register extraction schemas $schemas = new SchemaRegistry([ 'lead' => new SchemaDefinition( class: Lead::class, description: 'Business lead with contact information', prompt: 'Extract lead information from the text. Look for names, emails, ' ``` -------------------------------- ### Provide Few-Shot Examples Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms/packages/instructor/advanced/prompts.md Use `withExamples()` with an array of `Example` objects to guide the LLM's extraction behavior. Few-shot examples are highly effective for improving accuracy. ```php use Cognesy\Instructor\Extras\Example\Example; $result = (new StructuredOutput) ->withExamples([ new Example( input: 'Dr. Smith is a 45-year-old cardiologist from Boston.', output: ['name' => 'Dr. Smith', 'age' => 45, 'occupation' => 'cardiologist'], ), ]) ->with(messages: $text, responseModel: Person::class) ->get(); // @doctest id="7c23" ``` -------------------------------- ### Using Examples with StructuredOutput Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/packages/instructor/essentials/demonstrations/index.html Demonstrates how to provide examples to the `StructuredOutput` class to guide the model's extraction. Examples are particularly useful in `OutputMode::Json` and `OutputMode::MdJson` modes. ```php use Cognesy\Instructor\Extras\Example\Example; use Cognesy\Instructor\StructuredOutput; class User { public int $age; public string $name; } $user = (new StructuredOutput) ->with( messages: 'Our user Jason is 25 years old.', responseModel: User::class, examples: [ new Example( input: 'John is 50 and works as a teacher.', output: ['name' => 'John', 'age' => 50], ), new Example( input: 'We recently hired Ian, who is 27 years old.', output: ['name' => 'Ian', 'age' => 27], ), ], ) ->get(); ``` -------------------------------- ### List Available Tutorials Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/cookbook/introduction/index.html Run this command in the terminal to see all available tutorials and examples within the Instructor PHP project. This helps in discovering what content is available. ```bash ./bin/instructor-hub list ``` -------------------------------- ### Provide Few-Shot Examples for Extraction Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/packages/instructor/advanced/prompts/index.html Use `withExamples` to provide input/output examples that guide the LLM's extraction behavior. Few-shot examples are highly effective for improving extraction accuracy. ```php use Cognesy\Instructor\Extras\Example\Example; $result = (new StructuredOutput) ->withExamples([ new Example( input: 'Dr. Smith is a 45-year-old cardiologist from Boston.', output: ['name' => 'Dr. Smith', 'age' => 45, 'occupation' => 'cardiologist'], ) ]) ->with(messages: $text, responseModel: Person::class) ->get(); ``` -------------------------------- ### PHP: Execute and Read Agent Sessions Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/cookbook/examples/D04_AgentSessions/session_runtime_read_apis/index.html This example demonstrates setting up the session factory, repository, and runtime, creating two agents, executing them, and then using getSession, getSessionInfo, and listSessions to retrieve and verify their state and existence. It requires the 'examples/boot.php' file for setup. ```php create($factory->create(new AgentDefinition( name: 'agent-one', description: 'first', systemPrompt: 'You are one.', llmConfig: 'openai', ))); $two = $repo->create($factory->create(new AgentDefinition( name: 'agent-two', description: 'second', systemPrompt: 'You are two.', llmConfig: 'openai', ))); $runtime->execute($one->sessionId(), new SendMessage('Say one sentence about session one.', $loopFactory)); $runtime->execute($two->sessionId(), new SendMessage('Say one sentence about session two.', $loopFactory)); $sessionId = $one->sessionId(); $session = $runtime->getSession($sessionId); $info = $runtime->getSessionInfo($sessionId); $list = $runtime->listSessions(); echo "=== Result ===\n"; echo 'Loaded session: ' . $session->sessionId() . "\n"; echo 'Session info status: ' . $info->status()->value . "\n"; echo 'Session message count: ' . $session->state()->messages()->count() . "\n"; echo 'Session last response: ' . ($session->state()->finalResponse()->toString() ?: 'No response') . "\n"; echo 'List count: ' . $list->count() . "\n"; assert($session !== null, 'getSession should return a session'); assert($session->sessionId()->toString() === $sessionId->toString(), 'Loaded session ID should match requested ID'); assert($info->status()->value === 'active', 'Session info status should be active'); assert($session->state()->messages()->count() > 0, 'Session should have messages after SendMessage'); assert(!empty($session->state()->finalResponse()->toString()), 'Session should have a last response'); assert($list->count() === 2, 'listSessions should return both sessions'); ?> ``` -------------------------------- ### Provide Few-Shot Examples - Instructor PHP Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-mkdocs/packages/instructor/advanced/prompts.md Use `withExamples()` to provide input/output examples that guide the LLM's extraction behavior. Few-shot examples are effective for improving extraction accuracy. ```php use Cognesy\Instructor\Extras\Example\Example; $result = (new StructuredOutput) ->withExamples([ new Example( input: 'Dr. Smith is a 45-year-old cardiologist from Boston.', output: ['name' => 'Dr. Smith', 'age' => 45, 'occupation' => 'cardiologist'], ), ]) ->with(messages: $text, responseModel: Person::class) ->get(); // @doctest id="df4f" ``` -------------------------------- ### Run All Cookbooks Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms/cookbook/introduction.md Execute all available tutorials and examples starting from a specified ID using the instructor-hub all command. This is useful for testing cookbook execution. ```bash $ ./bin/instructor-hub all {id} ``` -------------------------------- ### PHP: Providing Examples for Structured Output Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/cookbook/examples/A02_Advanced/demonstrations/index.html Use examples to guide LLM inference for structured output. This is particularly useful for JSON and MdJson output modes. Ensure the `Example` class is imported. ```php withOutputMode(OutputMode::Json) ->onEvent(HttpRequestSent::class, fn($event) => dump($event)); $user = (new StructuredOutput($runtime)) ->withMessages("Our user Jason is 25 years old.") ->withResponseClass(User::class) ->withExamples([ new Example( input: "John is 50 and works as a teacher.", output: ['name' => 'John', 'age' => 50] ), new Example( input: "We have recently hired Ian, who is 27 years old.", output: ['name' => 'Ian', 'age' => 27], template: "example input:\n<|input|>\noutput:\n```json\n<|output|>\n```\n", ), ]) ->get(); echo "\nOUTPUT:\n"; dump($user); assert($user->name === 'Jason'); assert($user->age === 25); ?> ``` -------------------------------- ### Add Few-Shot Examples Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-mkdocs/packages/instructor/essentials/customize_prompts.md Incorporate few-shot examples using `withExamples()` to guide the model's extraction style. Examples are rendered as markdown within the system prompt on the new structured path. ```php use Cognesy\Instructor\Extras\Example\Example; $result = (new StructuredOutput) ->withExamples([ Example::fromText('Jane Doe, 31', ['name' => 'Jane Doe', 'age' => 31]), ]) ->with(messages: $text, responseModel: Person::class) ->get(); // @doctest id="fa61" ``` -------------------------------- ### Putting It Together: Runtime and Request Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms-full.txt Example demonstrating how to create a runtime at bootstrap and reuse it for multiple requests, keeping configuration centralized. ```APIDOC ## Putting It Together ### Description A typical application creates one runtime at bootstrap and passes it to each request. This keeps configuration centralized and each request minimal. ### Example ```php // Bootstrap $runtime = StructuredOutputRuntime::fromConfig( LLMConfig::fromPreset('openai') )->withMaxRetries(2); // Request 1 $person = (new StructuredOutput) ->withRuntime($runtime) ->with(messages: $text1, responseModel: Person::class) ->get(); // Request 2 $summary = (new StructuredOutput) ->withRuntime($runtime) ->with(messages: $text2, responseModel: Summary::class) ->get(); ``` ``` -------------------------------- ### Set Examples Using Fluent API Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-build/packages/instructor/essentials/demonstrations.mdx Demonstrates how to integrate examples into the `StructuredOutput` process using the `withExamples()` fluent method. This provides an alternative to passing examples directly in the `with()` method. ```php $user = (new StructuredOutput) ->withExamples([ Example::fromText('Jane, 31', ['name' => 'Jane', 'age' => 31]), ]) ->with( messages: 'Our user Jason is 25 years old.', responseModel: User::class, ) ->get(); // @doctest id="8dfc" ``` -------------------------------- ### Basic Example Usage with StructuredOutput Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-mkdocs/packages/instructor/essentials/demonstrations.md Instantiate `StructuredOutput` and provide messages, the response model, and a list of `Example` objects to guide the model's extraction. ```php use Cognesy\Instructor\Extras\Example\Example; use Cognesy\Instructor\StructuredOutput; class User { public int $age; public string $name; } $user = (new StructuredOutput) ->with( messages: 'Our user Jason is 25 years old.', responseModel: User::class, examples: [ new Example( input: 'John is 50 and works as a teacher.', output: ['name' => 'John', 'age' => 50], ), new Example( input: 'We recently hired Ian, who is 27 years old.', output: ['name' => 'Ian', 'age' => 27], ), ], ) ->get(); // @doctest id="bc18" ``` -------------------------------- ### HTTP Client Streaming Basics Example Source: https://github.com/cognesy/instructor-php/blob/main/builds/docs-site/cookbook/examples/C01_Http/http_client_streaming_basics/index.html This example demonstrates how to initiate and process a streaming HTTP request. It shows the basic setup for receiving data in chunks. ```php requestAsync('GET', 'https://httpbin.org/stream/20'); // Handle the response stream $promise->then(function (ResponseInterface $response) { echo "Status Code: " . $response->getStatusCode() . "\n"; // Get the response body stream $stream = $response->getBody(); // Read from the stream in chunks while (!$stream->eof()) { $chunk = $stream->read(1024); echo "Received chunk: " . strlen($chunk) . " bytes\n"; // Process the chunk here } echo "\nStream finished.\n"; }, function (object $error) { echo "Error: " . $error->getMessage() . "\n"; }); // Wait for the promise to resolve (or handle it asynchronously) $promise->wait(); ``` -------------------------------- ### Verify Example Discovery Source: https://github.com/cognesy/instructor-php/blob/main/packages/hub/docs/adding-examples.md Run this command after making changes to example configurations to ensure new examples are discovered and listed correctly. ```bash composer hub list ``` -------------------------------- ### Structured Output Extraction with Examples Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms-full.txt Demonstrates how to use few-shot learning by providing input/output examples to guide the LLM in extracting data according to a specified pattern. ```APIDOC ## StructuredOutput::with() with Examples ### Description Use the `examples` parameter within `StructuredOutput::with()` to provide few-shot learning examples for the LLM. ### Method `StructuredOutput::with()` ### Parameters #### Request Body - **messages** (string) - The prompt or message to send to the LLM. - **responseModel** (string) - The class name or schema for the expected response. - **examples** (array) - An array of input/output pairs to guide the LLM. ### Request Example ```php $person = StructuredOutput::with( messages: 'Extract: Jane Doe, 25 years', responseModel: PersonData::class, examples: [ ['input' => 'Bob is 40', 'output' => new PersonData(name: 'Bob', age: 40)], ], )->get(); ``` ``` -------------------------------- ### Setting Examples with Fluent API Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms/packages/instructor/essentials/demonstrations.md Examples can be provided using the fluent `withExamples()` method on the `StructuredOutput` object, allowing for a chained configuration style. ```php $user = (new StructuredOutput) ->withExamples([ Example::fromText('Jane, 31', ['name' => 'Jane', 'age' => 31]), ]) ->with( messages: 'Our user Jason is 25 years old.', responseModel: User::class, ) ->get(); // @doctest id="045f" ``` -------------------------------- ### Verify Instructor Installation Source: https://github.com/cognesy/instructor-php/blob/main/builds/build-llms/llms/packages/laravel/installation.md Run this command to verify that the Instructor package is installed and configured correctly. It checks for API key configuration and guides you through the next steps. ```bash php artisan instructor:install ```