PHPackages                             ljguo-latex/openai-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. ljguo-latex/openai-php

ActiveLibrary[API Development](/categories/api)

ljguo-latex/openai-php
======================

A PHP client for the OpenAI API with support for custom URL, API key, and model.

2.2.0(3w ago)013↓100%MITPHPPHP ^8.1

Since May 12Pushed 3w agoCompare

[ Source](https://github.com/ljguo-latex/openai-php)[ Packagist](https://packagist.org/packages/ljguo-latex/openai-php)[ Docs](https://github.com/ljguo-latex/openai-php)[ RSS](/packages/ljguo-latex-openai-php/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (4)Versions (5)Used By (0)

openai-php
==========

[](#openai-php)

适用于 OpenAI API 的轻量级 PHP 客户端，支持链式调用、流式输出，以及自定义接口地址、API Key 和默认模型。可无缝对接 OpenAI、Azure OpenAI、本地模型（如 Ollama）等任何兼容端点。

环境要求
----

[](#环境要求)

- PHP 8.1+
- Composer

安装
--

[](#安装)

```
composer require ljguo-latex/openai-php
```

快速开始
----

[](#快速开始)

```
use OpenAI\OpenAI;

$client = OpenAI::client(
    apiKey: 'sk-...',
    baseUrl: 'https://api.openai.com/v1', // 可选，默认值
    defaultModel: 'gpt-4o',               // 可选
);

$response = $client->chat()
    ->message('法国的首都是哪里？')
    ->send();

echo $response->content(); // "巴黎"
```

对话补全（Chat）
----------

[](#对话补全chat)

### 普通请求

[](#普通请求)

```
$response = $client->chat()
    ->model('gpt-4o')
    ->system('你是一个有用的助手。')
    ->message('PHP 是什么？')
    ->temperature(0.7)
    ->maxTokens(512)
    ->send();

echo $response->content();
echo $response->finishReason(); // "stop"
echo $response->usage->totalTokens;
```

### 多轮对话

[](#多轮对话)

```
$response = $client->chat()
    ->system('你是一个有用的助手。')
    ->user('我叫小明。')
    ->assistant('你好，小明！')
    ->user('我叫什么名字？')
    ->send();

echo $response->content(); // "你叫小明。"
```

### 流式输出

[](#流式输出)

```
$client->chat()
    ->model('gpt-4o')
    ->message('写一首关于春天的诗')
    ->stream(function (string $chunk) {
        echo $chunk;
        ob_flush();
        flush();
    });
```

### 流式输出获取 token 用量

[](#流式输出获取-token-用量)

```
use OpenAI\Responses\UsageResponse;

$client->chat()
    ->model('gpt-4o')
    ->message('写一首关于春天的诗')
    ->stream(function (string $chunk, ?UsageResponse $usage = null) {
        echo $chunk;

        if ($usage !== null) {
            echo "\nPrompt tokens: " . $usage->promptTokens;
            echo "\nCompletion tokens: " . $usage->completionTokens;
            echo "\nTotal tokens: " . $usage->totalTokens;
        }
    });
```

### 其他链式方法

[](#其他链式方法)

方法说明`model(string)`指定模型`system(string)`添加 system 消息`user(string)`添加 user 消息`assistant(string)`添加 assistant 消息`message(string)``user()` 的别名`withMessages(array)`批量设置消息数组`temperature(float)`采样温度，默认 `1.0``maxTokens(int)`最大 token 数`option(string, mixed)`设置任意额外参数文本补全（Completions）
-----------------

[](#文本补全completions)

```
// 普通请求
$response = $client->completions()
    ->model('gpt-3.5-turbo-instruct')
    ->prompt('从前有座山')
    ->temperature(0.8)
    ->maxTokens(100)
    ->send();

echo $response->text();

// 流式输出
$client->completions()
    ->prompt('从前有座山')
    ->stream(function (string $chunk, ?\OpenAI\Responses\UsageResponse $usage = null) {
        echo $chunk;

        if ($usage !== null) {
            echo "\nTotal tokens: " . $usage->totalTokens;
        }
    });
```

向量嵌入（Embeddings）
----------------

[](#向量嵌入embeddings)

```
// 单条输入
$response = $client->embeddings()
    ->model('text-embedding-3-small')
    ->input('你好，世界！')
    ->send();

$vector = $response->embedding(); // float[]

// 多条输入
$response = $client->embeddings()
    ->input(['Hello', 'World'])
    ->send();

foreach ($response->data as $item) {
    echo "第 {$item->index} 条：" . count($item->embedding) . " 维\n";
}
```

模型列表（Models）
------------

[](#模型列表models)

```
// 列出所有可用模型
$list = $client->models()->list();
print_r($list->ids()); // ['gpt-4o', 'gpt-3.5-turbo', ...]

// 获取指定模型详情
$model = $client->models()->retrieve('gpt-4o');
echo $model->id;
echo $model->ownedBy;
```

自定义 / 兼容端点
----------

[](#自定义--兼容端点)

只需修改 `baseUrl` 即可对接任何 OpenAI 兼容 API：

```
$client = OpenAI::client(
    apiKey:       'local-key',
    baseUrl:      'http://localhost:11434/v1',
    defaultModel: 'llama3',
);
```

错误处理
----

[](#错误处理)

```
use OpenAI\Exceptions\ApiException;

try {
    $response = $client->chat()->message('你好')->send();
} catch (ApiException $e) {
    echo $e->getMessage();    // API 错误信息
    echo $e->getStatusCode(); // HTTP 状态码

    if ($e->isRateLimitError()) {
        // 处理 429 限流
    } elseif ($e->isAuthenticationError()) {
        // 处理 401 认证失败
    } elseif ($e->isServerError()) {
        // 处理 5xx 服务端错误
    }
}
```

直接实例化客户端
--------

[](#直接实例化客户端)

```
use OpenAI\Client;

$client = new Client(
    apiKey:       'sk-...',
    baseUrl:      'https://api.openai.com/v1',
    defaultModel: 'gpt-4o',
    timeout:      60,
    httpOptions:  [], // Guzzle 配置项
);
```

运行测试
----

[](#运行测试)

```
composer install
composer test
```

开源协议
----

[](#开源协议)

MIT

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance94

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

4

Last Release

26d ago

Major Versions

v1.0.0 → v2.0.02026-05-12

### Community

Maintainers

![](https://www.gravatar.com/avatar/8292be8e27d63c7dbccd955772544b6757df3d98df8331185a2dd49bad27cc60?d=identicon)[ljguo-latex](/maintainers/ljguo-latex)

---

Tags

apiclientaiopenaichatllmgpt

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ljguo-latex-openai-php/health.svg)

```
[![Health](https://phpackages.com/badges/ljguo-latex-openai-php/health.svg)](https://phpackages.com/packages/ljguo-latex-openai-php)
```

###  Alternatives

[openai-php/client

OpenAI PHP is a supercharged PHP API client that allows you to interact with the Open AI API

5.8k26.1M293](/packages/openai-php-client)[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.7k371.6k5](/packages/theodo-group-llphant)[deepseek-php/deepseek-php-client

deepseek PHP client is a robust and community-driven PHP client library for seamless integration with the Deepseek API, offering efficient access to advanced AI and data processing capabilities.

46684.5k5](/packages/deepseek-php-deepseek-php-client)[mozex/anthropic-laravel

Laravel integration for the Anthropic API: facade, config publishing, install command, testing fakes, messages, streaming, tool use, thinking, and batches.

72287.1k1](/packages/mozex-anthropic-laravel)[mozex/anthropic-php

PHP client for the Anthropic API: messages, streaming, tool use, thinking, web search, code execution, batches, and more.

49480.9k16](/packages/mozex-anthropic-php)[telnyx/telnyx-php

Official Telnyx PHP SDK — APIs for Voice, SMS, MMS, WhatsApp, Fax, SIP Trunking, Wireless IoT, Call Control, and more. Build global communications on Telnyx's private carrier-grade network.

35729.6k2](/packages/telnyx-telnyx-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
