Data source: AI
1Presentation
The \Temma\Datasources\Ai data source provides a unified interface to query language models (LLMs) from various providers: OpenAI, Claude (Anthropic), Gemini (Google), Mistral, OpenRouter, Ollama, as well as any OpenAI-compatible service.
For complete documentation (attachments, JSON output, multi-turn conversation, OpenAI-compatible services), see the dedicated artificial intelligence page.
If you have correctly configured the connection parameters, Temma automatically creates an object of type \Temma\Datasources\Ai. By convention, we'll assume that you've named this connection ai in the etc/temma.php file (see configuration documentation).
In controllers, the connection is available by writing:
$ai = $this->ai;
In other objects managed by the dependency injection component, the connection is accessible by writing:
$ai = $loader->dataSources->ai;
$ai = $loader->dataSources['ai'];
2Configuration
The connection DSN is written as:
ai://PROVIDER/MODEL#API_KEY
Built-in providers:
- openai: OpenAI (GPT-4o, etc.)
- claude: Anthropic Claude
- gemini: Google Gemini
- mistral: Mistral AI
- openrouter: OpenRouter (multi-model gateway)
- ollama: Ollama (local models, no API key required)
Configuration example in etc/temma.php:
<?php
return [
'application' => [
'dataSources' => [
'ai' => 'ai://openai/gpt-4o#sk-proj-xxxxxxxxxxxxx',
],
],
];
For an OpenAI-compatible service, use the endpoint URL in brackets:
ai://[https://api.groq.com/openai/v1/chat/completions]/llama-3.3-70b#gsk-XXX
3Unified calls
3.1Array-like access
Returns a text response.
$response = $ai['What is the capital of France?'];
3.2read() method
Returns a raw text response.
// simple prompt
$response = $ai->read('What is the capital of France?');
// with a default value in case of error
$response = $ai->read('Translate to French: Hello', 'Bonjour');
3.3get() method
Automatically activates JSON mode and returns a decoded PHP array.
// the LLM is forced to respond in JSON
$data = $ai->get('List the 3 largest cities in France with their population');
// $data contains a PHP array
4Options
The read() and get() methods accept a third parameter $options:
- system: (string) System prompt.
- messages: (array) Conversation history.
- temperature: (float) Temperature (0 to 2).
- max_tokens: (int) Output token limit.
- attachments: (array) Attachments (images, audio, video, PDF).
- output: (string) Output format (alias or MIME type).
For full details on options, attachments, JSON output, and multi-turn conversations, see the full artificial intelligence documentation.
Example:
$response = $ai->read('Explain photosynthesis', null, [
'system' => 'You are a biology teacher. Answer concisely.',
'temperature' => 0.3,
'max_tokens' => 500,
]);