Ollama PHP Library
Это библиотека PHP для Ollama. Ollama - это проект с открытым исходным кодом, который служит мощной и удобной платформой для запуска LLM на локальной машине. Он служит мостом между сложностями технологии LLM и стремлением к доступному и настраиваемому опыту ИИ.
Оригинал https://github.com/ArdaGnsrn/ollama-php
Начало
Требует PHP 8.1+
Требует Ollama
Официальные документы Ollama вы можете найти здесь.
Перевод документации находится тут.
Установите Ollama PHP через менеджер пакетов Composer:
composer require ardagnsrn/ollama-php
Затем вы можете создать новый экземпляр клиента Ollama:
// with default base URL
$client = \ArdaGnsrn\Ollama\Ollama::client();
// or with custom base URL
$client = \ArdaGnsrn\Ollama\Ollama::client('http://localhost:11434');
Использование
Ресурс Completions
create
Генерировать ответ для заданной подсказки с предоставленной моделью.
$completions = $client->completions()->create([
'model' => 'llama3.1',
'prompt' => 'Once upon a time',
]);
$completions->response; // '...in a land far, far away...'
$response->toArray(); // ['model' => 'llama3.1', 'response' => '...in a land far, far away...', ...]
createStreamed
Создать ответ для данного запроса с помощью предоставленной модели и потоковой реакции.
$completions = $client->completions()->createStreamed([
'model' => 'llama3.1',
'prompt' => 'Once upon a time',
]);
foreach ($completions as $completion) {
echo $completion->response;
}
// 1. Iteration: '...in'
// 2. Iteration: ' a'
// 3. Iteration: ' land'
// 4. Iteration: ' far,'
// ...
Ресурс Chat
create
Создать ответ для данного запроса с помощью предоставленной модели.
$response = $client->chat()->create([
'model' => 'llama3.1',
'messages' => [
['role' => 'system', 'content' => 'You are a llama.'],
['role' => 'user', 'content' => 'Hello!'],
['role' => 'assistant', 'content' => 'Hi! How can I help you today?'],
['role' => 'user', 'content' => 'I need help with my taxes.'],
],
]);
$response->message->content; // 'Ah, taxes... *chew chew* Hmm, not really sure how to help with that.'
$response->toArray(); // ['model' => 'llama3.1', 'message' => ['role' => 'assistant', 'content' => 'Ah, taxes...'], ...]
Кроме того, вы можете использовать параметр tools для предоставления пользовательских функций чату. Параметр tools нельзя использовать с помощью метода createStreamed.
$response = $client->chat()->create([
'model' => 'llama3.1',
'messages' => [
['role' => 'user', 'content' => 'What is the weather today in Paris?'],
],
'tools' => [
[
'type' => 'function',
'function' => [
'name' => 'get_current_weather',
'description' => 'Get the current weather',
'parameters' => [
'type' => 'object',
'properties' => [
'location' => [
'type' => 'string',
'description' => 'The location to get the weather for, e.g. San Francisco, CA',
],
'format' => [
'type' => 'string',
'description' => 'The location to get the weather for, e.g. San Francisco, CA',
'enum' => ['celsius', 'fahrenheit']
],
],
'required' => ['location', 'format'],
],
],
]
]
]);
$toolCall = $response->message->toolCalls[0];
$toolCall->function->name; // 'get_current_weather'
$toolCall->function->arguments; // ['location' => 'Paris', 'format' => 'celsius']
$response->toArray(); // ['model' => 'llama3.1', 'message' => ['role' => 'assistant', 'toolCalls' => [...]], ...]
createStreamed
Сгенерировать ответ на заданное приглашение с помощью предоставленной модели и передать его в потоковом режиме.
$responses = $client->chat()->createStreamed([
'model' => 'llama3.1',
'messages' => [
['role' => 'system', 'content' => 'You are a llama.'],
['role' => 'user', 'content' => 'Hello!'],
['role' => 'assistant', 'content' => 'Hi! How can I help you today?'],
['role' => 'user', 'content' => 'I need help with my taxes.'],
],
]);
foreach ($responses as $response) {
echo $response->message->content;
}
// 1. Iteration: 'Ah,'
// 2. Iteration: ' taxes'
// 3. Iteration: '... '
// 4. Iteration: ' *chew,'
// ...
Ресурс Models
list
Перечислить все доступные модели.
$response = $client->models()->list(); $response->toArray(); // ['models' => [['name' => 'llama3.1', ...], ['name' => 'llama3.1:80b', ...], ...]]
show
Показать подробную информацию о конкретной модели.
$response = $client->models()->show('llama3.1');
$response->toArray(); // ['modelfile' => '...', 'parameters' => '...', 'template' => '...']
create
Создать новую модель.
$response = $client->models()->create([
'name' => 'mario',
'modelfile' => "FROM llama3.1\nSYSTEM You are mario from Super Mario Bros."
]);
$response->status; // 'success'
createStreamed
Создать новую модель и передать ответ в потоковом режиме.
$responses = $client->models()->createStreamed([
'name' => 'mario',
'modelfile' => "FROM llama3.1\nSYSTEM You are mario from Super Mario Bros."
]);
foreach ($responses as $response) {
echo $response->status;
}
copy
Скопировать существующую модель.
$client->models()->copy('llama3.1', 'llama3.2'); // bool
delete
Удалить модель.
$client->models()->delete('mario'); // bool
pull
Извлечь модель с сервера Ollama.
$response = $client->models()->pull('llama3.1');
$response->toArray() // ['status' => 'downloading digestname', 'digest' => 'digestname', 'total' => 2142590208, 'completed' => 241970]
pullStreamed
Извлечь модель с сервера Ollama и передать ответ в потоковом режиме.
$responses = $client->models()->pullStreamed('llama3.1');
foreach ($responses as $response) {
echo $response->status;
}
push
Отправить модель на сервер Ollama.
$response = $client->models()->push('llama3.1');
$response->toArray() // ['status' => 'uploading digestname', 'digest' => 'digestname', 'total' => 2142590208]
pushStreamed
Отправить модель на сервер Ollama и передать ответ в потоковом режиме.
$responses = $client->models()->pushStreamed('llama3.1');
foreach ($responses as $response) {
echo $response->status;
}
runningList
Перечислить все работающие модели.
$response = $client->models()->runningList(); $response->toArray(); // ['models' => [['name' => 'llama3.1', ...], ['name' => 'llama3.1:80b', ...], ...]]
Ресурс Blobs
exists
Проверить, существует ли blob.
$client->blobs()->exists('blobname'); // bool
Где: blobname - ожидаемый дайджест файла по протоколу SHA256
Например:
$client->blobs()->exists('sha256:29fdb92e57cf0827ded04ae6461b5931d01fa595843f55d36f5b275a52087dd2');
create
Создать новый blob.
$client->blobs()->create('blobname'); // bool
Где: blobname - ожидаемый дайджест файла по протоколу SHA256
Например:
$client->blobs()->create('sha256:29fdb92e57cf0827ded04ae6461b5931d01fa595843f55d36f5b275a52087dd2');
Ресурс Embed (Встраивание)
create
Создать встраивание для заданного текста с помощью предоставленной модели.
$response = $client->embed()->create([
'model' => 'llama3.1',
'input' => [
"Why is the sky blue?",
]
]);
$response->toArray(); // ['model' => 'llama3.1', 'embedding' => [0.1, 0.2, ...], ...]
Тестирование
composer test