PHP code example of adt / ai-chat

1. Go to this page and download the library: Download adt/ai-chat 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/ */

    

adt / ai-chat example snippets


new MercurePushPublisher(
    publishUrl: 'http://hub:8080/.well-known/mercure', // as the worker reaches it
    subscribeUrl: '/.well-known/mercure',              // as the browser reaches it
    publisherKey: $publisherKey, subscriberKey: $subscriberKey,
    topicPrefix: 'myapp/' . $tenant,
    issuer: 'https://myapp.example', audience: 'https://myapp.example/.well-known/mercure',
);

#[ORM\Entity]
class AiChatConversation implements ADT\AiChat\Entity\ConversationInterface
{
	use ADT\AiChat\Entity\ConversationTrait;

	#[ORM\ManyToOne(targetEntity: User::class)]
	public User $user;    // the owner, named by ChatOptions::$ownerField
	...
}

#[ORM\Entity]
class AiChatMessage implements ADT\AiChat\Entity\MessageInterface
{
	use ADT\AiChat\Entity\MessageTrait;

	#[ORM\ManyToOne(targetEntity: AiChatConversation::class)]
	protected ConversationInterface $conversation;    // ChatOptions::$conversationField
	...
}

#[ORM\Entity]
class AiChatAgent implements ADT\AiChat\Entity\AgentInterface
{
	use ADT\AiChat\Entity\AgentTrait;
	...
}

$chat = new ChatService($em, $client, $toolHandler, $queryExecutor, $provisioner,
	new BackgroundQueueMessageDispatcher($backgroundQueue),    // or your MessageDispatcher
	$piiFilter, $piiValueCollector,
	new ChatOptions(AiChatConversation::class, AiChatMessage::class, ownerField: 'user'),
);

$chat->setUserScope(function (?User $user, callable $turn) use ($securityUser): void {
    $user !== null ? $securityUser->runAs($user, $turn) : $turn(); // stateless, in memory
});

[$mapping, $created] = $provisioner->ensureProvisioned($schemaName);

// What ChatService::processQueuedMessage() does for you:
$runner = new AgentTurnRunner($client, $toolHandler, $provisioner->resolver($schemaName));

$result = $runner->run($conversation, $userMessage, function (?string $sessionId) use ($em): void {
	$em->flush();    // persist the session id as soon as it changes
});

$text = $piiFilter->filter($result->text, $piiValueCollector->collect($result->toolData));
// store $text + $result->toolData + $result->tokensInput/Output as a message

new ChatOptions(AiChatConversation::class, AiChatMessage::class,
	modelSelection: new ModelSelection(
		models: [
			'claude-sonnet-5-5' => ['label' => 'Claude Sonnet 5.5', 'contextWindowTokens' => 1000000],
			'claude-opus-5-5' => ['label' => 'Claude Opus 5.5', 'contextWindowTokens' => 1000000],
		],
		efforts: ['medium', 'high', 'max'],    // [] = send none, the model default
		defaultModel: 'claude-sonnet-5-5',     // null = the first model
		defaultEffort: 'high',
	),
);

// POST conversationId, rating ('1', '-1' or '' to clear), comment
$rating = $request->getPost('rating');
$response = $endpoint->rate($owner, $conversationId, $rating !== '' && $rating !== null ? (int) $rating : null, $request->getPost('comment'));

#[ORM\ManyToOne(targetEntity: User::class)]
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
protected ?User $sender = null;

$endpoint->setSenderFormatter(fn(User $user): string => $user->getName());

// the owner's conversation, written by the signed-in colleague
$endpoint->send($owner, $id, $text, $uploads, $model, $effort, sender: $me);
// readOnly false = may write, canManage false = may not rate or delete
$endpoint->conversations($owner, false, $owner === $me);
$endpoint->load($owner, $id, false, $owner === $me, viewer: $me);
$endpoint->poll($owner, $id, $afterId, viewer: $me);

$file = $client->uploadFile('export.csv', $contents, 'text/plain');

$result = $runner->run($conversation, $userMessage, $persist, [
    new Attachment($file['id'], 'text/plain', 'export.csv'),
]);

$tools = new CompositeToolExecutor($toolHandler, [new MonthlyReportTool(...)]);
// to ChatService and AgentProvisioner instead of $toolHandler (the agent is updated
// on the next session) and/or to the McpServer

$download = $endpoint->export($owner, $conversationId, $messageId, $token) ?? throw new NotFound;
foreach ($download->getHeaders() as $name => $value) { header("$name: $value"); }
$download->stream();

$server = new McpServer(
    $toolHandler,                       // the same ToolExecutor the chat uses
    new PiiResponseFilter(),            // applied to every string of every tool result
    serverName: 'my-app',
    serverVersion: '1.0.0',
    instructions: McpServer::DEFAULT_INSTRUCTIONS, // shown to the client model
    logger: $auditLogger,               // one info record per tool call
);

// in your controller, AFTER authenticating the caller:
$response = $server->handle($request->getMethod(), $request->getBody(), ['user' => $userId]);
// -> $response->status, $response->headers, $response->body (null = no body)

// your token entity: implements Mcp\McpToken, uses Mcp\McpTokenTrait (name, token_hash,
// expires_at, last_used_at) + its own id, owner association and creation time
$endpoint = new McpEndpoint($server, new McpTokenAuthenticator($em, McpTokenEntity::class, $policy));

// in the controller (no session, no CSRF, no sign-in redirect):
$response = $endpoint->handle($request->getMethod(), $request->getHeader('Authorization'), $request->getBody());

#[ORM\Entity]
#[ORM\UniqueConstraint(name: 'uniq_ai_pseudonym_anchor', columns: ['conversation_id', 'anchor'])]
class AiPseudonym implements PseudonymInterface
{
	use PseudonymTrait;    // anchor VARCHAR(40), value TEXT

	#[ORM\ManyToOne(targetEntity: AiChatConversation::class)]
	#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
	protected ConversationInterface $conversation;
	...
}

final class ClientResolver implements PiiSubjectResolver
{
	public function resolve(PiiFinding $finding): int|string|null
	{
		$ids = match ($finding->kind) {
			PiiFinding::EMAIL => $this->clients->idsByEmail($finding->text),
			PiiFinding::NAME => $this->clients->idsByName($finding->firstName, $finding->lastName),
			default => [],
		};
		return count($ids) === 1 ? $ids[0] : null;
	}

	public function isReadable(PiiFinding $finding): bool { return $this->staff->has($finding); }
	public function findInText(string $text): array { return []; }
	public function label(int|string $subject): ?string { return $this->clients->get($subject)?->getFullName(); }
}

$pseudonymizer = new Pseudonymizer(
	$em,
	AiPseudonym::class,
	new OpenAiCompatiblePiiDetector($url, 'qwen3', apiKey: $key,