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
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@
tests/chunk.php
.idea/
.env
example.php
example.md
/examples/
/blueprints/
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,39 @@ $conversation->message(
$response = $conversation->send();
```

### Tool Calling

Tool calling is integrated into the existing conversation flow:

1. Register tools on the `Agent`
2. Send user message(s)
3. `Conversation::send()` automatically runs the model -> tool -> model loop
4. Receive the final assistant answer

Tool argument schema is inferred from callback signature (parameter names and scalar types).

```php
use Utopia\Agents\Agent;
use Utopia\Agents\Conversation;
use Utopia\Agents\Message;
use Utopia\Agents\Roles\User;
use Utopia\Agents\Adapters\OpenAI;

$agent = new Agent(new OpenAI('your-api-key', OpenAI::MODEL_O4_MINI));

$agent->addTool(
'sum',
fn (int $a, int $b): int => $a + $b,
'Add two integers'
);

$conversation = new Conversation($agent);
$conversation->message(new User('user-1'), new Message('What is 2 + 3?'));

$final = $conversation->send();
echo $final->getContent();
```

### Streaming Responses (SSE)

The conversation layer supports incremental output streaming through `Conversation::listen(callable $listener)`.
Expand Down
78 changes: 71 additions & 7 deletions src/Agents/Adapters/OpenAI.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,12 @@ public function send(array $messages, ?callable $listener = null): Message
if (! $this->isMessageValid($message)) {
throw new \Exception('Invalid message format');
}
$formattedMessages[] = [
$formattedMessage = [
'role' => $message->getRole(),
'content' => $this->formatMessageContent($message),
];

$formattedMessages[] = $formattedMessage;
}

$instructions = [];
Expand Down Expand Up @@ -164,6 +166,7 @@ public function send(array $messages, ?callable $listener = null): Message
$payload['temperature'] = $temperature;

$schema = $agent->getSchema();

if ($schema !== null) {
$payload['response_format'] = [
'type' => 'json_schema',
Expand Down Expand Up @@ -236,11 +239,9 @@ function ($chunk) use (&$content, $listener) {
$choices = is_array($json) && isset($json['choices']) && is_array($json['choices']) ? $json['choices'] : [];
$firstChoice = isset($choices[0]) && is_array($choices[0]) ? $choices[0] : [];
$message = isset($firstChoice['message']) && is_array($firstChoice['message']) ? $firstChoice['message'] : [];
if (isset($message['content']) && is_string($message['content'])) {
$content = $message['content'];
} else {
throw new \Exception('Invalid response format received from the API');
}
$content = $this->extractMessageContent($message);

return new Message($content);
}

return new Message($content);
Expand Down Expand Up @@ -356,7 +357,11 @@ protected function usesDefaultTemperatureOnly(): bool

protected function isMessageValid(Message $message): bool
{
return ! empty($message->getRole()) && $this->hasTextOrImageContent($message);
if (empty($message->getRole())) {
return false;
}

return $this->hasTextOrImageContent($message);
}

protected function hasTextOrImageContent(Message $message): bool
Expand All @@ -379,6 +384,10 @@ protected function hasTextOrImageContent(Message $message): bool
*/
protected function formatMessageContent(Message $message): string|array
{
if ($message->getRole() === 'tool') {
return $message->getContent();
}

$parts = [];

if ($message->getContent() !== '') {
Expand Down Expand Up @@ -409,6 +418,61 @@ protected function formatMessageContent(Message $message): string|array
return $parts;
}

/**
* @param array<string, mixed> $message
*
* @throws \Exception
*/
protected function extractMessageContent(array $message): string
{
if (! array_key_exists('content', $message)) {
throw new \Exception('Invalid response format received from the API');
}
Comment on lines 418 to +430
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 content absence throws instead of returning empty string

When OpenAI returns a response that has only tool_calls and no content key (some API versions may omit it entirely rather than setting it to null), extractMessageContent throws 'Invalid response format received from the API'. Since extractToolCalls already handles the tool_calls field independently, treating an absent content as an empty string is safer and consistent with how null is already handled:

Suggested change
return $parts;
}
/**
* @param array<string, mixed> $message
*
* @throws \Exception
*/
protected function extractMessageContent(array $message): string
{
if (! array_key_exists('content', $message)) {
throw new \Exception('Invalid response format received from the API');
}
protected function extractMessageContent(array $message): string
{
if (! array_key_exists('content', $message)) {
return '';
}
$content = $message['content'];
if (is_string($content)) {
return $content;
}
if ($content === null) {
return '';
}
if (! is_array($content)) {
throw new \Exception('Invalid response format received from the API');
}


$content = $message['content'];
if (is_string($content)) {
return $content;
}

if ($content === null) {
return '';
}

if (! is_array($content)) {
throw new \Exception('Invalid response format received from the API');
}

$text = '';
foreach ($content as $part) {
if (is_string($part)) {
$text .= $part;

continue;
}

if (! is_array($part)) {
continue;
}

if (isset($part['text']) && is_string($part['text'])) {
$text .= $part['text'];

continue;
}

if (
isset($part['text']) &&
is_array($part['text']) &&
isset($part['text']['value']) &&
is_string($part['text']['value'])
) {
$text .= $part['text']['value'];
}
}

return $text;
}

/**
* @return array<string, mixed>
*/
Expand Down
142 changes: 142 additions & 0 deletions src/Agents/Agent.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ class Agent

protected ?Schema $schema = null;

/**
* @var array<string, Tool>
*/
protected array $tools = [];

protected Adapter $adapter;

/**
Expand Down Expand Up @@ -97,6 +102,143 @@ public function getSchema(): ?Schema
return $this->schema;
}

public function addTool(
string $name,
callable $handler,
string $description = ''
): self {
$this->tools[$name] = new Tool($name, $handler, $description);

return $this;
}

public function setTool(Tool $tool): self
{
$this->tools[$tool->getName()] = $tool;

return $this;
}

public function removeTool(string $name): self
{
unset($this->tools[$name]);

return $this;
}

/**
* @return list<Tool>
*/
public function getTools(): array
{
return array_values($this->tools);
}

public function getTool(string $name): ?Tool
{
return $this->tools[$name] ?? null;
}

/**
* @param array<string, mixed> $arguments
*/
public function callTool(string $name, array $arguments = []): mixed
{
$tool = $this->getTool($name);
if ($tool === null) {
$resolvedName = $this->resolveToolName($name);
if ($resolvedName !== null) {
$tool = $this->getTool($resolvedName);
}
}

if ($tool === null) {
throw new \InvalidArgumentException('Tool not found: '.$name);
}

return $tool->run($arguments);
}

/**
* Short alias for addTool().
*/
public function tool(
string $name,
callable $handler,
string $description = ''
): self {
return $this->addTool($name, $handler, $description);
}

public function drop(string $name): self
{
return $this->removeTool($name);
}

/**
* @return list<Tool>
*/
public function tools(): array
{
return $this->getTools();
}

public function find(string $name): ?Tool
{
return $this->getTool($name);
}

/**
* @param array<string, mixed> $arguments
*/
public function call(string $name, array $arguments = []): mixed
{
return $this->callTool($name, $arguments);
}

protected function resolveToolName(string $name): ?string
{
if (empty($this->tools)) {
return null;
}

$target = $this->canonicalToolName($name);
$matches = [];
foreach (array_keys($this->tools) as $candidate) {
if ($this->canonicalToolName($candidate) === $target) {
$matches[] = $candidate;
}
}

if (count($matches) === 1) {
return $matches[0];
}

return null;
}

protected function canonicalToolName(string $name): string
{
$canonical = strtolower(trim($name));
foreach (['get_', 'fetch_', 'tool_'] as $prefix) {
if (str_starts_with($canonical, $prefix)) {
$canonical = substr($canonical, strlen($prefix));
break;
}
}

$normalized = '';
$length = strlen($canonical);
for ($i = 0; $i < $length; $i++) {
$char = $canonical[$i];
if (($char >= 'a' && $char <= 'z') || ($char >= '0' && $char <= '9')) {
$normalized .= $char;
}
}

return $normalized;
}

/**
* Set the agent's schema
*/
Expand Down
Loading
Loading