{"id":13464009,"url":"https://github.com/tectalichq/public-openai-client-php","last_synced_at":"2025-03-25T09:31:30.817Z","repository":{"id":59810743,"uuid":"539343691","full_name":"tectalichq/public-openai-client-php","owner":"tectalichq","description":"OpenAI API Client for PHP. Includes all endpoints and models (DTOs) for all requests and responses.","archived":true,"fork":false,"pushed_at":"2023-10-23T03:18:11.000Z","size":292,"stargazers_count":334,"open_issues_count":0,"forks_count":63,"subscribers_count":14,"default_branch":"main","last_synced_at":"2025-03-11T13:41:42.423Z","etag":null,"topics":["api","api-client","api-client-php","artificial-intelligence","chatgpt","client","codex","dall-e","dalle","gpt-3","gpt-35","gpt-35-turbo","gpt-4","openai","php","sdk"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tectalichq.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2022-09-21T06:41:53.000Z","updated_at":"2025-01-16T01:31:09.000Z","dependencies_parsed_at":"2023-02-09T14:46:16.988Z","dependency_job_id":"bc652296-a8b4-45b2-8aab-1ef259bf735b","html_url":"https://github.com/tectalichq/public-openai-client-php","commit_stats":{"total_commits":29,"total_committers":3,"mean_commits":9.666666666666666,"dds":"0.24137931034482762","last_synced_commit":"2a343b6688485dc4919756334004d06592a01413"},"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tectalichq%2Fpublic-openai-client-php","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tectalichq%2Fpublic-openai-client-php/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tectalichq%2Fpublic-openai-client-php/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tectalichq%2Fpublic-openai-client-php/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tectalichq","download_url":"https://codeload.github.com/tectalichq/public-openai-client-php/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245435179,"owners_count":20614853,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-client","api-client-php","artificial-intelligence","chatgpt","client","codex","dall-e","dalle","gpt-3","gpt-35","gpt-35-turbo","gpt-4","openai","php","sdk"],"created_at":"2024-07-31T14:00:32.021Z","updated_at":"2025-03-25T09:31:25.807Z","avatar_url":"https://github.com/tectalichq.png","language":"PHP","funding_links":[],"categories":["Awesome PHP Open AI Projects"],"sub_categories":[],"readme":"# Tectalic OpenAI REST API Client\n\n\u003e **This package is no longer supported or maintained.**\n\n## Introduction\n\nThe **Tectalic OpenAI REST API Client** is a package that provides a convenient and straightforward way to interact with the **OpenAI API** from your PHP application.\n\nSupports **ChatGPT**, **GPT-4**, **GPT-3.5**, **GPT-3**, **Codex**, **DALL·E**, **Whisper**, **Fine-Tuning**, **Embeddings** and **Moderation** models, with fully typed Data Transfer Objects (DTOs) for all requests and responses and IDE autocomplete support.\n\nMore information is available from [https://tectalic.com/apis/openai](https://tectalic.com/apis/openai).\n\n**This is an unofficial package and has no affiliations with OpenAI.**\n\n## Examples\n\nIntegrating OpenAI into your application is now as simple as a few lines of code.\n\n### Chat Completion using ChatGPT (GPT-3.5 \u0026 GPT-4)\n\n```php\n$openaiClient = \\Tectalic\\OpenAi\\Manager::build(\n    new \\GuzzleHttp\\Client(),\n    new \\Tectalic\\OpenAi\\Authentication(getenv('OPENAI_API_KEY'))\n);\n\n/** @var \\Tectalic\\OpenAi\\Models\\ChatCompletions\\CreateResponse $response */\n$response = $openaiClient-\u003echatCompletions()-\u003ecreate(\n    new \\Tectalic\\OpenAi\\Models\\ChatCompletions\\CreateRequest([\n        'model' =\u003e 'gpt-4',\n        'messages' =\u003e [\n            [\n                'role' =\u003e 'user',\n                'content' =\u003e 'Will using a well designed and supported third party package save time?'\n            ],\n        ],\n    ])\n)-\u003etoModel();\n\necho $response-\u003echoices[0]-\u003emessage-\u003econtent;\n\n// Yes, using a well-designed and supported third-party package can save time during software development.\n// It allows you to focus on the core functionality of your application without having to reinvent the wheel or spend resources developing the same functionality from scratch.\n// A good third-party package can provide reliability, efficiency, and continued support with updates and bug fixes, which in turn facilitates faster development and a more stable final product.\n// Additionally, using widely adopted packages can also increase the chances of compatibility with other software components and make it easier for other developers to understand and work with your code.\n```\n\n[Learn more about chat completion](https://platform.openai.com/docs/guides/chat).\n\nThis handler supports both the *GPT-3.5* and *GPT-4* models:\n\n#### GPT-3.5\n\nSupported [GPT-3.5 models](https://platform.openai.com/docs/models/gpt-3-5) include `gpt-3.5-turbo` and more.\n\n#### GPT-4\n\nSupported [GPT-4 models](https://platform.openai.com/docs/models/gpt-4) include `gpt-4` and more.\n\nNote: GPT-4 is currently in a limited beta and is only accessible to those who have been granted access. [Please see here](https://platform.openai.com/docs/models/gpt-4) for details and instructions on how to join the waitlist.\n\nIf you receive a 404 error when attempting to use GPT-4, then your OpenAI account has not been granted access.\n\n### Chat Completion Function Calling using ChatGPT (GPT-3.5 \u0026 GPT-4)\n\nThe following example uses the `gpt-3.5-turbo-0613` model to demonstrate function calling.\n\nIt converts natural language into a function call, which can then be executed within your application.\n\n```php\n$openaiClient = \\Tectalic\\OpenAi\\Manager::build(\n    new \\GuzzleHttp\\Client(),\n    new \\Tectalic\\OpenAi\\Authentication(getenv('OPENAI_API_KEY'))\n);\n\n/** @var \\Tectalic\\OpenAi\\Models\\ChatCompletions\\CreateResponse $response */\n$response = $openaiClient-\u003echatCompletions()-\u003ecreate(new CreateRequest([\n            'model' =\u003e 'gpt-3.5-turbo-0613',\n            'messages' =\u003e [\n                ['role' =\u003e 'user', 'content' =\u003e 'What\\'s the weather like in Boston?']\n            ],\n            'functions' =\u003e [\n                [\n                    'name' =\u003e 'get_current_weather',\n                    'description' =\u003e 'Get the current weather in a given location',\n                    'parameters' =\u003e new \\Tectalic\\OpenAi\\Models\\ChatCompletions\\CreateRequestFunctionsItemParameters(\n                        [\n                            'type' =\u003e 'object',\n                            'properties' =\u003e [\n                                'location' =\u003e [\n                                    'type' =\u003e 'string',\n                                    'description' =\u003e 'The worldwide city and state, e.g. San Francisco, CA',\n                                ],\n                                'format' =\u003e [\n                                    'type' =\u003e 'string',\n                                    'description' =\u003e 'The temperature unit to use. Infer this from the users location.',\n                                    'enum' =\u003e ['celsius', 'farhenheit'],\n                                ],\n                                'num_days' =\u003e [\n                                    'type' =\u003e 'integer',\n                                    'description' =\u003e 'The number of days to forecast',\n                                ],\n                            ],\n                            'required' =\u003e ['location', 'format', 'num_days'],\n                        ]\n                    )\n                ]\n            ],\n            'function_call' =\u003e 'auto',\n        ]))-\u003etoModel();\n\n$params = json_decode($response-\u003echoices[0]-\u003emessage-\u003efunction_call-\u003earguments, true);\nvar_dump($params);\n\n// array(3) {\n//     'location' =\u003e\n//     string(6) \"Boston\"\n//     'format' =\u003e\n//     string(7) \"celsius\"\n//     'num_days' =\u003e\n//     int(1)\n//}\n\n```\n\n[Learn more about function calling](https://platform.openai.com/docs/guides/gpt/function-calling).\n\n### Text Completion (GPT-3)\n\n```php\n$openaiClient = \\Tectalic\\OpenAi\\Manager::build(new \\GuzzleHttp\\Client(), new \\Tectalic\\OpenAi\\Authentication(getenv('OPENAI_API_KEY')));\n\n/** @var \\Tectalic\\OpenAi\\Models\\Completions\\CreateResponse $response */\n$response = $openaiClient-\u003ecompletions()-\u003ecreate(\n    new \\Tectalic\\OpenAi\\Models\\Completions\\CreateRequest([\n        'model'  =\u003e 'text-davinci-003',\n        'prompt' =\u003e 'Will using a third party package save time?',\n    ])\n)-\u003etoModel();\n\necho $response-\u003echoices[0]-\u003etext;\n// Using a third party package can save time because you don't have to write the code yourself.\n```\n\nThis handler supports all [GPT-3 models](https://platform.openai.com/docs/models/gpt-3), including `text-davinci-003`, `text-davinci-002` and more.\n\n[Learn more about text completion](https://platform.openai.com/docs/guides/completion).\n\n### Code Completion (Codex)\n\n```php\n$openaiClient = \\Tectalic\\OpenAi\\Manager::build(new \\GuzzleHttp\\Client(), new \\Tectalic\\OpenAi\\Authentication(getenv('OPENAI_API_KEY')));\n\n/** @var \\Tectalic\\OpenAi\\Models\\Completions\\CreateResponse $response */\n$response = $openaiClient-\u003ecompletions()-\u003ecreate(\n    new \\Tectalic\\OpenAi\\Models\\Completions\\CreateRequest([\n        'model'  =\u003e 'code-davinci-002',\n        'prompt' =\u003e \"// PHP 8\\n// A variable that saves the current date and time\",\n        'max_tokens' =\u003e 256,\n        'stop' =\u003e \";\",\n    ])\n)-\u003etoModel();\n\necho $response-\u003echoices[0]-\u003etext;\n// $now = date(\"Y-m-d G:i:s\")\n```\n\nSupported [Codex models](https://platform.openai.com/docs/models/codex) include `code-davinci-002` and `code-cushman-001`.\n\n[Learn more about code completion](https://platform.openai.com/docs/guides/code).\n\n### Image Generation (DALL·E)\n\n```php\n$openaiClient = \\Tectalic\\OpenAi\\Manager::build(new \\GuzzleHttp\\Client(), new \\Tectalic\\OpenAi\\Authentication(getenv('OPENAI_API_KEY')));\n\n/** @var \\Tectalic\\OpenAi\\Models\\ImagesGenerations\\CreateResponse $response */\n$response = $openaiClient-\u003eimagesGenerations()-\u003ecreate(\n    new \\Tectalic\\OpenAi\\Models\\ImagesGenerations\\CreateRequest([\n        'prompt' =\u003e 'A cute baby sea otter wearing a hat',\n        'size' =\u003e '256x256',\n        'n' =\u003e 5\n    ])\n)-\u003etoModel();\n\nforeach ($response-\u003edata as $item) {\n    var_dump($item-\u003eurl);\n}\n```\n\n[Learn more about image generation](https://platform.openai.com/docs/guides/images).\n\n### Speech to Text Audio Transcription (Whisper)\n\n```php\n$openaiClient = \\Tectalic\\OpenAi\\Manager::build(new \\GuzzleHttp\\Client(), new \\Tectalic\\OpenAi\\Authentication(getenv('OPENAI_API_KEY')));\n\n/** @var \\Tectalic\\OpenAi\\Models\\AudioTranscriptions\\CreateResponse $response */\n$response = $openaiClient-\u003eaudioTranscriptions()-\u003ecreate(\n    new \\Tectalic\\OpenAi\\Models\\AudioTranscriptions\\CreateRequest([\n        'file' =\u003e '/full/path/to/audio/file.mp3',\n        'model' =\u003e 'whisper-1',\n    ])\n)-\u003etoModel();\n\necho $response-\u003etext;\n// Your audio transcript in your source language...\n```\n\nSupported [Whisper models](https://platform.openai.com/docs/models/whisper) include `whisper-1`.\n\n[Learn more about speech to text](https://platform.openai.com/docs/guides/speech-to-text), including the [50+ supported languages](https://platform.openai.com/docs/guides/speech-to-text/supported-languages).\n\n### Speech to Text Audio Translation (Whisper)\n\n```php\n$openaiClient = \\Tectalic\\OpenAi\\Manager::build(new \\GuzzleHttp\\Client(), new \\Tectalic\\OpenAi\\Authentication(getenv('OPENAI_API_KEY')));\n\n/** @var \\Tectalic\\OpenAi\\Models\\AudioTranslations\\CreateResponse $response */\n$response = $openaiClient-\u003eaudioTranslations()-\u003ecreate(\n    new \\Tectalic\\OpenAi\\Models\\AudioTranslations\\CreateRequest([\n        'file' =\u003e '/full/path/to/audio/file.mp3',\n        'model' =\u003e 'whisper-1',\n    ])\n)-\u003etoModel();\n\necho $response-\u003etext;\n// Your audio transcript in English...\n```\n\nSupported [Whisper models](https://platform.openai.com/docs/models/whisper) include `whisper-1`.\n\n[Learn more about speech to text](https://platform.openai.com/docs/guides/speech-to-text), including the [50+ supported languages](https://platform.openai.com/docs/guides/speech-to-text/supported-languages).\n\n## Installation\n\nNeed help getting started? See our guide: [how to build an app using the OpenAI API](https://tectalic.com/blog/build-an-app-using-openai-api).\n\n### System Requirements\n\n- PHP version 7.2.5 or newer (including PHP 8.0 and 8.1)\n- [PHP JSON extension](https://www.php.net/manual/en/json.installation.php) installed if using PHP 7.x. As of PHP 8.0, this extension became a core PHP extension so is always enabled.\n- A [PSR-18](https://www.php-fig.org/psr/psr-18/) compatible HTTP client such as 'Guzzle' or the 'Symfony HTTP Client'.\n\n### Composer Installation\n\nInstall the package into your project:\n\n```shell\ncomposer require tectalic/openai\n```\n\n## Usage\n\nAfter installing the **Tectalic OpenAI REST API Client** package into your project, ensure you also have a [compatible PSR-18 HTTP client](https://packagist.org/providers/psr/http-client-implementation) such as 'Guzzle' or the Symfony 'HTTP Client'.\n\nYou can use the following code sample and customize it to suit your application.\n\n```php\n// Load your project's composer autoloader (if you aren't already doing so).\nrequire_once(__DIR__ . '/vendor/autoload.php');\n```\n\n```php\nuse Symfony\\Component\\HttpClient\\Psr18Client;\nuse Tectalic\\OpenAi\\Authentication;\nuse Tectalic\\OpenAi\\Client;\nuse Tectalic\\OpenAi\\Manager;\n\n// Build a Tectalic OpenAI REST API Client globally.\n$auth = new Authentication(getenv('OPENAI_API_KEY'));\n$httpClient = new Psr18Client();\nManager::build($httpClient, $auth);\n\n// or\n\n// Build a Tectalic OpenAI REST API Client manually.\n$auth = new Authentication(getenv('OPENAI_API_KEY'));\n$httpClient = new Psr18Client();\n$client = new Client($httpClient, $auth, Manager::BASE_URI);\n```\n\n### Authentication\nTo authenticate your API requests, you will need to provide an `Authentication` (`$auth`) object when calling `Manager::build()`.\n\nAuthentication to the **OpenAI API** is by HTTP Bearer authentication.\n\nPlease see the OpenAI API documentation for more details on obtaining your authentication credentials.\n\nIn the **Usage** code above, customize the `Authentication` constructor to your needs. For example, will likely need to add a `OPENAI_API_KEY` environment variable to your system.\n\n### Client Class\n\nThe primary class you will interact with is the `Client` class (`Tectalic\\OpenAi\\Client`).\n\nThis `Client` class also contains the helper methods that let you quickly access the 19 API Handlers.\n\nPlease see below for a complete list of supported handlers and methods.\n\n### Supported API Handlers and Methods\n\nThis package supports 28 API Methods, which are grouped into 19 API Handlers.\n\nSee the table below for a full list of API Handlers and Methods.\n\n\n| API Handler Class and Method Name | Description | API Verb and URL |\n| --------------------------------- | ----------- | ---------------- |\n|`AudioTranscriptions::create()`|Transcribes audio into the input language.|`POST` `/audio/transcriptions`|\n|`AudioTranslations::create()`|Translates audio into English.|`POST` `/audio/translations`|\n|`ChatCompletions::create()`|Creates a model response for the given chat conversation.|`POST` `/chat/completions`|\n|`Completions::create()`|Creates a completion for the provided prompt and parameters.|`POST` `/completions`|\n|~~`Edits::create()`~~|~~Creates a new edit for the provided input, instruction, and parameters.~~|~~`POST` `/edits`~~|\n|`Embeddings::create()`|Creates an embedding vector representing the input text.|`POST` `/embeddings`|\n|`Files::list()`|Returns a list of files that belong to the user's organization.|`GET` `/files`|\n|`Files::create()`|Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit.|`POST` `/files`|\n|`Files::retrieve()`|Returns information about a specific file.|`GET` `/files/{file_id}`|\n|`Files::delete()`|Delete a file.|`DELETE` `/files/{file_id}`|\n|`FilesContent::download()`|Returns the contents of the specified file.|`GET` `/files/{file_id}/content`|\n|~~`FineTunes::list()`~~|~~List your organization's fine-tuning jobs~~|~~`GET` `/fine-tunes`~~|\n|~~`FineTunes::create()`~~|~~Creates a job that fine-tunes a specified model from a given dataset.\u003cbr /\u003eResponse includes details of the enqueued job including job status and the name of the fine-tuned models once complete.\u003cbr /\u003eLearn more about fine-tuning~~|~~`POST` `/fine-tunes`~~|\n|~~`FineTunes::retrieve()`~~|~~Gets info about the fine-tune job.\u003cbr /\u003eLearn more about fine-tuning~~|~~`GET` `/fine-tunes/{fine_tune_id}`~~|\n|~~`FineTunesCancel::cancelFineTune()`~~|~~Immediately cancel a fine-tune job.~~|~~`POST` `/fine-tunes/{fine_tune_id}/cancel`~~|\n|~~`FineTunesEvents::listFineTune()`~~|~~Get fine-grained status updates for a fine-tune job.~~|~~`GET` `/fine-tunes/{fine_tune_id}/events`~~|\n|`FineTuningJobs::listPaginated()`|List your organization's fine-tuning jobs|`GET` `/fine_tuning/jobs`|\n|`FineTuningJobs::create()`|Creates a job that fine-tunes a specified model from a given dataset.\u003cbr /\u003eResponse includes details of the enqueued job including job status and the name of the fine-tuned models once complete.\u003cbr /\u003eLearn more about fine-tuning|`POST` `/fine_tuning/jobs`|\n|`FineTuningJobs::retrieve()`|Get info about a fine-tuning job.\u003cbr /\u003eLearn more about fine-tuning|`GET` `/fine_tuning/jobs/{fine_tuning_job_id}`|\n|`FineTuningJobsCancel::fineTuning()`|Immediately cancel a fine-tune job.|`POST` `/fine_tuning/jobs/{fine_tuning_job_id}/cancel`|\n|`FineTuningJobsEvents::listFineTuning()`|Get status updates for a fine-tuning job.|`GET` `/fine_tuning/jobs/{fine_tuning_job_id}/events`|\n|`ImagesEdits::createImage()`|Creates an edited or extended image given an original image and a prompt.|`POST` `/images/edits`|\n|`ImagesGenerations::create()`|Creates an image given a prompt.|`POST` `/images/generations`|\n|`ImagesVariations::createImage()`|Creates a variation of a given image.|`POST` `/images/variations`|\n|`Models::list()`|Lists the currently available models, and provides basic information about each one such as the owner and availability.|`GET` `/models`|\n|`Models::retrieve()`|Retrieves a model instance, providing basic information about the model such as the owner and permissioning.|`GET` `/models/{model}`|\n|`Models::delete()`|Delete a fine-tuned model. You must have the Owner role in your organization to delete a model.|`DELETE` `/models/{model}`|\n|`Moderations::create()`|Classifies if text violates OpenAI's Content Policy|`POST` `/moderations`|\n\nDeprecated method(s) are listed with ~~strike-through~~ formatting. Please do not use these methods, as they will be removed in a future release.\n\n### Making a Request\n\nThere are two ways to make a request to the nominated API Handler and API Method:\n\nIf you built the client to be accessible globally, you can use the relevant API Handler Class directly:\n\n```php\nuse Tectalic\\OpenAi\\Handlers\\AudioTranscriptions;\n\n(new AudioTranscriptions())-\u003ecreate();\n```\n\nAlternatively, you can access all API Handlers from the client class using the Client class:\n\n```php\n$client-\u003eaudioTranscriptions()-\u003ecreate();\n```\n\n### Retrieving the Response\n\nOnce you have made a request using one of the two methods outlined above, the next step is to access the response.\n\nYou can access the response in different ways. Please choose your preferred one.\n\n#### Model Responses\n\nModel responses are Data Transfer Object (DTO) style PHP classes, with public properties for each API property.\n\nThey offer a structured way of retrieving the response from an API request.\n\nAll Response Models are an instance of `Tectalic\\OpenAi\\Models\\AbstractModel` or `Tectalic\\OpenAi\\Models\\AbstractModelCollection`.\n\nAfter [performing the request](#making-a-request), use the `-\u003etoModel()` fluent method to the API Method:\n\n```php\nuse Tectalic\\OpenAi\\Handlers\\AudioTranscriptions;\n\n$model = (new AudioTranscriptions())-\u003ecreate()-\u003etoModel();\n```\n\nEach API Method's `toModel()` call will return the appropriate Model class type for the API Method you have just called.\n\n#### Associative Array Responses\n\nAfter performing the request, use the `-\u003etoArray()` fluent method to the API Method:\n\n```php\nuse Tectalic\\OpenAi\\Handlers\\AudioTranscriptions;\n\n$array = (new AudioTranscriptions())-\u003ecreate()-\u003etoArray();\n```\n\nIn the resulting associative array, the array keys will match the names of the public properties in the relevant Model class.\n\n#### PSR 7 Response Objects\n\nIf you need to access the raw response or inspect the HTTP headers, use the `-\u003egetResponse()` fluent method to the API Method. It will return a `Psr\\Http\\Message\\ResponseInterface`:\n\n```php\nuse Tectalic\\OpenAi\\Handlers\\AudioTranscriptions;\n\n$response = (new AudioTranscriptions())-\u003ecreate()-\u003egetResponse();\n```\n\n### Errors\n\nWhen performing requests with **Tectalic OpenAI REST API Client**, specific scenarios will cause a `Tectalic\\OpenAi\\Exception\\ClientException` to be thrown. Please see below for details.\n\n#### Invalid Usage of the `Manager` Class\n\nA `\\LogicException` will be thrown if the `Manager::build()` function is called multiple times, or if `Manager::access()` is called before calling `Manager::build()`.\n\n#### Unsuccessful HTTP Response Codes\n\nThe **Tectalic OpenAI REST API Client** depends on a PSR-18 compatible HTTP client, and that HTTP client should not throw an exception for [unsuccessful HTTP response codes](https://www.php-fig.org/psr/psr-18/#error-handling).\n\nAn unsuccessful response code is classified as one that is not in the range `200`-`299` (inclusive). Examples of unsuccessful response codes include:\n\n- Informational responses (`100`-`199`)\n- Redirection responses (`300`-`399`)\n- Client error responses (`400`-`499`)\n- Server error responses (`500`-`599`)\n\nIf an unsuccessful response code does occur:\n\n- your HTTP Client will *not* throw an Exception.\n- the API Handler's `toModel()` method will throw a `ClientException`.\n- the API Handler's `toArray()` method will return the response body and not throw a `ClientException`.\n- The API Handler's `getResponse()` method will return the raw response and not throw a `ClientException`.\n\nBelow is an example of how you may wish to use a `try`/`catch` block when performing a request so that you can detect and handle unexpected errors.\n\n```php\nuse Tectalic\\OpenAi\\Authentication;\nuse Tectalic\\OpenAi\\Client;\nuse Tectalic\\OpenAi\\ClientException;\nuse Tectalic\\OpenAi\\Manager;\n\n// Build a Tectalic OpenAI REST API Client globally.\n$auth = new Authentication('token');\nManager::build($httpClient, $auth);\n$handler = new AudioTranscriptions();\n\n// Perform a request\ntry {\n    $model = $handler-\u003ecreate()-\u003etoModel();\n    // Do something with the response model...\n} catch (ClientException $e) {\n    // Error response received. Retrieve the HTTP response code and response body.\n    $responseBody = $handler-\u003etoArray();\n    $responseCode = $handler-\u003egetResponse()-\u003egetStatusCode();\n    // Handle the error...\n}\n```\n\n#### HTTP Client Exceptions\n\nIf your HTTP client of choice throws an exception other than `ClientException`, the **Tectalic OpenAI REST API Client** `Client` and its API Handler classes will let these exceptions bubble up.\n\nConsult your HTTP client's documentation for more details on exception handling.\n\n## Tests\n\nThe **Tectalic OpenAI REST API Client** package includes several types of automated PHPUnit tests to verify the correct operation:\n\n- Unit Tests\n- Integration Tests\n\nTo run these tests, you will need to have installed the **Tectalic OpenAI REST API Client** package with its dev dependencies (i.e. not using the `--no-dev` flag when running composer).\n\n### Unit Tests\n\nThese PHPUnit tests are designed to:\n\n- confirm that each API Method assembles a valid request that matches the OpenAI API OpenAPI specification.\n- verify the behaviour of other parts of the package, such as the `Client` and `Manager` classes.\n\nThe unit tests can be run using the following command, which needs to be run from this package's root directory.\n\n```shell\ncomposer test:unit\n```\n\nUnit tests do *not* perform any real requests against the OpenAI API.\n\nUnit tests are located in the `tests/Unit` directory.\n\n### Integration Tests\n\nIntegration tests are located in the `tests/Integration` directory.\n\nThese PHPUnit tests are designed to confirm that each API Method parses a valid response, according to the OpenAI API OpenAPI specification. Out of the box the integration tests are designed to work with the [Prism Mock Server](https://meta.stoplight.io/docs/prism/).\n\n#### Using Prism as the Target\n\nMake sure Prism is installed. Please see the [Prism documentation](https://meta.stoplight.io/docs/prism/) for details on how to install Prism.\n\nOnce Prism is installed, you can run prism and the integration tests side by side in separate terminal windows, or using the following command, which need to be run from this package's root directory.\n\n```shell\necho \"\u003e Starting Prism server\"\nprism mock tests/openapi.yaml \u003e/dev/null 2\u003e\u00261 \u0026\nPRISM_PID=$!\nsleep 2\necho \"  =\u003e Started\"\ncomposer test:integration\nkill $PRISM_PID\n```\n\nThose commands will start the Prism mock server, then run the integration tests, and then stop the Prism mock server when the tests are completed.\n\nIn this case the integration tests do *not* perform any real requests against the OpenAI API.\n\n#### Using a Different Target\n\nBy setting the `OPENAI_CLIENT_TEST_BASE_URI` environment variable, you can set a different API endpoint target for the integration tests.\n\nFor example, instead of using Prism, you can use a different mocking/staging/test server of your choice, or you can use the OpenAI API's live endpoints.\n\nDo not forget to set the appropriate credentials in the `OPENAI_CLIENT_TEST_AUTH_USERNAME` `OPENAI_CLIENT_TEST_AUTH_PASSWORD` environment variables.\n\nAfter your setup is complete simply run the following command.\n\n```shell\ncomposer test:integration\n```\n\nWe do not recommend running integration tests against the live OpenAI API endpoints. This is because the tests will send example data to all endpoints, which can result in new data being created, or existing data being deleted.\n\n### Writing Your Own Tests\n\nIf you are writing your own tests, you will likely need to mock the responses from the **OpenAI API**.\n\nOne way of doing this is to install the `php-http/mock-client` package into your project, and then use the `\\Http\\Mock\\Client` class (instead of a real PSR-18 client) when instantiating the **Tectalic OpenAI REST API Client**.\n\nThis allows you to mock the responses from the **OpenAI API**, rather than performing real requests.\n\nPlease see the [Mock Client documentation](https://docs.php-http.org/en/latest/clients/mock-client.html#mock-client) for details.\n\n## Support\n\nIf you have any questions or feedback, please use the [discussion board](https://github.com/tectalichq/public-openai-client-php/discussions).\n\n## License\n\nThis software is copyright (c) 2022-present [Tectalic](https://tectalic.com).\n\nFor copyright and license information, please view the **LICENSE** file.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftectalichq%2Fpublic-openai-client-php","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftectalichq%2Fpublic-openai-client-php","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftectalichq%2Fpublic-openai-client-php/lists"}