PHP code example of assistant-engine / open-functions-core

1. Go to this page and download the library: Download assistant-engine/open-functions-core 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/ */

    

assistant-engine / open-functions-core example snippets


// A common llm call
$response = $client->chat()->create([
    'model'         => 'gpt-4o',
    'messages'      => $messages, // 1. Building the messages array
    'tools'         => $functionDefinitions, // 2. Collect the right function definitions
]);

if (isset($response->choices[0]->message->toolCalls)) {
    foreach ($response->choices[0]->message->toolCalls as $toolCall) {
        // 3. Executing the requested tool call
    }
}


use AssistantEngine\OpenFunctions\Core\Models\Messages\Content\ToolCall;
use AssistantEngine\OpenFunctions\Core\Models\Messages\DeveloperMessage;
use AssistantEngine\OpenFunctions\Core\Models\Messages\ToolMessage;
use AssistantEngine\OpenFunctions\Core\Models\Messages\UserMessage;
use AssistantEngine\OpenFunctions\Core\Models\Messages\AssistantMessage;
use AssistantEngine\OpenFunctions\Core\Models\Messages\MessageList;

// Define an array of messages based on the OpenAI API schema.
// These primitives can be used to structure the conversation context.
$messages = [
    new DeveloperMessage("You are a helpful assistant."),
    new UserMessage("What's the weather like today in Paris?"),
    (new AssistantMessage())
        ->addToolCall(new ToolCall("tool_call_1", "getWeather", json_encode(["cityName" => "Paris"]))),
    new ToolMessage("The weather in Paris is sunny with a temperature of 24°C.", "tool_call_1"),
    new AssistantMessage("The current weather in Paris is sunny with a high of 24°C."),
    new UserMessage("Thanks!")
];

// Create a MessageList and add the messages array
$messageList = new MessageList();
$messageList->addMessages($messages);

// Convert the MessageList to an array for use in an API call
$conversationArray = $messageList->toArray();

// These definitions can now be used as the tools parameter in your OpenAI client call.
$response = $client->chat()->create([
    'model'    => 'gpt-4o',
    'messages' => $conversationArray
]);



use AssistantEngine\OpenFunctions\Core\Contracts\AbstractOpenFunction;
use AssistantEngine\OpenFunctions\Core\Helpers\FunctionDefinition;
use AssistantEngine\OpenFunctions\Core\Helpers\Parameter;
use AssistantEngine\OpenFunctions\Core\Models\Responses\TextResponseItem;

class WeatherOpenFunction extends AbstractOpenFunction
{
    /**
     * Generate function definitions.
     *
     * This method returns a schema defining the "getWeather" function.
     * It e weather for.')
                ->


use AssistantEngine\OpenFunctions\Core\Examples\WeatherOpenFunction;

// Instantiate the WeatherOpenFunction.
$weatherFunction = new WeatherOpenFunction();

// Generate the function definitions. This creates a schema for functions like "getWeather" and "getForecast".
$functionDefinitions = $weatherFunction->generateFunctionDefinitions();

// These definitions can now be used as the tools parameter in your OpenAI client call.
$response = $client->chat()->create([
    'model'    => 'gpt-4o',
    'messages' => $conversationArray,
    'tools'    => $functionDefinitions,
]);

// Process the response and execute any tool calls as needed.


use AssistantEngine\OpenFunctions\Core\Examples\WeatherOpenFunction;
use AssistantEngine\OpenFunctions\Core\Tools\OpenFunctionRegistry;

// Create an instance of the registry.
$registry = new OpenFunctionRegistry();

// Instantiate two WeatherOpenFunction instances.
// For this example, imagine the WeatherOpenFunction can be configured to use different temperature units.
// The first instance is set for Celsius (default), and the second for Fahrenheit.
$weatherCelsius = new WeatherOpenFunction("celsius"); // Configured to return temperatures in Celsius.
$weatherFahrenheit = new WeatherOpenFunction("fahrenheit"); // Imagine this instance is configured to return Fahrenheit.

// Register the functions under different namespaces.
// The registry automatically prefixes function names with the namespace (e.g., "celsius_getWeather", "fahrenheit_getWeather").
$registry->registerOpenFunction('celsius', 'Weather functions using Celsius.', $weatherCelsius);
$registry->registerOpenFunction('fahrenheit', 'Weather functions using Fahrenheit.', $weatherFahrenheit);

// Retrieve all namespaced function definitions to pass to the OpenAI client.
$toolDefinitions = $registry->generateFunctionDefinitions();

// Use these tool definitions in the client call.
$response = $client->chat()->create([
    'model'    => 'gpt-4o',
    'messages' => $conversationArray,
    'tools'    => $toolDefinitions,
]);

// Later, when the client calls a function, the registry will use the namespaced function name 
// (e.g., "celsius_getWeather" or "fahrenheit_getWeather") to invoke the correct method.

use AssistantEngine\OpenFunctions\Core\Examples\DeliveryOpenFunction;
use AssistantEngine\OpenFunctions\Core\Tools\OpenFunctionRegistry;

$registry = new OpenFunctionRegistry(true, 'This is the registry where you can control active functions');

$burger = new DeliveryOpenFunction([
    'Classic Burger',
    'Cheese Burger',
    'Bacon Burger',
    'Veggie Burger',
    'Double Burger'
]);

$pizza = new DeliveryOpenFunction([
    'Margherita',
    'Pepperoni',
    'Hawaiian',
    'Veggie',
    'BBQ Chicken',
    'Meat Lovers'
]);

$sushi = new DeliveryOpenFunction([
    'California Roll',
    'Spicy Tuna Roll',
    'Salmon Nigiri',
    'Eel Avocado Roll',
    'Rainbow Roll',
    'Vegetable Roll'
]);

$registry->registerOpenFunction(
    'burger',
    'This is a nice burger place.',
    $burger
);

$registry->registerOpenFunction(
    'pizza',
    'This is a nice pizza place',
    $pizza
);

$registry->registerOpenFunction(
    'sushi',
    'This is a nice sushi place',
    $sushi
);

/**
 * Extend the message list by prepending a developer message with namespace details.
 *
 * @param MessageList $messageList
 * @return void
 */
public function extend(MessageList $messageList): void
{
    if (empty($this->registry->getNamespaces())) {
        return;
    }
    $messageList->prependMessages([$this->getNamespacesDeveloperMessage()]);
}

use AssistantEngine\OpenFunctions\Core\Models\Messages\MessageList;
use AssistantEngine\OpenFunctions\Core\Tools\OpenFunctionRegistry;
use AssistantEngine\OpenFunctions\Core\Presenter\RegistryPresenter;

// Instantiate your registry and register any open functions as needed.
$registry = new OpenFunctionRegistry();
// (Assume functions are registered here...)

// Create a message list and add the registry as an extension.
$messageList = new MessageList();
$messageList->addExtension(new RegistryPresenter($registry),);

// When converting to an array, the registry extension prepends the developer message.
$conversationArray = $messageList->toArray();


use AssistantEngine\OpenFunctions\Core\Contracts\AbstractOpenFunction;
use AssistantEngine\OpenFunctions\Core\Helpers\FunctionDefinition;
use AssistantEngine\OpenFunctions\Core\Helpers\Parameter;
use AssistantEngine\OpenFunctions\Core\Models\Responses\TextResponseItem;

class WeatherOpenFunction extends AbstractOpenFunction
{
    /**
     * Returns the current weather for the given city.
     *
     * @param string $cityName
     * @return TextResponseItem
     */
    public function getWeather(string $cityName)
    {
        $weathers = ['sunny', 'rainy', 'cloudy', 'stormy', 'snowy', 'windy'];
        $weather = $weathers[array_rand($weathers)];
    
        return new TextResponseItem("The weather in {$cityName} is {$weather}.");
    }
    
    // ...
}

// Instantiate the WeatherOpenFunction.
$weatherFunction = new WeatherOpenFunction();

// Call the 'getWeather' method via callMethod.
$response = $weatherFunction->callMethod('getWeather', ['cityName' => 'New York']);

// Output the response as an array.
print_r($response->toArray());


// Execute the function call using the registry.
$response = $registry->callMethod('celsius_getWeather', ['cityName' => 'New York']);
// Output the response as an array.
print_r($response->toArray());

$response = $client->chat()->create([
    'model'         => 'gpt-4o',
    'messages'      => $conversationArray, 
    'tools'         => $toolDefinitions,
]);

if (isset($response->choices[0]->message->toolCalls)) {
    foreach ($response->choices[0]->message->toolCalls as $toolCall) {
        $namespacedName = $toolCall['function']['name'] ?? null;
        $argumentsJson = $toolCall['function']['arguments'] ?? '{}';
    
        $response = $registry->callMethod($namespacedName, json_decode($argumentsJson, true));
    }
}