Overview
TheMagic::ask() method provides the simplest way to get answers from an LLM. It’s perfect for straightforward questions that require a concise response.
Basic Usage
Ask a simple question
The most basic usage returns a string answer:By default,
Magic::ask() returns a full sentence response.Get concise answers
For short, direct answers without full sentences, set the
$sentence parameter to false:Structured Data Extraction
You can also extract structured data by providing a JSON schema:When using a custom schema, the response is automatically structured according to your schema definition.
Schema Type Options
The$schema parameter accepts standard JSON Schema types:
string- Default, returns a text responseinteger- Returns a numeric valueboolean- Returns true/falsearray- Returns an array of itemsobject- Returns a structured object
Example: Extracting Numbers
Example: Extracting Arrays
How It Works
Under the hood,Magic::ask() from src/Magic.php:50:
- Creates a chat session with optimized system instructions
- Uses the
extracttool to enforce the output schema - Configures response style based on the
$sentenceparameter - Returns the extracted value directly
Best Practices
When to use Magic::ask()
When to use Magic::ask()
- Quick factual questions
- Simple data extraction
- One-off LLM queries
- Prototyping and testing
When to use Magic::chat()
When to use Magic::chat()
- Multi-turn conversations
- Complex interactions requiring tools
- Streaming responses
- Custom message history
Related Methods
- Magic::function() - For type-safe function-like LLM calls (src/Magic.php:117)
- Magic::chat() - For full conversational interactions
- Magic::extract() - For document extraction with custom strategies
Next Steps
Multimodal Chat
Learn to chat with images using Step\Image
Document Extraction
Extract structured data from documents