PHPackages                             witness-sdk/php-sdk - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. witness-sdk/php-sdk

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

witness-sdk/php-sdk
===================

The PHP SDK for the Witness Application.

v0.1.1(1mo ago)00MITPHPPHP ^8.1

Since Jun 13Pushed 1mo agoCompare

[ Source](https://github.com/witness-sdk/php-sdk)[ Packagist](https://packagist.org/packages/witness-sdk/php-sdk)[ Docs](https://witness.sh)[ RSS](/packages/witness-sdk-php-sdk/feed)WikiDiscussions main Synced 1mo ago

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

This package does not work yet. Do not install until V1.
========================================================

[](#this-package-does-not-work-yet-do-not-install-until-v1)

Witness PHP SDK
===============

[](#witness-php-sdk)

The PHP SDK for the Witness Application.

Repository: [github.com/witness-sdk/php-sdk](https://github.com/witness-sdk/php-sdk)

Witness captures inference telemetry on a side channel: events are buffered in-process and delivered to [witness.sh](https://witness.sh) as a single batch at the end of the request. Your inference hot path is never blocked, and delivery failures never throw into your application — if ingestion is down, your models still answer.

Install
-------

[](#install)

```
composer require witness-sdk/php-sdk
```

Requires PHP 8.1+ with `ext-curl` and `ext-json`. No other dependencies.

Quickstart
----------

[](#quickstart)

```
use Witness\Witness;

Witness::init(['api_key' => 'w_live_...', 'project' => 'prod-chat']);

$client = Witness::watch(
    OpenAI::factory()
        ->withApiKey('gsk_...')
        ->withBaseUri('https://api.groq.com/openai/v1')
        ->make(),
    ['provider' => 'groq'],
);

$response = $client->chat()->create([
    'model' => 'llama-3.3-70b-versatile',
    'messages' => [['role' => 'user', 'content' => 'Hello']],
]);

// inference → your provider, direct
// telemetry → witness.sh, at request end
```

`Witness::watch()` wraps an OpenAI-compatible client instance in a transparent proxy — use the returned object in place of the original. Every `chat()->create()`, `embeddings()->create()`, `messages->create()`(Anthropic-style), and streaming call is traced automatically. Both method style (`$client->chat()->create()`) and property style (`$client->chat->completions->create()`) clients work.

> PHP cannot patch classes at runtime, so unlike the Python and Node SDKs (which patch the client class once), `watch()` wraps each instance. Provider is inferred from the client's base URL when it is exposed publicly; most PHP clients keep it private, so passing `['provider' => ...]` explicitly is recommended.

Prefer explicit control? Use `Witness::log()` instead:

```
$chat = Witness::log(
    fn (array $messages) => $client->chat()->create([
        'model' => 'llama-3.3-70b-versatile',
        'messages' => $messages,
    ]),
    ['provider' => 'groq'],
);

$response = $chat([['role' => 'user', 'content' => 'Hello']]);
```

`Witness::log()` wraps any callable that performs an inference call. It times the call, extracts `model` and token usage from the response by duck-typing (any OpenAI-compatible response shape works — objects, arrays, or `ArrayAccess`), and buffers an event. The wrapped callable's return value and exceptions pass through untouched — failed calls are recorded with `status: "error"` and re-thrown.

Provider and model are read from the response when possible; the options (`provider`, `model`, `operation`, `metadata`) fill in whatever the response cannot answer.

Opting out of telemetry
-----------------------

[](#opting-out-of-telemetry)

Skip reporting for specific calls:

```
// Callback scope — works with watch() and Witness::log()
Witness::ignore(fn () => $client->chat()->create([...]));

// Single call — watch() strips it before the provider sees it
$client->chat()->create(['model' => '...', 'messages' => [...], 'witness_ignore' => true]);
```

To keep only a fraction of events on high-volume paths, set a sample rate:

```
Witness::init(['api_key' => '...', 'project' => '...', 'sample_rate' => 0.1]); // keep ~10%
```

Configuration
-------------

[](#configuration)

`Witness::init()` accepts an options array:

KeyDefaultNotes`api_key``WITNESS_API_KEY` env varRequired (option or env)`project``WITNESS_PROJECT` env varRequired (option or env)`base_url``https://witness.sh/api/v1`Override for staging / self-hosted`queue_size``10000`Bounded in-memory event buffer`sample_rate``1.0`Fraction of calls to record (per-call decision)If no API key or project is configured, `init()` logs a warning and the SDK stays **disabled**: instrumented code runs normally and nothing is sent. Your observability layer never crashes your app over a missing env var.

`Witness::flush(timeout: 5.0)` delivers buffered events now and keeps running — useful in long-running workers (queue consumers, Octane, Swoole) where the request never "ends". `Witness::shutdown()` flushes and stops; a shutdown function is registered automatically by `init()`, so in classic request-per-process PHP you never need to call either one.

Delivery model
--------------

[](#delivery-model)

PHP is request-scoped with no background threads, so this SDK buffers events in memory (enqueueing is a plain array append) and posts them as one `{"events": [...]}` batch envelope when `flush()` or `shutdown()` runs — normally at the very end of the request, after your response is built. Failed deliveries are retried with backoff (bounded by the flush timeout), then dropped with a warning. Telemetry is never worth an exception.

Long-running workers should call `Witness::flush()` periodically (e.g. after each job) so events do not sit in memory for hours.

Privacy
-------

[](#privacy)

Witness sends **metadata only**: provider, model, latency, token counts, and status. Prompt and completion text are never transmitted.

Wire contract
-------------

[](#wire-contract)

The SDK posts `{"events": [...]}` batch envelopes to `POST {base_url}/events` with a `Bearer` API key. The full contract lives in [`schema/v1/event.json`](schema/v1/event.json) and is versioned via the `schema_version` field on every event.

Roadmap
-------

[](#roadmap)

- Non-blocking delivery via curl\_multi fire-and-forget
- Provider inference for clients that expose their base URL via config objects
- Time-to-last-token on streamed responses

Development
-----------

[](#development)

```
composer install
composer test
```

License
-------

[](#license)

MIT

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance90

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity34

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 ~0 days

Total

2

Last Release

46d ago

### Community

Maintainers

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

---

Top Contributors

[![Christopher-Law](https://avatars.githubusercontent.com/u/25482861?v=4)](https://github.com/Christopher-Law "Christopher-Law (6 commits)")

---

Tags

inferencetracingopenaitelemetryobservabilityllm

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/witness-sdk-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/witness-sdk-php-sdk/health.svg)](https://phpackages.com/packages/witness-sdk-php-sdk)
```

###  Alternatives

[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

326123.0k1](/packages/cognesy-instructor-php)[symfony/ai-platform

PHP library for interacting with AI platform provider.

521.4M300](/packages/symfony-ai-platform)[llm-agents/agents

LLM Agents PHP SDK - Autonomous Language Model Agents for PHP

16716.2k9](/packages/llm-agents-agents)[soukicz/llm

LLM client with support for cache, tools and async requests

4414.3k](/packages/soukicz-llm)

PHPackages © 2026

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