Giter Site home page Giter Site logo

srcnalt / openai-unity Goto Github PK

View Code? Open in Web Editor NEW
604.0 14.0 135.0 1.11 MB

An unofficial OpenAI Unity Package that aims to help you use OpenAI API directly in Unity Game engine.

License: MIT License

C# 100.00%
chatgpt openai openai-api unity unity3d dalle whisper

openai-unity's Introduction

Twitter

OpenAI Unity Package

An unofficial Unity package that allows you to use the OpenAI API directly in the Unity game engine.

How To Use

Youtube Tutorials

You can find dedicated video tutorials for how to use this package in this YouTube playlist.

https://www.youtube.com/playlist?list=PLrE-FZIEEls1-c7QifZYzeq50Id08FcJo

image

Importing the Package

To import the package, follow these steps:

Setting Up Your OpenAI Account

To use the OpenAI API, you need to have an OpenAI account. Follow these steps to create an account and generate an API key:

Saving Your Credentials

To make requests to the OpenAI API, you need to use your API key and organization name (if applicable). To avoid exposing your API key in your Unity project, you can save it in your device's local storage.

To do this, follow these steps:

  • Create a folder called .openai in your home directory (e.g. C:User\UserName\ for Windows or ~\ for Linux or Mac)
  • Create a file called auth.json in the .openai folder
  • Add an api_key field and a organization field (if applicable) to the auth.json file and save it
  • Here is an example of what your auth.json file should look like:
{
    "api_key": "sk-...W6yi",
    "organization": "org-...L7W"
}

You can also pass your API key into OpenAIApi ctor when creating an instance of it but again, this is not recommended!

var openai = new OpenAIApi("sk-Me8...6yi");

IMPORTANT: Your API key is a secret. Do not share it with others or expose it in any client-side code (e.g. browsers, apps). If you are using OpenAI for production, make sure to run it on the server side, where your API key can be securely loaded from an environment variable or key management service.

Making Requests to OpenAPI

You can use the OpenAIApi class to make async requests to the OpenAI API.

All methods are asynchronous and can be accessed directly from an instance of the OpenAIApi class.

Here is an example of how to make a request:

private async void SendRequest()
{
    var req = new CreateChatCompletionRequest
    {
        Model = "gpt-3.5-turbo",
        Messages = new List<ChatMessage>()
        {
            new ChatMessage()
            {
                Role = "user",
                Content = "Hello!"
            }
        }
    };
    var res = await openai.CreateChatCompletion(req);
}

To make a stream request, you can use the CreateCompletionAsync and CreateChatCompletionAsync methods. These methods are going to set Stream property of the request to true and return responses through an onResponse callback. In this case text responses are stored in Delta property of the Choices field in the Chat Completion.

var req = new CreateChatCompletionRequest{
    Model = "gpt-3.5-turbo",
    Messages = new List<ChatMessage>
    {
        new ChatMessage()
        {
            Role = "user",
            Content = "Write a 100 word long short story in La Fontaine style."
        }
    },
    Temperature = 0.7f,
};
    
openai.CreateChatCompletionAsync(req, 
    (responses) => {
        var result = string.Join("", responses.Select(response => response.Choices[0].Delta.Content));
        Debug.Log(result);
    }, 
    () => {
        Debug.Log("completed");
    }, 
    new CancellationTokenSource()
);

Sample Projects

This package includes two sample scenes that you can import via the Package Manager:

  • ChatGPT sample: A simple ChatGPT like chat example.
  • DallE sample: A DALL.E text to image generation example.

Known Issues

  • Can't See the Image Result in WebGL Builds: Due to CORS policy of OpenAI image storage in local WebGL builds you will get the generated image's URL however it will not be downloaded using UnityWebRequest until you run it out of localhost, on a server.

  • Streamed Response is just blank in WebGL Build: Unity 2020 WebGL has a bug where stream responses return empty. You can update and try with a newer version of Unity.

Supported Unity Versions for WebGL Builds

The following table shows the supported Unity versions for WebGL builds:

Unity Version Windows Linux MacOS WebGL Android IOS Oculus 2
2022.3.x ⚠️ ⚠️ ⚠️
2021.3.x ⚠️ ⚠️ ⚠️
2020.3.x ⚠️ ⚠️ ⚠️
2019.4.x ⚠️ ⚠️ ⚠️ ⚠️ ⚠️ ⚠️
✅ = Supported ⚠️ = Not Tested ⛔ = Not Supported

Please report any issues you encounter with builds.

Further Reading

For more information on how to use the various request parameters, please refer to the OpenAI documentation: https://platform.openai.com/docs/api-reference

openai-unity's People

Contributors

srcnalt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openai-unity's Issues

Setting lengthSec longer than duration, ending it early, causes strange behavior

Describe the bug
I'm trying to make the clip length dynamic by toggling the recording with a button instead of fixed length recording. So I set the lengthSec to 89 as whisper probably rounds it to the nearest second anyway, but it gives odd results.

This is not the case with using the default duration of 5 and letting the timer end the recording.

To Reproduce
Steps to reproduce the behavior:

  1. clip = Microphone.Start(dropdown.options[index].text, false, 89, 44100);
  2. Fire Microphone.End(null) before the time limit

Expected behavior
Should end the recording and process it.

Screenshots

  1. Said "1 2 3 4 5 6 7 8" only, but the transcript repeats it multiple times and sent even a URL back.
    Screenshot 2023-09-29 121035

  2. Said "1 2 3 4 3 2 1" only, but the transcript not only repeated it, it started counting up out of nowhere.
    Screenshot 2023-09-29 115604

  3. Said "1 2 3 4 3 2 1" only, but in the transcript was repeated many times
    Screenshot 2023-09-29 123031

Environment (please complete the following information):

  • OS: Windows 10
  • Unity Version [e.g. 2022.3.1f1]
  • Plugin Version [e.g. 0.1.0]

Additional context
Is this because the recording doesn't end there? Or when setting a clip length it creates a file that long and fills it up with data? How could this be achieved to have a conversation and not wait until the timer ends?

Import Error in Unity

I cannot import the package into Unity.

Steps to reproduce the behavior:

  1. When importing the package in Unity I get the Error:

_[Package Manager Window] Error adding package: https://github.com/srcnalt/OpenAI-Unity.git.
Unable to add package [https://github.com/srcnalt/OpenAI-Unity.git]:
Error when executing git command. fatal: not in a git directory

UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()_

  1. I am working with Unity version 2022.3.11f1

  2. I already get an error message in Unity when opening the package manager:

[Package Manager Window] Error searching for packages. An error occurred, likely on the server. Please try again later.
Unable to perform online search:
Request [GET https://packages.unity.com/-/api/search?host=editor&provider=enterprise] failed with status code [502]
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

Not sure wether it has anything to do with the error importing the package here.

I'm a complete amateur using Unity so any help is appreciated!

NullReferenceException: Object reference not set to an instance of an object

I followed all the steps but when I push the button to send the text I always receive this error message:

NullReferenceException: Object reference not set to an instance of an object
OpenAI.ChatGPT.SendReply () (at Assets/Samples/OpenAI Unity/0.1.0/ChatGPT/ChatGPT.cs:41)

I have checked all the rederences in the editor ( the ChatGPT publics ) and all are correct.

I'm using Unity 2021.3.0f1 on a Mac.

Any help is welcome. Thanks!

Accessing different models

Thank you for all of your hard work on this and for making it available.

I'm trying to change the model per OpenAI documentation. Accessing GPT 3.5 models works just fine.

var completionResponse = await openai.CreateChatCompletion(new CreateChatCompletionRequest()
      {
          Model = "gpt-3.5-turbo-0301",
          Messages = messages
      });

But if I try to pass other models, particularly GPT 3 modes, to the constructor:

Model = "gpt-3-turbo-0301"
Model = "gpt-3-text-ada-001"
Model = "gpt-3.0-turbo-0301"

It return the following error message.

Error Message: The model gpt-3-text-ada-001 does not exist

Does this only support GPT-3.5 ?

Model currently overloaded

This might be an issue or I may have missed something.

I've been intermittently receiving the following error in the console:

Error Message: That model is currently overloaded with other requests. You can retry your request, or contact us through our help center at help.openai.com if the error persists. (Please include the request ID 5afba5db32f54f11340d57aebeaf640d in your message.)
Error Type: server_error

UnityEngine.Debug:LogError (object)
OpenAI.OpenAIApi/<DispatchRequest>d__6`1<OpenAI.CreateChatCompletionResponse>:MoveNext () (at Library/PackageCache/com.srcnalt.openai-unity@5924018f2c/Runtime/OpenAIApi.cs:85)
UnityEngine.UnitySynchronizationContext:ExecuteTasks ()

It's obvious that OpenAI / ChatGPT's API is busy but Is there are way to catch and redirect this error?

I'm new to Unity (JavaScript developer), normally I would wrap network request in a Try Catch block, but I'm not sure if this throws an exception or just logs the issue to console.

Create transcription request results in a No JSON content found error

Describe the bug
Create transcription request is not working on il2cpp, I am getting this error message when a request is sent, seems like a Newtonsoft json issue, was wondering if anyone had encountered it
image

"Newtonsoft.Json.JsonSerializationException: No JSON content found and type \'OpenAI.CreateAudioResponse\' is not nullable. Path \'\', line 0, position 0.\n  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x00057] in C:\\Users\\Adrien\\Workspace\\Newtonsoft\\Newtonsoft.Json-for-Unity-Pedro\\Src\\Newtonsoft.Json\\Serialization\\JsonSerializerInternalReader.cs:159 \n  at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in C:\\Users\\Adrien\\Workspace\\Newtonsoft\\Newtonsoft.Json-for-Unity-Pedro\\Src\\Newtonsoft.Json\\JsonSerializer.cs:904 \n  at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00003] in C:\\Users\\Adrien\\Workspace\\Newtonsoft\\Newtonsoft.Json-for-Unity-Pedro\\Src\\Newtonsoft.Json\\JsonSerializer.cs:883 \n  at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x00030] in C:\\Users\\Adrien\\Workspace\\Newtonsoft\\Newtonsoft.Json-for-Unity-Pedro\\Src\\Newtonsoft.Json\\JsonConvert.cs:831 \n  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x0000c] in C:\\Users\\Adrien\\Workspace\\Newtonsoft\\Newtonsoft.Json-for-Unity-Pedro\\Src\\Newtonsoft.Json\\JsonConvert.cs:787 \n  at OpenAI.OpenAIApi.DispatchRequest[T] (System.String path, System.Collections.Generic.List`1[T] form) [0x00166] in C:\\Users\\kenpc\\Unity\\TheSafeOne\\Library\\PackageCache\\com.srcnalt.openai-unity@d2a258ab0c\\Runtime\\OpenAIApi.cs:177

To Reproduce
Steps to reproduce the behavior:

  1. Run the transcription sample, add a try catch on the createTranscriptionRequest line first
  2. Run the debugger, or check if it gets stuck
  3. See error

Expected behavior
It should not throw an error

Environment (please complete the following information):

  • OS: Android built with il2cpp
  • Unity Version 2021.3.25f1
  • Plugin Version 0.1.15

I got a problem with Json not reading properly on 0.1.11 version

This is what's been thrown at me:

JsonReaderException: Invalid property identifier character: “. Path '', line 2, position 1.
Newtonsoft.Json.JsonTextReader.ParseProperty () (at /root/repo/Src/Newtonsoft.Json/JsonTextReader.cs:1600)
Newtonsoft.Json.JsonTextReader.ParseObject () (at /root/repo/Src/Newtonsoft.Json/JsonTextReader.cs:1571)
Newtonsoft.Json.JsonTextReader.Read () (at /root/repo/Src/Newtonsoft.Json/JsonTextReader.cs:432)
Newtonsoft.Json.JsonReader.ReadAndAssert () (at /root/repo/Src/Newtonsoft.Json/JsonReader.cs:1169)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs:464)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs:309)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs:202)
Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/JsonSerializer.cs:904)
Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/JsonSerializer.cs:883)
Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:831)
Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:787)
OpenAI.Configuration..ctor (System.String apiKey, System.String organization) (at Library/PackageCache/com.srcnalt.openai-unity@5924018f2c/Runtime/Configuration.cs:33)
OpenAI.OpenAIApi.get_Configuration () (at Library/PackageCache/com.srcnalt.openai-unity@5924018f2c/Runtime/OpenAIApi.cs:28)
OpenAI.OpenAIApi.DispatchRequest[T] (System.String path, System.String method, System.Byte[] payload) (at Library/PackageCache/com.srcnalt.openai-unity@5924018f2c/Runtime/OpenAIApi.cs:73)
OpenAI.OpenAIApi.CreateChatCompletion (OpenAI.CreateChatCompletionRequest request) (at Library/PackageCache/com.srcnalt.openai-unity@5924018f2c/Runtime/OpenAIApi.cs:179)
OpenAI.ChatGPT.SendReply () (at Assets/Samples/OpenAI Unity/0.1.11/ChatGPT/ChatGPT.cs:59)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) (at :0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <4a31731933e0419ca5a995305014ad37>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <4a31731933e0419ca5a995305014ad37>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <4a31731933e0419ca5a995305014ad37>:0)

WebGL Authentication

Basically I have the same issue as this: #45
and this: #47

These are markes as resolved but I didn't find any solution (and looks like the authors didn't either?)
This is the error message:
{
"error": {
"message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",
"type": "invalid_request_error",
"param": null,
"code": null
}
}

It happens ONLY in WebGL builds, not in the editor. No problem with the API key, as I pass it directly into the constructor. Tested in 2020.3.0f1, 2021.3.22f1, and 2022.2.19f1 so not a Unity version error.

There's something going on and I need a workaround to get a testable WEBGL build.

JsonSerializationException Error

JsonSerializationException: Could not find member 'id' on object of type 'CreateCompletionResponse'. Path 'id', line 1, position 6.
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject (System.Object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.String id) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs:2433)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs:502)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs:309)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs:202)
Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/JsonSerializer.cs:904)
Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/JsonSerializer.cs:883)
Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:831)
Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:787)
OpenAI.OpenAIApi.DispatchRequest[T] (System.String path, System.Net.Http.HttpMethod method, System.Byte[] payload) (at Library/PackageCache/com.srcnalt.openai-unity@36ddc4ce71/Runtime/OpenAIApi.cs:70)
OpenAI.OpenAIApi.CreateCompletion (OpenAI.CreateCompletionRequest request) (at Library/PackageCache/com.srcnalt.openai-unity@36ddc4ce71/Runtime/OpenAIApi.cs:148)
OpenAI.ChatGPT.SendReply () (at Assets/Samples/OpenAI Unity/0.1.4/ChatGPT/ChatGPT.cs:34)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) (at <1f66344f2f89470293d8b67d71308c07>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <4014a86cbefb4944b2b6c9211c8fd2fc>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <4014a86cbefb4944b2b6c9211c8fd2fc>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <4014a86cbefb4944b2b6c9211c8fd2fc>:0)

Need the headers to be customizable

For usage not straightly go to the OpenAI official web, it need the header to be edited for like security usage. Really thanks if you implement it!

ChatCompletion Response is sometimes empty

Hello.
I use ChatCompletion with Stream=true

I have an issue. Sometimes the responses of CreateChatCompletionAsync is empty.
image

image

I have created a system that wait 3sec and try again but often the response is always empty.

I tried with Insmonia/Postman with streaming mode and the responses is never empty.

What can I do ?

When microphone is off I get the word "you" in the "Text" field in the API response with Whisper

Describe the bug
Most often when the microphone is muted or there is no sound around I get the word "you" in the "Text" field from the API response to the Whisper API which is wired there should be nothing just an empty string.

To Reproduce
Steps to reproduce the behavior:

  1. Go to the Whisper Sample scene and add this line to the Whisper code in the EndRecording method: Debug.Log("response: " + res.Serialize());.
  2. Click on Play and mute your microphone.
  3. Scroll down on the console and see the result of the line we add in step 1.
  4. See the error.

Expected behavior
When there is no sound around or the microphone is muted the "Text" field from the response of the Whisper API should have a value of an empty string "" not the word "you".

Screenshots
image

Environment

  • OS: Windows 10 Pro
  • Unity Version: 2021.3.19f1
  • Plugin Version: 0.1.12

Does this SDK support related questions?

Hi, thanks for your SDK, I wonder does it support related questions?
For example, I asked three questions, the second and third questions are related to the first one, and it seems that I can't get a satisfactory answer.

Response text from ChatGPT is getting truncated.

Hi, I am trying out the ChatGPT sample project. I am sending following text to ChatGPT:

Instruction: Act as a professional chef and reply to the questions.
Q: tell me a recipe of healthy dish made using coconuts
A:

And the response is:
Instruction: Act as a professional chef and reply to the questions.
Q: tell me a recipe of healthy dish made using coconuts
A: Coconut Chicken Soup is a delicious and healthy dish! Here’s what you’ll need:

Ingredients:

  • 2 Tablespoons vegetable oil
  • 1 Onion, finely chopped
  • 2 Garlic cloves, minced
  • 1 Carrot, grated
  • 2 cups diced cooked chicken
  • 2 cups low-sodium chicken stock
  • 2 cups coconut milk
  • 1 teaspoon curry powder
  • Salt and pepper, to taste
  • 1/4 cup finely chopped fresh cilantro

Instructions:

  1. Heat the oil in a large pot
    Q:

Screenshot 2023-03-04 210741

"Tests" can conflict with existing project's tests

@srcnalt As the tests .asmdef file is named "Tests" and included in the GitHub repo, if users have their own Tests assembly defined in their project, it'll cause compilation errors on import. Probably best to rename your Tests assembly to something that won't conflict.

JsonSerializationException: Could not find member 'warning' on object of type 'CreateChatCompletionResponse'. Path 'warning', line 2, position 12.

  1. I use this to run is okay on July 11 & 12 (Taipei time).
  2. but run it to have error on July 13 (Taipei time), even I create new unity project (pure) to test/run.
    Error log:
    JsonSerializationException: Could not find member 'warning' on object of type 'CreateChatCompletionResponse'. Path 'warning', line 2, position 12.
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject (System.Object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.String id) (at <761cf2a144514d2291a678c334d49e9b>:0)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) (at <761cf2a144514d2291a678c334d49e9b>:0)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember,

Environment (please complete the following information):

  • OS: [e.g. Windows 11
  • Unity Version 2022.3.1f1
  • Openai-Unity: 0.1.14

errorLog

JsonSerializationException: Could not find member 'id' on object of type 'CreateChatCompletionResponse' v0.1.12

Hey @srcnalt , I'm seeing this issue in v0.1.12 with Unity 2022.2.16 running WebGL builds. Here is the JSON returned by OpenAI Chat Completion:

{"id":"chatcmpl-7Blu4ha7YR834teg22T0XYBdBk77D","object":"chat.completion","created":1683040104,"model":"gpt-3.5-turbo-0301","usage":{"prompt_tokens":70,"completion_tokens":58,"total_tokens":128},"choices":[{"message":{"role":"assistant","content":"Hello, it is a pleasure to be chatting with you today.\n\nI am feeling quite content at the moment, thank you for asking. How about yourself?\n\nDo you have any questions for me? I am happy to share my thoughts and insights on science, philosophy, and life in general."},"finish_reason":"stop","index":0}]}

But the library is throwing this error via Newtonsoft:

app.framework.js.br:10 JsonSerializationException: Could not find member 'id' on object of type 'CreateChatCompletionResponse'. Path 'id', line 1, position 6.
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject (System.Object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.String id) [0x00000] in <00000000000000000000000000000000>:0
--- End of stack trace from previous location where exception was thrown ---

Anything else I should adjust to get this to work?

Seems long response will be cut out

Hi, thanks for your SDK, but I got a problem. For instance, I ask "I'm late for class, help me write a 200-word review", and the response was not analyzed correctly. It seems to be cut out, and only shows a small part in front. The "finish reason" for the response.Choices[0] is "length".

Snipaste_2023-02-02_10-29-41

Snipaste_2023-02-02_10-31-35

Respond is just you

When I use the sample scene I just get "you" as a response. Doesn't matter what microphone or what I say.

OpenAI Package cannot import

Hi, i'm following your tutorial, but i'm having issues to import OpenAI package from git URL.

Some idea how fix it? It seems like a issue from the package git.

Screenshot_64

Invalid Request Error

I am getting this error:
UnityEngine.Debug:LogError (object)
OpenAI.OpenAIApi/d__6`1<OpenAI.CreateCompletionResponse>:MoveNext () (at Library/PackageCache/com.srcnalt.openai-unity@8d6d57d5ae/Runtime/OpenAIApi.cs:88)
UnityEngine.UnitySynchronizationContext:ExecuteTasks ()

Any Idea on how to fix it?

How to solve GPT-4 turbo (gpt-4-1106-preview) error

edit DataTypes.cs

    public struct CreateChatCompletionResponse : IResponse
    {
        public ApiError Error { get; set; }
        public string Model { get; set; }
        public string Id { get; set; }
        public string Object { get; set; }
        public long Created { get; set; }
        public List<ChatChoice> Choices { get; set; }
        public Usage Usage { get; set; }
        // Add these fields
        public string SystemFingerprint { get; set; }
    }

now you can use gpt-4-1106-preview model.

Android build does not work

On Unity, the program works flawless. I tried to build it for android. OpenAI does not answer on apk. Is it because we call ApiKey from our computer? If it is how can i implement api key on script? If it isn't what should i do to make this work?

Android issue

Describe the bug
This is not working in the Unity android build when i try to do speech to text it records the audio transcipting it but does not return the words i have said

Null reference related to layout rebuilder

I'm not sure if any of you are experiencing this but I keep getting a null reference error everytime I click the send button. I'm not sure where the problem is located because when I checked if I have everything correctly it shows that I have and the problem is also not code based as far as I can see, to my knowledge at least.

I just went to my application, then run the start button, go to the NPC and speak to her and then see the error pop up.

Schermafbeelding 2023-06-12 153330

What is supposed to happen is that the character should be responding after the send button is clicked

Schermafbeelding 2023-06-12 153330

Schermafbeelding 2023-06-12 153537

Schermafbeelding 2023-06-12 153631
Schermafbeelding 2023-06-12 153651
Schermafbeelding 2023-06-12 153704

OS: Windows 11
Unity Version 2021.3.20f1
I used the latest version of this plugin for unity

some words in the pictures are dutch

today update 0.1.11 error

JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

Newtonsoft.Json.JsonTextReader.ParseValue () (at /root/repo/Src/Newtonsoft.Json/JsonTextReader.cs:1817)
Newtonsoft.Json.JsonTextReader.Read () (at /root/repo/Src/Newtonsoft.Json/JsonTextReader.cs:429)
Newtonsoft.Json.JsonReader.ReadAndMoveToContent () (at /root/repo/Src/Newtonsoft.Json/JsonReader.cs:1240)
Newtonsoft.Json.JsonReader.ReadForType (Newtonsoft.Json.Serialization.JsonContract contract, System.Boolean hasConverter) (at /root/repo/Src/Newtonsoft.Json/JsonReader.cs:1197)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs:202)
Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/JsonSerializer.cs:904)
Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/JsonSerializer.cs:883)
Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:831)
Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:787)
OpenAI.OpenAIApi.DispatchRequest[T] (System.String path, System.String method, System.Byte[] payload) (at Library/PackageCache/com.srcnalt.openai-unity@5924018f2c/Runtime/OpenAIApi.cs:79)
OpenAI.OpenAIApi.CreateChatCompletion (OpenAI.CreateChatCompletionRequest request) (at Library/PackageCache/com.srcnalt.openai-unity@5924018f2c/Runtime/OpenAIApi.cs:179)
OpenAI.ChatGPT.SendReply () (at Assets/Samples/OpenAI Unity/0.1.11/ChatGPT/ChatGPT.cs:59)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) (at :0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at :0)
UnityEngine.UnitySynchronizationContext.Exec () (at :0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at :0)

Handle error in async void DispatchRequest

Hi,

I found some issues when request.downloadHandler.text retrieve an error message.

Because the lines retrieved are like that
ErrorMessageHandle

and after you try to convert them with: var data = JsonConvert.DeserializeObject(value, jsonSerializerSettings);
But this give a error exception because the json format is not correct.

I have done some changes to fix this
https://codefile.io/f/HWLrBZPdhh

Tell me if it's look good for you my fixes.

Request: Streaming completions

Thanks for this well crafted package!

I have a request, could you please add Streaming to completions?
As described in the API:
stream boolean Optional Defaults to false
Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events] as they become available, with the stream terminated by a data: [DONE] message.

With media type "application/octet-stream"

Conflict between PlasticSCM and srcnalt.openAI-Unity

Here is the bug report in detail.

\Library/PackageCache/com.srcnalt.openai-unity@ef49d3b/Runtime/Configuration.cs(14,26): error CS0433: The type 'JsonSerializerSettings' exists in both 'Newtonsoft.Json.Net20, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' and 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

Library/PackageCache/com.srcnalt.openai-unity@ef49d3baf3/Runtime/OpenAIApi.cs(45,26): error CS0433: The type 'JsonSerializerSettings' exists in both 'Newtonsoft.Json.Net20, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' and 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

Auth Error on WebGL

Within the editor things communicate fine with OpenAI but when building and running a WebGL build I get the following response:

{
"error": {
"message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",
"type": "invalid_request_error",
"param": null,
"code": null
}
}

Why is it the apiKey headers are not being passed on WebGL builds?

Readme is invalid

var req = new CreateCompletionRequest{
    Model = "text-davinci-003",
    Prompt = "Say this is a test.",
    MaxTokens = 7,
    Temperature = 0
};
    
openai.CreateCompletionAsync(req, 
    (responses) => {
        var result = string.Join("", responses.Select(response => response.Choices[0].Delta.Content));
        Debug.Log(result);
    }, 
    () => {
        Debug.Log("completed");
    }, 
    new CancellationTokenSource());
}

Should be

var req = new CreateCompletionRequest{
    Model = "text-davinci-003",
    Prompt = "Say this is a test.",
    MaxTokens = 7,
    Temperature = 0
};
    
openai.CreateCompletionAsync(req, 
    (responses) => {
        var result = string.Join("", responses.Select(response => response.Choices[0].Text));
        Debug.Log(result);
    }, 
    () => {
        Debug.Log("completed");
    }, 
    new CancellationTokenSource());
}

GPT 4 Model

I can work with the GPT3 model but when I tried to change to model name to one of the GPT4 models, the project didn't crash and didn't give any auth. error but it says it is a GPT3 model and no idea about GPT4. Is this an issue or just the wrong use?
I am new to AI models, so any help is appreciated!

"No text was generated from this prompt" on Quest 2 VR device

Thank you for sharing a fantastic project!
I was able to make it run well on the Unity editor. However, when it runs on Meta Quest 2 device (Android), I always get "No text was generated from this prompt." Double-checked API Keys and internet access permission but found no issues. (When I intentionally put the wrong API key, it gives me an API key error. Also, other components in my app require internet access and work well)
Any suggestions would be appreciated!

Invalid expression term on Import

hi, i've just imported the package into unity (2019.4.38f1c1 LTS) on windows and it immediately gives me the following error:

Library\PackageCache\com.srcnalt.openai-unity@f06833f\Runtime\OpenAIApi.cs(19,64): error CS1525: Invalid expression term '='

it seems to refer to the line: private Configuration Configuration => configuration ??= new Configuration();

Would you happen to know what the problem could be?

Thanks!

how can i add max_tokens: 100

Hello, Scarlett
I have been using this project for some time, and sometimes chatgpt replies to me with long tokens. I want to reduce its response. But cannot add 'max_tokens': max_ Tokens, what can I do。

Not working with WebGL builds

Hi @srcnalt , thanks for this amazing project!
As with previous similar issues, I am stuck with my WebGL build. It works well in the editor but not in the web version where I got an error 400 when posting to https://api.openai.com/v1/chat/completions (ie, when sending a message) from the game hosted on my website.

I am developing on MacOS (M1 chip) and the editor version is 2021.3.22f1.
I tried to pull the latest code from the repo but still do not solve the issue.

Some of my build settings that might be of interest are attached.
Any help would be really appreciated :)

I'll keep you updated if I find any solution in the meantime.

Cheers.

Capture d’écran 2023-04-25 à 13 06 19

Capture d’écran 2023-04-25 à 13 05 59

JsonSerializationException on CreateChatCompletion

Describe the bug
Calling CreateChatCompletion results in a JsonSerializationException when attempting to deserialize the CreateChatCompletionResponse object. Full error: JsonSerializationException: Could not find member 'system_fingerprint' on object of type 'CreateChatCompletionResponse'. Path 'system_fingerprint', line 21, position 23.

To Reproduce
Steps to reproduce the behavior:

  1. Call the following:

var completionResponse = await openai.CreateChatCompletion(new CreateChatCompletionRequest()
{
Model = "gpt-4-1106-preview",
Messages = [list of messages],
Temperature = 0.0f,
}

Expected behavior
A populated completionResponse.

Environment:

  • OS: MacOS Ventura version 13.4
  • Unity Version [e.g. 2022.3.7f1]
  • Plugin Version [e.g. 0.1.5]

Context:
This was working yesterday. Maybe the OpenAI API updated?

not working on IOS

hello , I am trying to include this Api to phone application , the app work fin in editor but when I build it in device it won't work.
I saw a simulare issue here #19 and the solution was to change backend script from IL2CPP to Mono and it works find on android but IOS only accept IL2CPP.
Is there any solution ?

Dall-E 3

Does the current project here support Dall-E 3?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.