The Chat API provides a fluent interface for building conversational AI applications. Create multi-turn conversations with support for text, images, tool calling, and streaming responses.
use Mateffy\Magic;use Mateffy\Magic\Chat\Messages\Step;$messages = Magic::chat() ->model('google/gemini-2.0-flash-lite') ->temperature(0.5) ->messages([ Step::user([ Step\Text::make('What is in this picture and where was it taken?'), Step\Image::make('https://example.com/eiffel-tower.jpg'), ]), Step::assistant([ Step\Text::make('The picture shows the Eiffel Tower, which is located in Paris, France.'), ]), Step::user('How much is a flight to Paris?'), ]) ->stream();
use Mateffy\Magic\Chat\Messages\Step;// Text onlyStep::user('Tell me about Paris');// Text with imageStep::user([ Step\Text::make('What is in this image?'), Step\Image::make('https://example.com/photo.jpg'),]);
Build conversations by passing an array of messages:
Magic::chat() ->messages([ Step::user('What is the weather in Paris?'), Step::assistant('Let me check that for you.'), Step::user('Thanks!'), ]) ->stream();
use Mateffy\Magic\Chat\ToolChoice;// Let the AI decide (default)Magic::chat() ->tools([/* ... */]) ->toolChoice(ToolChoice::Auto) ->stream();// Force a specific toolMagic::chat() ->tools(['extract' => /* ... */]) ->toolChoice('extract') ->stream();// Require any tool to be calledMagic::chat() ->tools([/* ... */]) ->forceTool(ToolChoice::Required) ->stream();
$messages = Magic::chat()->prompt('Hello')->stream();// First text message$firstText = $messages->firstText();// Last text message$lastText = $messages->lastText();// All text concatenated$allText = $messages->text();
// First tool call$toolCall = $messages->firstToolCallMessage();// First tool result$result = $messages->firstToolResultMessage();// Get the output$output = $result->output;
Magic::chat() ->prompt('Tell me a story') ->onMessage(function ($message) { // Called for each complete message logger()->info('New message', ['type' => get_class($message)]); }) ->onMessageProgress(function ($message) { // Called during streaming for each chunk echo $message->text(); }) ->stream();