{"id":20702893,"url":"https://github.com/easygithdev/phpopenai","last_synced_at":"2025-10-19T03:24:26.079Z","repository":{"id":114119583,"uuid":"609984109","full_name":"EasyGithDev/PHPOpenAI","owner":"EasyGithDev","description":"PHPOpenAI is a wrapper to access OpenAI API","archived":false,"fork":false,"pushed_at":"2024-02-25T12:59:14.000Z","size":3584,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-09T01:12:50.215Z","etag":null,"topics":["ai","api","curl","dall-e","dalle","gpt-3","gpt-35-turbo","openai","php","whisper"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"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/EasyGithDev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2023-03-05T20:09:17.000Z","updated_at":"2024-09-25T14:39:43.000Z","dependencies_parsed_at":"2024-02-25T13:35:09.086Z","dependency_job_id":"2d83bd48-8cc5-4aee-b2a6-74366d227227","html_url":"https://github.com/EasyGithDev/PHPOpenAI","commit_stats":null,"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"purl":"pkg:github/EasyGithDev/PHPOpenAI","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGithDev%2FPHPOpenAI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGithDev%2FPHPOpenAI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGithDev%2FPHPOpenAI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGithDev%2FPHPOpenAI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/EasyGithDev","download_url":"https://codeload.github.com/EasyGithDev/PHPOpenAI/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGithDev%2FPHPOpenAI/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279000725,"owners_count":26082894,"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","status":"online","status_checked_at":"2025-10-08T02:00:06.501Z","response_time":56,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["ai","api","curl","dall-e","dalle","gpt-3","gpt-35-turbo","openai","php","whisper"],"created_at":"2024-11-17T01:05:23.853Z","updated_at":"2025-10-09T01:13:43.496Z","avatar_url":"https://github.com/EasyGithDev.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PHPOpenAI\n\n`PHPOpenAI` is a community-maintained library that enables the use of the `OpenAI` API in PHP.\n\nThe project is written in PHP and can be used to easily integrate the `OpenAI API` into your existing PHP project.\n\n## System Requirements\n\nThis project is based on PHP version 8.1 in order to use features such as enumerations. This project does not require any external dependencies. However, you must have the cURL extension installed for it to work properly.\n\n- PHP version \u003e= 8.1\n- cURL extension\n\n## Installation\n\nThe project uses Composer to manage dependencies. If you haven't already installed Composer, you can do so by following the instructions on the official Composer website.\n\n### Packagist install\n\nTo install the project, you can install the package from packagist.org using the following command:\n\n```bash\ncomposer require easygithdev/php-openai\n```\n\n## Writing a first example\n\nTo use the `OpenAI API`, you need to sign up on their website and obtain an API key. Once you have your API key, you can use it in your PHP code to send requests to the OpenAI API.\n\nTo find out how to get your key, go to the following address:\n\n[https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key).\n\n\nHere's an example code that shows you how to use the OpenAI API in PHP:\n\n```php\n\u003c?php\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse EasyGithDev\\PHPOpenAI\\Helpers\\ModelEnum;\nuse EasyGithDev\\PHPOpenAI\\OpenAIClient;\n\n$apiKey = getenv('OPENAI_API_KEY');\n\n$response = (new OpenAIClient($apiKey))-\u003eCompletion()-\u003ecreate(\n    ModelEnum::TEXT_DAVINCI_003,\n    \"Say this is a test\",\n)-\u003etoObject();\n\n// Response as stClass object\necho '\u003cpre\u003e', print_r($response, true), '\u003c/pre\u003e';\n```\n\nThis code instantiates a new `OpenAIApi` object with an API key, and then creates a new `Completion` object to perform text completion with the GPT-3 AI language model provided by OpenAI.\n\nThe `create()` method is called on the `Completion` object to generate a new text completion. It takes two parameters:\n\n- the first parameter is the ID of the GPT-3 model to use for completion. In this case, it uses the TEXT_DAVINCI_003 model.\n- the second parameter is the prompt or input text for which the completion will be generated. In this case, the prompt is \"Say this is a test\".\n\nThe result of the completion is returned in the `$response` variable. The result can then be used for further processing, such as displaying the completed text or feeding it into another part of the program for additional processing.\n\n\n## Manage the API Key\n\nYou can use an environment variable to store your key. You can then use this variable as in the following example:\n\n```bash\nexport OPENAI_API_KEY=\"sk-xxxxxxxxxxx\"\n```\n\nYou can put the variable in Apache configuration file  :\n\n```\n\u003cVirtualHost hostname:80\u003e\n   ...\n   SetEnv OPENAI_API_KEY sk-xxxxxxxxxxx\n   ...\n\u003c/VirtualHost\u003e\n```\n\nAnd then restart the service.\n\nNow, you can use the environment variable by calling the `getenv()` function of PHP.\n\n```php\n\u003c?php\n$response = (new OpenAIApi(getenv('OPENAI_API_KEY')))-\u003eCompletion()-\u003ecreate(\n    ModelEnum::TEXT_DAVINCI_003,\n    \"Say this is a test\",\n);\n```\n\n## Manage the organization\n\nIf you wish to provide information about your organization, you must proceed as follows.\n\n```php\n\u003c?php\n$apiKey = getenv('OPENAI_API_KEY');\n$org = getenv('OPENAI_API_ORG');\n\n// Passing the organization to the client\n$response = (new OpenAIClient($apiKey, $org))\n```\n\n## Manage the API's Url\n\nIf you need to modify the API's URL, you can proceed as follows:\n\n```php\n\u003c?php\n$apiKey = getenv('OPENAI_API_KEY');\n\n// Create a new router, with origine url and version\n$route = new OpenAIRoute(\n    'https://api.openai.com',\n    'v1'\n);\n\n// Get a specific Url\necho $route-\u003ecompletionCreate() , '\u003cbr\u003e';\n\n// Passing the router to the client\n$response = (new OpenAIClient($apiKey))\n    -\u003esetRoute($route);\n```\n\nTo redefine a route, you need to extend the `OpenAIRoute` class or implement the `Route` interface.\n\n## Manage the reponses\n\nThe API returns responses in JSON format. To facilitate access to the different information, you can call `toObject()` or `toArray()` methods  of the Handler object to access the data.\n\n```php\n\u003c?php\n\n$response = (new OpenAIClient($apiKey))-\u003eCompletion()-\u003ecreate(\n    ModelEnum::TEXT_DAVINCI_003,\n    \"Say this is a test\",\n)-\u003etoObject();\n\n// Response as a stClass object\necho '\u003cpre\u003e', print_r($response, true), '\u003c/pre\u003e';\n\n$response = (new OpenAIClient($apiKey))-\u003eCompletion()-\u003ecreate(\n    ModelEnum::TEXT_DAVINCI_003,\n    \"Say this is a test\",\n)-\u003etoArray();\n\n// Response as an associative array\necho '\u003cpre\u003e', print_r($response, true), '\u003c/pre\u003e';\n```\n\n## Manage the errors\n\nSometimes, the API returns errors. Therefore, it is necessary to be able to identify what caused the problem. To handle this difficulty, you have many options. \n\nIf you are using a Handler object with `toObject()` or `toArray()` methods, just use a `try-catch` structure.\n\n```php\ntry {\n    $response = (new OpenAIClient('BAD KEY'))\n        -\u003eCompletion()\n        -\u003ecreate(\n            ModelEnum::TEXT_DAVINCI_003,\n            \"Say this is a test\",\n        )\n        -\u003etoObject();\n} catch (Throwable $t) {\n    echo nl2br($t-\u003egetMessage());\n    die;\n}\n```\n\nIf you are using the `CurlResponse` object, you can check that an error has occurred using the validators. \n\n```php\n\n$handler = (new OpenAIClient('BAD KEY'))-\u003eCompletion()-\u003ecreate(\n    ModelEnum::TEXT_DAVINCI_003,\n    \"Say this is a test\",\n);\n\n$response = $handler-\u003egetResponse();\n$contentTypeValidator = $handler-\u003egetContentTypeValidator();\n\nif (!(new StatusValidator($response))-\u003evalidate() or \n    !(new $contentTypeValidator($response))-\u003evalidate()) {\n    echo $response-\u003egetBody();\n}\n```\n\n[Learn more about errors](https://platform.openai.com/docs/guides/error-codes/api-errors).\n\n## An example of application \n\nHere is a video showing an application that allows you to create images with a painting style defined by the user. \nThis application is created using the PHPOpenAI project.\n\n\n\u003cp\u003e\n\nhttps://user-images.githubusercontent.com/3519890/230593418-22f26562-e88c-4a92-9601-93bb671a16c0.mp4\n\n\u003c/p\u003e\n\nYou can find the code here:\n\n[https://github.com/EasyGithDev/PHPOpenAI-Playground.git](https://github.com/EasyGithDev/PHPOpenAI-Playground.git).\n\n## Code samples\n\nIntegrating OpenAI into your application is now as simple as a few lines of code.\n\nYou can find all codes here:\n\n[https://github.com/EasyGithDev/PHPOpenAI-Examples](https://github.com/EasyGithDev/PHPOpenAI-Examples).\n\n### Text Completion using ChatGPT\n\n```php\n$response = (new OpenAIClient($apiKey))-\u003eChat()-\u003ecreate(\n    ModelEnum::GPT_3_5_TURBO,\n    [\n        new ChatMessage(ChatMessage::ROLE_SYSTEM, \"You are a helpful assistant.\"),\n        new ChatMessage(ChatMessage::ROLE_USER, \"Who won the world series in 2020?\"),\n        new ChatMessage(ChatMessage::ROLE_ASSISTANT, \"The Los Angeles Dodgers won the World Series in 2020.\"),\n        new ChatMessage(ChatMessage::ROLE_USER, \"Where was it played?\"),\n    ]\n)-\u003etoObject();\n```\n\n[Learn more about chat completion](https://platform.openai.com/docs/guides/chat).\n\n### Text Completion using GPT-3\n\n```php\n$response = (new OpenAIClient($apiKey))-\u003eCompletion()-\u003ecreate(\n    ModelEnum::TEXT_DAVINCI_003,\n    \"Say this is a test\",\n)-\u003etoObject();\n```\n\n[Learn more about text completion](https://platform.openai.com/docs/guides/completion).\n\n### Text Completion using stream\n\nThe stream attribute in the OpenAI API is an optional parameter that you can use to control the data flow returned by the API. If you set this option to True, the API will return a response as a streaming data rather than a single response.\n\nThis means that you can retrieve the results of the API as they become available, rather than waiting for the complete response before processing them. This option can be useful for applications that require real-time processing of large amounts of data.\n\n\n\u003cp\u003e\n\nhttps://user-images.githubusercontent.com/3519890/229144053-d32e6416-0980-44ea-97b7-b2d4a2d26a5d.mp4\n\n\u003c/p\u003e\n\n\n```php\n\u003c?php\nheader('Content-Type: text/event-stream');\nheader('Cache-Control: no-cache');\n\n...\n\n(new OpenAIClient($apiKey))-\u003eCompletion()-\u003ecreate(\n    model: \"text-davinci-003\",\n    prompt: \"Translate this into 1. French, 2. Spanish and 3. Japanese:\\n\\nWhat rooms do you have available?\\n\\n1.\",\n    temperature: 0.3,\n    max_tokens: 100,\n    top_p: 1.0,\n    frequency_penalty: 0.0,\n    presence_penalty: 0.0,\n    stream: true\n)-\u003egetResponse();\n```\n\n```html\n\u003chtml\u003e\n\n\u003cbody\u003e\n    \u003cdiv id=\"result\"\u003e\u003c/div\u003e\n    \u003cscript\u003e\n        function nl2br(str, replaceMode, isXhtml) {\n            var breakTag = (isXhtml) ? '\u003cbr /\u003e' : '\u003cbr\u003e';\n            var replaceStr = (replaceMode) ? '$1' + breakTag : '$1' + breakTag + '$2';\n            return (str + '').replace(/([^\u003e\\r\\n]?)(\\r\\n|\\n\\r|\\r|\\n)/g, replaceStr);\n        }\n\n        if (typeof (EventSource) !== 'undefined') {\n            console.info('Starting connection...');\n            var source = new EventSource('stream.php');\n            source.addEventListener('open', function (e) {\n                console.info('Connection was opened.');\n            }, false);\n\n            source.addEventListener('error', function (e) {\n                var txt;\n                switch (event.target.readyState) {\n                    // if reconnecting\n                    case EventSource.CONNECTING:\n                        txt = 'Reconnecting...';\n                        break;\n                    // if error was fatal\n                    case EventSource.CLOSED:\n                        txt = 'Connection failed. Will not retry.';\n                        break;\n                }\n                console.error('Connection error: ' + txt);\n            }, false);\n\n            source.addEventListener('message', function (e) {\n                if (e.data == \"[DONE]\") {\n                    source.close();\n                    return;\n                }\n                document.getElementById('result').innerHTML += nl2br(JSON.parse(e.data).choices[0].text);\n\n            }, false);\n        } else {\n            alert('Your browser does not support Server-sent events! Please upgrade it!');\n            console.error('Connection aborted');\n        }\n    \u003c/script\u003e\n\u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n### Text Edit\n\n```php\n$response = (new OpenAIClient($apiKey))-\u003eEdit()-\u003ecreate(\n    \"What day of the wek is it?\",\n    ModelEnum::TEXT_DAVINCI_EDIT_001,\n    \"Fix the spelling mistakes\",\n)-\u003etoObject();\n```\n\n[Learn more about text edit](https://platform.openai.com/docs/guides/code/editing-code).\n\n### Image Generation Using DALL·E\n\n```php\nfunction displayUrl($url)\n{\n    return '\u003cimg src=\"' . $url . '\" /\u003e';\n}\n\n$response = (new OpenAIClient($apiKey))-\u003eImage()-\u003ecreate(\n    \"a rabbit inside a beautiful garden, 32 bit isometric\",\n    n: 2,\n    size: ImageSizeEnum::is256,\n)-\u003etoObject();\n```\n\n```html\n\u003c?php foreach ($response-\u003edata as $image) : ?\u003e\n    \u003cdiv\u003e \u003c?= displayUrl($image-\u003eurl) ?\u003e \u003c/div\u003e\n\u003c?php endforeach; ?\u003e\n```\n\n![rabit-32bits](https://user-images.githubusercontent.com/3519890/229202939-4d9290cb-e1fe-4860-b6d6-14bf41d5322b.png)\n\n\n\n[Learn more about image generation](https://platform.openai.com/docs/guides/images).\n\n### Image Variation Using DALL·E\n\n```php\n $response = (new OpenAIClient($apiKey))-\u003eImage()-\u003ecreateVariation(\n        __DIR__ . '/../../assets/image_variation_original.png',\n        n: 2,\n        size: ImageSizeEnum::is256\n    )-\u003etoObject();\n```\n\n![variation-1](https://user-images.githubusercontent.com/3519890/229203659-0c61bb77-c19e-4840-ad4d-6b22f0179260.png)\n\n\n[Learn more about image variation](https://platform.openai.com/docs/guides/images/variations).\n\n### Image Edit Using DALL·E\n\n```php\n $response = (new OpenAIClient($apiKey))-\u003eImage()-\u003ecreateEdit(\n        image: __DIR__ . '/../../assets/image_edit_original.png',\n        mask: __DIR__ . '/../../assets/image_edit_mask2.png',\n        prompt: 'a sunlit indoor lounge area with a pool containing a flamingo',\n        size: ImageSizeEnum::is512,\n    )-\u003etoObject();\n```\n\n![img-edit](https://user-images.githubusercontent.com/3519890/229203979-baf001e9-f72d-4741-a1c8-e8fa48c8c8e3.png)\n\n\n[Learn more about image edit](https://platform.openai.com/docs/guides/images/edits).\n\n### Embedding\n\n```php\n$response = (new OpenAIClient($apiKey))-\u003eEmbedding()-\u003ecreate(\n    ModelEnum::TEXT_EMBEDDING_ADA_002,\n    \"The food was delicious and the waiter...\",\n)-\u003etoObject();\n```\n\n[Learn more about embedding](https://platform.openai.com/docs/guides/embeddings).\n\n### Audio Transcription (Speech to text) using Whisper\n\n```php\n$response = (new OpenAIClient($apiKey))-\u003eAudio()\n    -\u003eaddCurlParam('timeout', 30)\n    -\u003etranscription(\n        __DIR__ . '/../../assets/openai.mp3',\n        ModelEnum::WHISPER_1,\n        response_format: AudioResponseEnum::SRT\n    )-\u003etoObject();\n```\n\n[Learn more about audio transcription](https://platform.openai.com/docs/guides/speech-to-text).\n\n### Audio Translation (Speech to text) using Whisper\n\n```php\n$response = (new OpenAIClient($apiKey))-\u003eAudio()\n    -\u003eaddCurlParam('timeout', 30)\n    -\u003etranslation(\n        __DIR__ . '/../../assets/openai_fr.mp3',\n        'whisper-1',\n        response_format: AudioResponseEnum::TEXT\n    )-\u003etoObject();\n```\n\n[Learn more about audio translation](https://platform.openai.com/docs/guides/speech-to-text/translations).\n\n### Model List\n\n```php\n$response = (new OpenAIClient($apiKey))\n    -\u003eModel()\n    -\u003elist()\n    -\u003etoObject();\n```\n\n[Learn more about model](https://platform.openai.com/docs/api-reference/models).\n\n### Model Retrieve\n\n```php\n$response = (new OpenAIClient($apiKey))\n    -\u003eModel()\n    -\u003eretrieve('text-davinci-001')\n    -\u003etoObject();\n```\n\n[Learn more about model](https://platform.openai.com/docs/api-reference/models/retrieve).\n\n### Model Delete\n\n```php\n$response = (new OpenAIClient($apiKey))\n    -\u003eModel()\n    -\u003edelete(\n        $_POST['model']\n    )-\u003etoObject();\n```\n\n[Learn more about model](https://platform.openai.com/docs/api-reference/fine-tunes/delete-model).\n\n\n### File List\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFile()\n    -\u003elist()\n    -\u003etoObject();\n```\n\n[Learn more about file](https://platform.openai.com/docs/api-reference/files/list).\n\n### File Upload\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFile()\n    -\u003ecreate(\n        __DIR__ . '/../../assets/mydata.jsonl',\n        'fine-tune',\n    )\n    -\u003etoObject();\n```\n\n[Learn more about file](https://platform.openai.com/docs/api-reference/files/upload).\n\n### File Delete\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFile()\n    -\u003edelete('file-xxxx')\n    -\u003etoObject();\n```\n\n[Learn more about file](https://platform.openai.com/docs/api-reference/files/delete).\n\n### File Retrieve\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFile()\n    -\u003eretrieve('file-xxxx')\n    -\u003etoObject();\n```\n\n[Learn more about model](https://platform.openai.com/docs/api-reference/files/retrieve).\n\n### File Retrieve Content\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFile()\n    -\u003edownload('file-xxxx')\n    -\u003etoObject();\n```\n\n[Learn more about model](https://platform.openai.com/docs/api-reference/files/retrieve-content).\n\n\n### Fine-tune List\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFineTune()\n    -\u003elist()\n    -\u003etoObject();\n```\n\n[Learn more about fine-tune](https://platform.openai.com/docs/api-reference/fine-tunes/list).\n\n### Fine-tune Create\n\n```php\n $response = (new OpenAIApi($apiKey))\n        -\u003eFineTune()\n        -\u003ecreate(\n            'file-xxxx'\n        )\n        -\u003etoObject();\n```\n\n[Learn more about fine-tune](https://platform.openai.com/docs/api-reference/fine-tunes/create).\n\n### Fine-tune Retrieve\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFineTune()\n    -\u003eretrieve('ft-xxx')\n    -\u003etoObject();\n```\n\n[Learn more about fine-tune](https://platform.openai.com/docs/api-reference/fine-tunes/retrieve).\n\n### Fine-tune List Events\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFineTune()\n    -\u003elistEvents('ft-xxx')\n    -\u003etoObject();\n```\n\n[Learn more about fine-tune](https://platform.openai.com/docs/api-reference/fine-tunes/events).\n\n### Fine-tune Cancel\n\n```php\n$response = (new OpenAIApi($apiKey))\n    -\u003eFineTune()\n    -\u003eCancel('ft-xxx')\n    -\u003etoObject();\n```\n\n[Learn more about fine-tune](https://platform.openai.com/docs/api-reference/fine-tunes/cancel).\n\n### Moderation\n\n```php\n$response = (new OpenAIClient($apiKey))\n    -\u003eModeration()\n    -\u003ecreate('I want to kill them.')\n    -\u003etoObject();\n```\n\n[Learn more about moderation](https://platform.openai.com/docs/models/moderation).\n\n## Testing\n\nTo run all tests:\n\n```bash\ncomposer test tests\n```\n\nTo run only one test :\n\n```bash\ncomposer test tests/[NAME]Test.php\n```\n\n### Summary\n\nPHPOpenAI is a useful project for PHP developers who want to easily integrate the OpenAI API into their projects. With simple installation and the use of Composer, text classification, image generation and named entity recognition into your PHP application.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feasygithdev%2Fphpopenai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feasygithdev%2Fphpopenai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feasygithdev%2Fphpopenai/lists"}