> For the complete documentation index, see [llms.txt](https://indie-4.gitbook.io/one-click-translations-documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://indie-4.gitbook.io/one-click-translations-documentation/openaiintegration.cs.md).

# OpenAIIntegration.cs

**OpenAIIntegration Class**

The OpenAIIntegration class provides a static interface for interacting with the OpenAI API to translate text within Unity. It leverages UnityWebRequest to make asynchronous API calls and handles the response to retrieve translated text.

**Namespace**: Indie.Localization

**Static Fields:**

* **apiKey**: A string representing the API key required for authenticating requests to the OpenAI API. Make sure to set this before making requests.
* **apiUrl**: A string containing the URL endpoint for the OpenAI API's chat completion feature.
* **model**: A string specifying the AI model to use for translation, in this case, gpt-4o-mini.
* **temperature**: A float value that controls the randomness of the output. A higher value means more random results.

**Methods**:

* **TranslateTextAsync(string text):** An async method that sends a translation request to the OpenAI API and returns the translated text.
* **Parameters**:
  * text: A string representing the text to be translated, formatted as a JSON object.
* **Returns**:
  * A Task\<string> containing the translated text in JSON format.
* **Usage**:
  * The method serializes the request body into JSON and sends it to the OpenAI API. It processes the response to extract the translated content and returns it as a string.
* **OpenAIResponse**: A class that represents the structure of the response from the OpenAI API.
  * **Choice**: A nested class within OpenAIResponse that stores the message content returned by the API.
  * **Message**: A nested class within Choice that holds the translated content.

**Key Details:**

* **Request Construction:** The request body is constructed as a JSON object with the specified model and temperature. It includes a system message to instruct the AI on how to format its output, ensuring translations are returned in the same JSON format as received.
* **Handling Responses:** The response from the API is deserialized to extract the translated content, which is then returned as a string. If there are any connection or protocol errors, these are logged, and an exception is thrown.
* **Usage of UnityWebRequest:** The method uses Unity's UnityWebRequest for HTTP communication, setting appropriate headers for content type and authorization.
