{"id":13721967,"url":"https://github.com/mochi-neko/ChatGPT-API-unity","last_synced_at":"2025-05-07T14:30:56.561Z","repository":{"id":112531902,"uuid":"609361758","full_name":"mochi-neko/ChatGPT-API-unity","owner":"mochi-neko","description":"A client library of ChatGPT chat completion API for Unity.","archived":false,"fork":false,"pushed_at":"2023-11-07T11:28:31.000Z","size":186,"stargazers_count":120,"open_issues_count":2,"forks_count":14,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-21T14:31:44.526Z","etag":null,"topics":["chatgpt-api","unity"],"latest_commit_sha":null,"homepage":"","language":"C#","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/mochi-neko.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,"roadmap":null,"authors":null}},"created_at":"2023-03-04T00:32:36.000Z","updated_at":"2025-01-11T03:56:27.000Z","dependencies_parsed_at":"2023-11-07T11:47:55.548Z","dependency_job_id":null,"html_url":"https://github.com/mochi-neko/ChatGPT-API-unity","commit_stats":null,"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mochi-neko%2FChatGPT-API-unity","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mochi-neko%2FChatGPT-API-unity/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mochi-neko%2FChatGPT-API-unity/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mochi-neko%2FChatGPT-API-unity/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mochi-neko","download_url":"https://codeload.github.com/mochi-neko/ChatGPT-API-unity/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252895527,"owners_count":21821177,"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":["chatgpt-api","unity"],"created_at":"2024-08-03T01:01:23.239Z","updated_at":"2025-05-07T14:30:55.636Z","avatar_url":"https://github.com/mochi-neko.png","language":"C#","funding_links":[],"categories":["Project List"],"sub_categories":["\u003cspan id=\"tool\"\u003eLLM (LLM \u0026 Tool)\u003c/span\u003e"],"readme":"# ChatGPT-API-unity\n\nA client library of [ChatGPT chat completion API](https://platform.openai.com/docs/api-reference/chat/create) for Unity.\n\nSee also official [document](https://platform.openai.com/docs/guides/chat) and [API reference](https://platform.openai.com/docs/api-reference/chat).\n\n## How to import by Unity Package Manager\n\nAdd following dependencies to your `/Packages/mainfest.json`.\n\n```json\n{\n  \"dependencies\": {\n    \"com.mochineko.chatgpt-api\": \"https://github.com/mochi-neko/ChatGPT-API-unity.git?path=/Assets/Mochineko/ChatGPT_API#0.7.3\",\n    ...\n  }\n}\n```\n\n## How to use chat completion by ChatGPT API\n\n1. Generate API key on [OpenAI](https://platform.openai.com/account/api-keys). (Take care your API key, this is a secret information then you should not open.)\n2. You can specify chat model. (Available models are defined by `Model`.)\n3. Create an instance of `ChatCompletionAPIConnection` with API key and chat model. (This instance memorizes old messages in session.)\n4. You can set system message (prompt) to instruct assistant with your situation by constructor of `ChatCompletionAPIConnection`.\n5. Input user message and call `ChatCompletionAPIConnection.CompleteChatAsync()`.\n6. Response message is in `ChatCompletionResponseBody.ResultMessage` (= `ChatCompletionResponseBody.Choices[0].Message.Content`).\n\nAn essential sample code with [UniTask](https://github.com/Cysharp/UniTask) is as follows:\n\n```csharp\n#nullable enable\nusing System;\nusing System.Threading;\nusing Cysharp.Threading.Tasks;\nusing Mochineko.ChatGPT_API.Memories;\nusing UnityEngine;\n\nnamespace Mochineko.ChatGPT_API.Samples\n{\n    /// \u003csummary\u003e\n    /// A sample component to complete chat by ChatGPT API on Unity.\n    /// \u003c/summary\u003e\n    public sealed class ChatCompletionSample : MonoBehaviour\n    {\n        /// \u003csummary\u003e\n        /// API key generated by OpenAPI.\n        /// \u003c/summary\u003e\n        [SerializeField] private string apiKey = string.Empty;\n\n        /// \u003csummary\u003e\n        /// System message to instruct assistant.\n        /// \u003c/summary\u003e\n        [SerializeField, TextArea] private string systemMessage = string.Empty;\n\n        /// \u003csummary\u003e\n        /// Message sent to ChatGPT API.\n        /// \u003c/summary\u003e\n        [SerializeField, TextArea] private string message = string.Empty;\n\n        /// \u003csummary\u003e\n        /// Max number of chat memory of queue.\n        /// \u003c/summary\u003e\n        [SerializeField] private int maxMemoryCount = 20;\n\n        private ChatCompletionAPIConnection? connection;\n        private IChatMemory? memory;\n\n        private void Start()\n        {\n            // API Key must be set.\n            if (string.IsNullOrEmpty(apiKey))\n            {\n                Debug.LogError(\"OpenAI API key must be set.\");\n                return;\n            }\n\n            memory = new FiniteQueueChatMemory(maxMemoryCount);\n\n            // Create instance of ChatGPTConnection with specifying chat model.\n            connection = new ChatCompletionAPIConnection(\n                apiKey,\n                memory,\n                systemMessage);\n        }\n\n        [ContextMenu(nameof(SendChat))]\n        public void SendChat()\n        {\n            SendChatAsync(this.GetCancellationTokenOnDestroy()).Forget();\n        }\n        \n        [ContextMenu(nameof(ClearChatMemory))]\n        public void ClearChatMemory()\n        {\n            memory?.ClearAllMessages();\n        }\n        \n        private async UniTask SendChatAsync(CancellationToken cancellationToken)\n        {\n            // Validations\n            if (connection == null)\n            {\n                Debug.LogError($\"[ChatGPT_API.Samples] Connection is null.\");\n                return;\n            }\n\n            if (string.IsNullOrEmpty(message))\n            {\n                Debug.LogError($\"[ChatGPT_API.Samples] Chat content is empty.\");\n                return;\n            }\n\n            ChatCompletionResponseBody response;\n            try\n            {\n                await UniTask.SwitchToThreadPool();\n                \n                // Create message by ChatGPT chat completion API.\n                response = await connection.CompleteChatAsync(\n                        message,\n                        cancellationToken);\n            }\n            catch (Exception e)\n            {\n                // Exceptions should be caught.\n                Debug.LogException(e);\n                return;\n            }\n\n            await UniTask.SwitchToMainThread(cancellationToken);\n\n            // Log chat completion result.\n            Debug.Log($\"[ChatGPT_API.Samples] Result:\\n{response.ResultMessage}\");\n        }\n    }\n}\n```\n\nSee also [Sample](./Assets/Mochineko/ChatGPT_API.Samples/ChatCompletionSample.cs).\n\n## How to use chat completion by ChatGPT API more resilient\n\nSee `RelentChatCompletionAPIConnection` and `RelentChatCompletionSample`\n using [Relent](https://github.com/mochi-neko/Relent).\n\nYou can use API with explicit error handling, retry, timeout, bulkhead, and so on.\n\n```json\n{\n  \"dependencies\": {\n    \"com.mochineko.chatgpt-api.relent\": \"https://github.com/mochi-neko/ChatGPT-API-unity.git?path=/Assets/Mochineko/ChatGPT_API.Relent#0.7.3\",\n    \"com.mochineko.chatgpt-api\": \"https://github.com/mochi-neko/ChatGPT-API-unity.git?path=/Assets/Mochineko/ChatGPT_API#0.7.3\",\n    \"com.mochineko.relent\": \"https://github.com/mochi-neko/Relent.git?path=/Assets/Mochineko/Relent#0.2.0\",\n    \"com.cysharp.unitask\": \"https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask\",\n    ...\n  }\n}\n```\n\n## How to calculate token length of text in local\n\nYou can calculate token length of text\n by `TiktokenSharp.Tiktoken.Encode(string)` as follows:\n\n```csharp\nusing TiktokenSharp;\n\nprivate int CalculateTokenLength()\n{\n    string text = \"A text that you want to calculate token length.\";\n\n    // Specify model name.\n    Tiktoken tiktoken = TikToken.EncodingForModel(\"gpt-3.5-turbo\");\n    \n    // Encoding is tokenizing.\n    int[] tokens = tikToken.Encode(text);\n    \n    return tokens.Length;\n}\n```\n\nIf you want to calculate on Unity editor,\n please use `ItemuMenu \u003e Mochineko \u003e TiktokenEditor` window.\n\n## How to customize chat memories\n\nYou can use customized memories of chat by implementing `IChatMemory` interface.\n\nPresets are available:\n\n- `FiniteQueueChatMemory`\n  - A queue that has max number of messages.\n- `FiniteQueueWithFixedPromptsChatMemory`\n  - A queue that has max number of user/assistant messages and free number of prompts (system messages).\n- `FiniteTokenLengthQueueChatMemory`\n  - A queue that has max number of token lenght of all messages.\n- `FiniteTokenLengthQueueWithFixedPromptsChatMemory`\n  - A queue that has max number of token lenght of user/assistant messages and free number of prompts (system messages).\n\n## How to stream response\n\nSee [streaming sample](./Assets/Mochineko/ChatGPT_API.Samples/ChatCompletionAsStreamSample.cs).\n\nYou can await foreach as follows:\n\n```csharp\nvar builder = new StringBuilder();\n // Receive enumerable from ChatGPT chat completion API.\nvar enumerable = await connection.CompleteChatAsStreamAsync(\n    message,\n    cancellationToken);\n\nawait foreach (var chunk in enumerable.WithCancellation(cancellationToken))\n{\n    // First chunk has only \"role\" element.\n    if (chunk.Choices[0].Delta.Content is null)\n    {\n        Debug.Log($\"[ChatGPT_API.Samples] Role:{chunk.Choices[0].Delta.Role}.\");\n        continue;\n    }\n    \n    var delta = chunk.Choices[0].Delta.Content;\n    builder.Append(delta);\n    Debug.Log($\"[ChatGPT_API.Samples] Delta:{delta}, Current:{builder}\");\n}\n\n// Log chat completion result.\nDebug.Log($\"[ChatGPT_API.Samples] Completed: \\n{builder}\");\n```\n.\n\n## How to use function calling\n\n1. Define function with JSON schema.\n2. Specify function by request parameters.\n3. Call chat completion API.\n4. Use `result.Choices[0].Message.FunctionCall` \n\nSee `FunctionCalling()` in [test code](./Assets/Mochineko/ChatGPT_API.Tests/ChatCompletionAPIConnectionTest.cs).\n\n## Changelog\n\nSee [CHANGELOG](./CHANGELOG.md).\n\n## 3rd Party Notices\n\nSee [NOTICE](./NOTICE.md).\n\n## License\n\nLicensed under the [MIT](./LICENSE) license.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmochi-neko%2FChatGPT-API-unity","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmochi-neko%2FChatGPT-API-unity","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmochi-neko%2FChatGPT-API-unity/lists"}