PHPackages                             focusbp/openai-response-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. focusbp/openai-response-php

ActiveLibrary[API Development](/categories/api)

focusbp/openai-response-php
===========================

OpenAI Responses API helper for PHP with function calling and vector store sync.

v0.1.5(6mo ago)02MITPHPPHP &gt;=7.3

Since Oct 28Pushed 6mo agoCompare

[ Source](https://github.com/focusbp/openai-response-php)[ Packagist](https://packagist.org/packages/focusbp/openai-response-php)[ RSS](/packages/focusbp-openai-response-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (7)Used By (0)

OpenAI Response PHP
===================

[](#openai-response-php)

A lightweight PHP library that wraps the OpenAI Responses API to provide:

- **Vector Store integration** (sync local text files into an OpenAI Vector Store and use them as context)
- **Function Calling support** (tool invocation with typed arguments)

This library is intended to be easy to drop into a simple PHP app, even on older environments.

Install
-------

[](#install)

You can install it via Composer:

```
composer require focusbp/openai-response-php
```

---

Features
--------

[](#features)

### 🧠 Vector Store Integration

[](#-vector-store-integration)

- Syncs a local directory of text files into an OpenAI Vector Store.
- Lets the model answer questions using that knowledge.

### 🔧 Function Calling

[](#-function-calling)

- Define tools (functions) in PHP and expose them to the model.
- The model can call your tools with structured arguments.
- Supports dependency injection via a controller object.

### 💬 Conversation Recording

[](#-conversation-recording)

- Conversation history (messages) can be persisted via `Recorder` implementations:
    - `SessionRecorder` (stores in `$_SESSION`)
    - `FileRecorder` (stores in local JSON files)

### 📡 Status Polling

[](#-status-polling)

- Includes a simple async-style status polling example using `status_poll.php` to report "what the AI is doing right now" to the frontend.

---

Requirements
------------

[](#requirements)

- **PHP**: 7.3+ (no typed properties required)
- **Extensions**: `cURL`, `json`
- **Web server**: Any server that can run PHP (Apache, nginx + PHP-FPM, etc.)
- **OpenAI API Key**

---

Quick Start
-----------

[](#quick-start)

This is the fastest way to see it working in a browser.

1. **Set your API key**

    Open `tests/config/config.php` and set your OpenAI API key:

    ```
    $apikey = 'sk-...';
    ```
2. **Deploy**

    Upload the entire `tests/` directory (and the project library) to a PHP-capable web server.
3. **Access the demo UI**

    Open `index.php` in your browser.
    The sample UI can answer:

    - questions about upcoming events (from the Vector Store)
    - weather questions (via Function Calling)

---

Vector Store Usage
------------------

[](#vector-store-usage)

### 1. Add source files

[](#1-add-source-files)

Put plain text files (or other supported text content) into the `vector_store/` directory.
For example:

```
vector_store/
  events.txt
  faq.txt
  company_info.txt

```

These files act as your "knowledge base."

### 2. Sync with OpenAI

[](#2-sync-with-openai)

From the sample UI (the test app in `tests/`), click:

**"Sync Vector Store"**

When you click that:

- The library will upload/sync the contents of `vector_store/` to the configured Vector Store in OpenAI.
- The Vector Store will then be used to ground answers.

If a Vector Store does not exist yet, the library can create one.
If it already exists, the library can update it.

---

Function Calling
----------------

[](#function-calling)

The library exposes a Function Calling interface so the model can decide to call your PHP functions as tools.

### 1. Create a tool

[](#1-create-a-tool)

Create a class in the `function_tools/` directory that implements `\focusbp\OpenAIResponsePhp\FunctionTool`.

Example (simplified):

```
class Weather implements \focusbp\OpenAIResponsePhp\FunctionTool {

    public function name(): string {
        return "weather";
    }

    public function description(): string {
        return "Returns a weather forecast.";
    }

    public function parameters(): array {
        return [
            'type' => 'object',
            'properties' => [
                'city' => [
                    'type' => 'string',
                    'description' => 'Name of the city to get the weather for (e.g. "Tokyo", "Osaka")',
                ],
            ],
            'required' => ['city'],
            'additionalProperties' => false,
        ];
    }

    public function execute(\focusbp\OpenAIResponsePhp\Controller $ctl, array $arguments) {
        $city = isset($arguments['city']) ? (string)$arguments['city'] : '';

        if ($city === '') {
            return [
                'ok'    => false,
                'error' => 'Missing required argument "city".',
            ];
        }

        // Demo implementation
        return [
            'ok'       => true,
            'city'     => $city,
            'forecast' => 'Sunny',
        ];
    }
}
```

### 2. Dependency injection via Controller

[](#2-dependency-injection-via-controller)

If your tool needs shared services like:

- database connections
- HTTP clients
- config

…you can create your own class that **extends** `\focusbp\OpenAIResponsePhp\Controller` and put those dependencies there.

Then, when you instantiate the `OpenAI` client, pass that controller instance into the constructor.

Inside `execute()`, you’ll receive that same `$ctl` instance, so you can do things like `$ctl->db->query(...)` or `$ctl->weatherApi->fetch(...)`.

### 3. Auto-loading

[](#3-auto-loading)

Any class you put in `function_tools/` that implements `FunctionTool` will be auto-discovered and made available to the model.

---

Conversation &amp; Status
-------------------------

[](#conversation--status)

### Message history

[](#message-history)

The library keeps a running conversation history (system / user / assistant / tool messages).
This can be persisted using a `Recorder`:

- `SessionRecorder` keeps messages in `$_SESSION`.
- `FileRecorder` can write JSON logs to disk.

Both provide:

- `read()`
- `write()`
- `append()`

### Status polling

[](#status-polling)

The sample UI calls `status_poll.php` on an interval and displays a short status string (e.g. “fetching vector store…”).
This status string is stored via a `StatusManager` implementation.

Example implementation:

- `SessionStatusManager` stores a `_status_msg` value in `$_SESSION`.

---

Logging
-------

[](#logging)

All request/response logs and debug output can be written to the `log/` directory.

If you’re debugging or auditing model behavior:

- Check the generated files in `log/`.
- You can also wire up a `FileRecorder` so you have a full transcript.

---

Project Structure (reference)
-----------------------------

[](#project-structure-reference)

Below is a typical layout to help you navigate:

```
/ (project root)
├─ src/
│  ├─ OpenAI.php                # Main wrapper class
│  ├─ Controller.php            # Base controller for dependency injection
│  ├─ Recorder.php              # Interface for saving conversation history
│  ├─ SessionRecorder.php       # Recorder using $_SESSION
│  ├─ FileRecorder.php          # Recorder using local JSON files
│  ├─ StatusManager.php         # Interface for run status tracking
│  ├─ SessionStatusManager.php  # Session-based StatusManager
│  └─ ... other core classes ...
│
├─ function_tools/
│  ├─ Weather.php               # Example FunctionTool implementation
│  └─ ... your tools ...
│
├─ vector_store/
│  └─ *.txt                     # Knowledge base files to sync
│
├─ log/
│  └─ *.log                     # Logs and conversation transcripts
│
├─ tests/
│  ├─ index.php                 # Browser demo UI
│  ├─ status_poll.php           # Polling endpoint for status
│  └─ style.css                 # Simple chat UI styling
│
└─ README.md

```

---

Demo Flow (What the sample UI does)
-----------------------------------

[](#demo-flow-what-the-sample-ui-does)

1. You open `tests/index.php` in your browser.
2. You see a chat-like interface.
3. You ask something like:
    - “What upcoming events are there?”
    - “What’s the weather tomorrow in Tokyo?”
4. Under the hood:
    - For event questions, it retrieves knowledge from the synced Vector Store.
    - For weather questions, it calls the `Weather` tool via Function Calling.
5. The UI polls `status_poll.php` so you can see status text like “Start AI Processing...” or other internal messages.

---

Security Notes
--------------

[](#security-notes)

- Do not expose your API key publicly.
    `tests/index.php` is for local or protected testing.
- Vector Store content is sent to OpenAI.
    Do not sync files that contain secrets, PII, or anything you’re not comfortable sending to an API.
- Logs may contain both user input and model output.

---

License
-------

[](#license)

Add your preferred license here (MIT, Apache-2.0, etc.).

---

Contributing
------------

[](#contributing)

Pull requests and issues are welcome.
If you add new tools or storage backends (e.g. RedisRecorder, DatabaseStatusManager), please include minimal usage docs in your PR so others can learn from it.

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance66

Regular maintenance activity

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity24

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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

6

Last Release

197d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/bf5cb0d5e613ad46dc914d666adc87374aee859706e17fb7c845342c5b47d327?d=identicon)[focusbp](/maintainers/focusbp)

---

Top Contributors

[![focusbp](https://avatars.githubusercontent.com/u/143786363?v=4)](https://github.com/focusbp "focusbp (8 commits)")

---

Tags

function-callingopenaiopenai-apiphpvector-store

### Embed Badge

![Health badge](/badges/focusbp-openai-response-php/health.svg)

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

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

4.0k143.3M480](/packages/stripe-stripe-php)[twilio/sdk

A PHP wrapper for Twilio's API

1.6k92.9M272](/packages/twilio-sdk)[knplabs/github-api

GitHub API v3 client

2.2k15.8M187](/packages/knplabs-github-api)[facebook/php-business-sdk

PHP SDK for Facebook Business

90821.9M34](/packages/facebook-php-business-sdk)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

74513.7M114](/packages/meilisearch-meilisearch-php)[google/gax

Google API Core for PHP

265103.1M454](/packages/google-gax)

PHPackages © 2026

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