https://github.com/focusbp/openai-response-php
A lightweight utility for working with OpenAI Responses API and Vector Stores.
https://github.com/focusbp/openai-response-php
function-calling openai openai-api php vector-store
Last synced: 3 months ago
JSON representation
A lightweight utility for working with OpenAI Responses API and Vector Stores.
- Host: GitHub
- URL: https://github.com/focusbp/openai-response-php
- Owner: focusbp
- License: mit
- Created: 2025-10-28T17:29:18.000Z (6 months ago)
- Default Branch: main
- Last Pushed: 2025-10-28T21:03:45.000Z (6 months ago)
- Last Synced: 2025-10-28T21:25:40.764Z (6 months ago)
- Topics: function-calling, openai, openai-api, php, vector-store
- Language: PHP
- Homepage:
- Size: 32.2 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 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
You can install it via Composer:
```bash
composer require focusbp/openai-response-php
```
---
## Features
### π§ 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
- 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 history (messages) can be persisted via `Recorder` implementations:
- `SessionRecorder` (stores in `$_SESSION`)
- `FileRecorder` (stores in local JSON files)
### π‘ 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
- **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
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:
```php
$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
### 1. Add source files
Put plain text files (or other supported text content) into the `vector_store/` directory.
For example:
```text
vector_store/
events.txt
faq.txt
company_info.txt
```
These files act as your "knowledge base."
### 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
The library exposes a Function Calling interface so the model can decide to call your PHP functions as tools.
### 1. Create a tool
Create a class in the `function_tools/` directory that implements `\focusbp\OpenAIResponsePhp\FunctionTool`.
Example (simplified):
```php
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
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
Any class you put in `function_tools/` that implements `FunctionTool` will be auto-discovered and made available to the model.
---
## Conversation & Status
### 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
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
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)
Below is a typical layout to help you navigate:
```text
/ (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)
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
- 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
Add your preferred license here (MIT, Apache-2.0, etc.).
---
## 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.