lucianatonet/groq-php

访问 Groq REST API 的 PHP 库

0.0.9 2024-09-07 01:37 UTC

This package is auto-updated.

Last update: 2024-09-19 03:23:38 UTC


README

Groq PHP

Version Total Downloads License

一个强大的 PHP 库,用于无缝集成 Groq API。此库简化了与 Groq 的交互,使开发者能够轻松利用其高级语言模型、音频处理和视觉功能。

在 Laravel 中使用?请查看: GroqLaravel

安装

composer require lucianotonet/groq-php

配置

Groq 控制台 获取您的 API 密钥并将其设置为环境变量

GROQ_API_KEY=your_key_here

用法

初始化 Groq 客户端

use LucianoTonet\GroqPHP\Groq;

$groq = new Groq();

列出模型

检索可用的模型列表

$models = $groq->models()->list();

foreach ($models['data'] as $model) {
    echo 'Model ID: ' . $model['id'] . PHP_EOL;
    echo 'Developer: ' . $model['owned_by'] . PHP_EOL;
    echo 'Context Window: ' . $model['context_window'] . PHP_EOL;
}

聊天功能

基本聊天

发送聊天完成请求

$response = $groq->chat()->completions()->create([
    'model' => 'llama3-8b-8192',
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Explain the importance of low latency LLMs'
        ]
    ],
]);

echo $response['choices'][0]['message']['content'];

流式聊天

流式传输聊天完成响应

$response = $groq->chat()->completions()->create([
    'model' => 'mixtral-8x7b-32768',
    'messages' => [
        [
            'role' => 'user',
            'content' => $message
        ]
    ],
    'stream' => true
]);

foreach ($response->chunks() as $chunk) {
    if (isset($chunk['choices'][0]['delta']['content'])) {
        echo $chunk['choices'][0]['delta']['content'];
        ob_flush();
        flush();
    }
}

工具调用

在聊天完成中使用工具

$tools = [
    [
        "type" => "function",
        "function" => [
            "name" => "calendar_tool",
            "description" => "Gets the current time in a specific format.",
            "parameters" => [
                "type" => "object",
                "properties" => [
                    "format" => [
                        "type" => "string",
                        "description" => "The format of the time to return."
                    ],
                ],
                "required" => ["format"],
                "default" => ["format" => "d-m-Y"]
            ],
        ]
    ],
    [
        "type" => "function",
        "function" => [
            "name" => "weather_tool",
            "description" => "Gets the current weather conditions of a location.",
            "parameters" => [
                "type" => "object",
                "properties" => [
                    "location" => [
                        "type" => "string",
                        "description" => "Location to get weather information."
                    ],
                ],
                "required" => ["location"],
                "default" => ["location" => "New York"]
            ],
        ]
    ],
    // Other tools...
];

// First inference...
 // Start of Selection
$response = $groq->chat()->completions()->create([
    'model' => 'mixtral-8x7b-32768',
    'messages' => $messages,
    "tool_choice" => "auto",
    "tools" => $tools
]);

foreach ($response['choices'][0]['message']['tool_calls'] as $tool_call) {
    $function_args = json_decode($tool_call['function']['arguments'], true);
    
    // Call the tool...
    $function_name = $tool_call['function']['name'];
    if (function_exists($function_name)) {
        $function_response = $function_name($function_args);
    } else {
        $function_response = "Function $function_name not defined.";
    }

    $messages[] = [
        'tool_call_id' => $tool_call['id'],
        'role' => 'tool',
        'name' => $function_name,
        'content' => $function_response,
    ];
}

// Build final response...
$response = $groq->chat()->completions()->create([
    'model' => 'mixtral-8x7b-32768',
    'messages' => $messages
]);


echo $response['choices'][0]['message']['content'];

JSON 模式

请求 JSON 对象作为响应格式

use LucianoTonet\GroqPHP\GroqException;

try {
    $response = $groq->chat()->completions()->create([
        'model' => 'mixtral-8x7b-32768',
        'messages' => [
            [
                'role' => 'system',
                'content' => "You are an API and shall respond only with valid JSON.",
            ],
            [
                'role' => 'user',
                'content' => 'Explain the importance of low latency LLMs',
            ],
        ],
        'response_format' => ['type' => 'json_object']
    ]);

    $jsonResponse = json_decode($response['choices'][0]['message']['content'], true);

    // Accessing the JSON response
    print_r($jsonResponse); 

} catch (GroqException $err) {
    echo $err->getCode() . "<br>"; 
    echo $err->getMessage() . "<br>";    
    echo $err->getType() . "<br>";           

    if($err->getFailedGeneration()) {
        print_r($err->getFailedGeneration());
    }
}

音频转录

转录音频内容

$transcription = $groq->audio()->transcriptions()->create([
    'file' => '/path/to/audio/file.mp3',
    'model' => 'whisper-large-v3',
    'response_format' => 'json',
    'language' => 'en',
    'prompt' => 'Optional transcription prompt'
]);

echo json_encode($transcription, JSON_PRETTY_PRINT);

音频翻译

翻译音频内容

$translation = $groq->audio()->translations()->create([
    'file' => '/path/to/audio/file.mp3',
    'model' => 'whisper-large-v3',
    'response_format' => 'json',
    'prompt' => 'Optional translation prompt'
]);

echo json_encode($translation, JSON_PRETTY_PRINT);

视觉功能

使用提示分析图像

$analysis = $groq->vision()->analyze('/path/to/your/image.jpg', 'Describe this image');

echo $analysis['choices'][0]['message']['content'];

错误处理

优雅地处理潜在错误

use LucianoTonet\GroqPHP\GroqException;

try {
    $response = $groq->chat()->completions()->create([
        'model' => 'mixtral-8x7b-32768',
        'messages' => [
            [
                'role' => 'user',
                'content' => 'Hello, world!'
            ]
        ]
    ]);
} catch (GroqException $err) {
    echo "<strong>Error code:</strong> " . $err->getCode() . "<br>"; // e.g., 400
    echo "<strong>Message:</strong> " . $err->getMessage() . "<br>";    // Detailed error description
    echo "<strong>Type:</strong> " . $err->getType() . "<br>";           // e.g., invalid_request_error
    echo "<strong>Headers:</strong><br>"; 
    print_r($err->getHeaders()); // ['server' => 'nginx', ...]
}

超时

全局超时配置

为所有请求设置全局超时(以毫秒为单位)

$groq = new Groq([
    'timeout' => 20 * 1000, // 20 seconds
]);

请求特定超时

为特定请求指定超时(以毫秒为单位)

$groq->chat()->completions()->create([
    'model' => 'mixtral-8x7b-32768',
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Hello, world!'
        ]
    ],
], ['timeout' => 5 * 1000]); // 5 seconds

语义版本控制

此包遵循 SemVer 规范。然而,在不兼容的更改可能以次要版本发布的情况下

  1. 仅影响静态类型且不影响运行时行为的更改。
  2. 对内部库组件的修改,这些组件在技术上对公共,但不是用于外部使用。 (如果您依赖于此类内部组件,请提交 GitHub 问题)
  3. 在实际情况中预计不会影响大多数用户的更改。

需求

PHP version