OpenAI PHP Client

repository·main·Indexed 26 days ago

https://github.com/openai-php/client

A community-maintained PHP client for interacting with the OpenAI API. It provides structured access to resources including Chat, Audio, Embeddings, Images, Moderations, and FineTuning. The library supports PHP 8.2+ and offers features such as function calling, real-time streaming, and vector store management.

Tokens
14.1K
Snippets
40
Records
54
Agent score
41%

What's inside openai-php/client

  1. Manage Thread Runs (Deprecated)

    main

    WARNING: Deprecated API

    OpenAI has deprecated the Assistants API and it will stop working by August 26, 2026. Use the Responses API instead.

    Use the threads()->runs() resource to manage runs within a thread. This includes creating runs, retrieving run status, modifying metadata, and canceling active runs.

  2. Quickstart: Basic API Usage

    main

    To use the client, obtain your API key from OpenAI, initialize the client using OpenAI::client(), and call the desired resource method. The following example demonstrates creating a response using the responses() resource.

    $yourApiKey = getenv('YOUR_API_KEY');
    $client = OpenAI::client($yourApiKey);
    
    $response = $client->responses()->create([
        'model' => 'gpt-4o',
        'input' => 'Hello!',
    ]);
    
    echo $response->outputText; // Hello! How can I assist you today?
  3. Configure the client for Azure OpenAI Service

    main

    To use Azure OpenAI, you must manually construct the client using the factory. You need to set the BaseUri to include your resource name and deployment ID, provide the api-key header, and include the api-version query parameter. Note that because the deployment ID is in the BaseUri, you do not need to pass a model parameter in your API calls.

    $client = OpenAI::factory()
        ->withBaseUri('{your-resource-name}.openai.azure.com/openai/deployments/{deployment-id}')
        ->withHttpHeader('api-key', '{your-api-key}')
        ->withQueryParam('api-version', '{version}')
        ->make();
    
    // Basic completion call (no model parameter needed)
    $result = $client->completions()->create([
        'prompt' => 'PHP is'
    ]);
  4. Install OpenAI PHP Client

    main

    Install the OpenAI PHP client using Composer. This package requires PHP 8.2 or higher.

    If your project does not already have a PSR-18 compliant HTTP client integrated, you should also install a client like Guzzle to ensure php-http/discovery can function correctly.

    composer require openai-php/client
    composer require guzzlehttp/guzzle
  5. Manage Fine-Tuning jobs (Deprecated)

    main

    [WARNING] Deprecation Notice

    OpenAI has deprecated the FineTunes API and it is expected to stop working by January 4, 2024. Use this resource only if maintaining legacy support is required.

    Available actions for the fineTunes() resource:

    • create(): Start a new fine-tuning job with a training file and model.
    • list(): Retrieve a list of your organization's fine-tuning jobs.
    • retrieve(id): Get detailed information about a specific job, including status, hyperparams, and file IDs.
    • cancel(id): Immediately cancel a running job.
    • listEvents(id): Get a list of status updates for a job.
    • listEventsStreamed(id): Stream fine-grained status updates for a job.
  6. Configure Assistants API header

    main

    The Assistants API is deprecated and will stop working by August 26, 2026. If you are manually creating a client from a factory, you must provide the OpenAI-Beta header with the value assistants=v2 to use this resource.

    $factory->withHttpHeader('OpenAI-Beta', 'assistants=v2')
  7. Mock API responses for testing

    main

    The package provides OpenAI\Testing\ClientFake to simulate API responses in your tests. When using the fake client, responses are returned in the order they are provided during instantiation. You can use the fake() method on response classes to define specific parameters for your test case. For streamed responses, you can provide a resource (like a file handle) to simulate the stream.

    use OpenAI	esting\
    ClientFake;
    use OpenAI\Responses\Completions\CreateResponse;
    
    $client = new ClientFake([
        CreateResponse::fake([
            'choices' => [
                [
                    'text' => 'awesome!',
                ],
            ],
        ]),
    ]);
    
    $completion = $client->completions()->create([
        'model' => 'gpt-3.5-turbo-instruct',
        'prompt' => 'PHP is ',
    ]);
    
    expect($completion['choices'][0]['text'])->toBe('awesome!');
  8. Configure a custom OpenAI client

    main

    For advanced configurations, use OpenAI::factory() to build a client. This allows you to specify an API key, organization, project, base URI, custom HTTP client, custom headers, query parameters, or a custom stream handler for streaming responses.

    $yourApiKey = getenv('YOUR_API_KEY');
    
    $client = OpenAI::factory()
        ->withApiKey($yourApiKey)
        ->withOrganization('your-organization') // default: null
        ->withProject('Your Project') // default: null
        ->withBaseUri('openai.example.com/v1') // default: api.openai.com/v1
        ->withHttpClient($httpClient = new \GuzzleHttp\Client([])) // default: HTTP client found using PSR-18 HTTP Client Discovery
        ->withHttpHeader('X-My-Header', 'foo')
        ->withQueryParam('my-param', 'bar')
        ->withStreamHandler(fn (RequestInterface $request): ResponseInterface => $httpClient->send($request, [
            'stream' => true // Allows to provide a custom stream handler for the http client.
        ]))
        ->make();
  9. Increase HTTP client timeout

    main

    If you encounter timeouts, you can increase the timeout duration by configuring a custom HTTP client (e.g., Guzzle) and passing it to the OpenAI factory.

    OpenAI::factory()
        ->withApiKey($apiKey)
        ->withOrganization($organization)
        ->withHttpClient(new \GuzzleHttp\Client(['timeout' => $timeout]))
        ->make();
  10. Simulate API errors in tests

    main

    To test how your application handles API failures, you can provide a Throwable object (such as an ErrorException) to the ClientFake constructor.

    $client = new ClientFake([
        new \OpenAI\Exceptions\ErrorException([
            'message' => 'The model `gpt-1` does not exist',
            'type' => 'invalid_request_error',
            'code' => null,
        ], 404)
    ]);
    
    // The ErrorException will be thrown when calling the API
    $completion = $client->completions()->create([
        'model' => 'gpt-3.5-turbo-instruct',
        'prompt' => 'PHP is ',
    ]);
  11. Use Function Calling with the `Responses` Resource

    main

    You can define custom functions as tools in a response request. When the model decides to use a tool, the response will contain a function_call item. You must then execute your local code with the provided arguments.

    $response = $client->responses()->create([
        'model' => 'gpt-4o-mini',
        'tools' => [
            [
                'type' => 'function',
                'name' => 'get_temperature',
                'description' => 'Get the current temperature in a given location',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'location' => ['type' => 'string', 'description' => 'The city and state, e.g. San Francisco, CA'],
                        'unit' => ['type' => 'string', 'enum' => ['celsius', 'fahrenheit']],
                    ],
                    'required' => ['location'],
                ],
            ]
        ],
        'input' => "What is the temperature in Rio Grande do Norte, Brazil?",
    ]);
    
    foreach ($response->output as $item) {
        if ($item->type === 'function_call') {
            $name = $item->name ?? null;
            $args = json_decode($item->arguments ?? '{}', true) ?: [];
    
            if ($name === 'get_temperature') {
                // ✅ Call your custom function here with $args
            }
        }
    }
  12. Handle Function Calls in Streamed Runs

    main

    When using createStreamed, you may encounter the thread.run.requires_action event. To continue the stream, you must submit tool outputs using submitToolOutputsStreamed. This is typically done in a loop until the run status reaches completed.

    $stream = $client->threads()->runs()->createStreamed(
        threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
        parameters: [
            'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd',
        ],
    );
    
    do {
        foreach($stream as $response){
            switch($response->event){
                case 'thread.run.requires_action':
                    $run = $response->response;
                    // Overwrite the stream with the new stream started by submitting the tool outputs
                    $stream = $client->threads()->runs()->submitToolOutputsStreamed(
                        threadId: $run->threadId,
                        runId: $run->id,
                        parameters: [
                            'tool_outputs' => [
                                [
                                    'tool_call_id' => 'call_KSg14X7kZF2WDzlPhpQ168Mj',
                                    'output' => '12',
                                ]
                            ],
                        ]
                    );
                    break;
                // Handle other events like 'thread.run.completed', etc.
            }
        }
    } while ($run->status != "completed")