PHP code example of johannes85 / ai-bundle

1. Go to this page and download the library: Download johannes85/ai-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

johannes85 / ai-bundle example snippets



$messages = [
  new Message(MessageRole::HUMAN, 'Tell me about Canada')
];

$res = $opanAi->generate($messages);
...
$res = $ollama->generate($messages);
...

$messages = [
  new Message(
    MessageRole::HUMAN,
    'What is the content of this image?',
    files: [File::fromPath(FileType::IMAGE, 'image/jpg', __DIR__.'/image.jpg')]
  )
];
$res = $llm->generate($messages);

class CountryInfo {
  public string $name;

  // Usage of setter for further processing/validation of the set data
  private string $capital;
  public function setCapital(string $capital) {
    $this->capital = $capital;
  }

  // Array member type hinting via Attribute
  #[ArrayType(itemType: 'string')] public array $languages; 
}

$info = $llm->generate([
  new Message(MessageRole::HUMAN, 'Tell me about Canada')
], responseDataType: CountryInfo::class);

/* Result:
CountryInfo#248 (3) {
  public string $name =>
  string(6) "Canada"
  private string $capital =>
  string(6) "Ottawa"
  public array $languages =>
  array(2) {
    [0] =>
    string(7) "English"
    [1] =>
    string(6) "French"
  }
}
*/

$res = $this->llm->generate(
  [
    new Message(
      MessageRole::HUMAN,
      'What is the current weather in Karlsruhe (49° 1′ N , 8° 24′ O) and Stuttgart (48° 47′ N, 9° 11′ O), Germany'
    )
  ],
  toolbox: new Toolbox(
    [
      new CallbackTool(
        'getWeather',
        'Retrieves current weather',
        function (
          #[Description('Latitude, for example 52.52')] string $latitude,
          #[Description('Longitude, for example 13.41')] string $longitude
        ) use ($output) {
          return file_get_contents(
            'https://api.open-meteo.com/v1/forecast?latitude=' . $latitude . '&longitude=' . $longitude . '&current=temperature,windspeed'
          );
        }
      )
    ],
    toolChoice: ToolChoice::AUTO, // Can be also ToolChoice::FORCE_TOOL_USAGE or the name of a tool to enforce usage
    maxLLMCalls: 10 // Maximal number of LLM calls, set to a sensible value to avoid infinite loops or expensive calls. Default: 10
  )
)
bash
composer install
php bin/console example:... --llm= ollama
bash
php bin/console
bash
export MISTRAL_AI_APIKEY=...
export ANTHROPIC_APIKEY=...
export GOOGLE_AI_APIKEY=...
export OPEN_AI_APIKEY=...
export DEEP_SEEK_APIKEY=...