Code Monkey home page Code Monkey logo

chatgpt.net's Introduction

chatgpt.net's People

Contributors

caulm avatar pawanosman avatar yinyihao1 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

chatgpt.net's Issues

Response status code does not indicate success: 429 (Too Many Requests).

I had get 429 issue.
Anyone can help me?

private bool createChatGptObj()
{
bool success = false;

        try
        {
            _gptObj = new ChatGpt(_apiKey);
            _gptObj.SetConversations(new List<Net.DTO.ChatGPT.ChatGptConversation>()
            {
                new Net.DTO.ChatGPT.ChatGptConversation(),
            });

            success = true;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        return success;
    }

    private async void askAndReponse(string question)
    {
        await _gptObj.AskStream(response =>
        {
            this.Invoke(new Action(() =>
            {
                rtbMessage.AppendText(response);
            }));

        }, question);
    }

Exception in chatGpt.CreateClient

My environment:
.Net 6.0, Windows 10
I have installed playwright.ps1, referring to issue #1.

My steps:
When calling chatGpt.WaitForReady(), the Chromium browser can pop up and display the login page.
Then, when calling chatGpt.CreateClient with my SessionToken, the program throws an exception, saying: One or more errors occurred (Response status code does not indicate success: 403 (Forbidden).), while nothing changes in the browser.

I tried to login manually in this pop-up browser, using Google account, but it said: can not log in because this browser or application may not be secure. Not sure if it is as expected.
In addition, I'm using VPN to access openai.com. Maybe a proxy problem?

Do you have any suggestions?
Thank you

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ChatGPT.Net.DTO.ChatGPTUnofficial.ChatGptUnofficialMessageResponse' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

I use a snippet from the example code for the ChatGptUnofficial class

            var bot = new ChatGptUnofficial("I put my session ID here");

            // get response
            var response = await bot.Ask("What is the weather like today?"); // <- this line gives the exception
            Console.WriteLine(response);

            // stream response
            await bot.AskStream(response => {
                Console.WriteLine(response);
            }, "What is the weather like today?");

Exception:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ChatGPT.Net.DTO.ChatGPTUnofficial.ChatGptUnofficialMessageResponse' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.'

The program tries running the line for a good few sessions then gives the exception.

The input is not a valid Base-64 string as it contains a non-base 64 character

An exception is thrown when ChatGptUnofficial.Ask is called for the second time.

Message:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
Stack Trace:

在 System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
在 System.Convert.FromBase64String(String s)
在 ChatGPT.Net.ChatGptUnofficial.ValidateToken(String token) 在 E:\Mirai-console\livebot\source\ChatGPT.Net\ChatGPTUnofficial.cs 中: 第 200 行
在 ChatGPT.Net.ChatGptUnofficial.<SendMessage>d__33.MoveNext() 在 E:\Mirai-console\livebot\source\ChatGPT.Net\ChatGPTUnofficial.cs 中: 第 208 行
在 ChatGPT.Net.ChatGptUnofficial.<Ask>d__30.MoveNext() 在 E:\Mirai-console\livebot\source\ChatGPT.Net\ChatGPTUnofficial.cs 中: 第 147 行

The length of Base64 encoded string tokenParts[1] is not a multiple of 4. So some '=' are needed to add at the end of the string. (likely to be a flaw in .NET library)

image

Does not work with ChatGPT4

I have an account and pay for ChatGPT4 but if i put in the model as "gpt-4" as suggested in the API documents i get an invalid response

Authorisation header using Bearer Auth

Getting below 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.",

How to add this auth with bearer token ?

An error occurred while sending the request.

I found that sometimes the unofficial API cannot respond when the reply message is too long.
For example, I asked "Perceptual hash algorithm", using ChatGptUnofficial.Ask. Then an exception was thrown.
Message:
An error occurred while sending the request.
Stack trace:

在 System.Net.Http.HttpConnection.<SendAsyncCore>d__62.MoveNext()
在 System.Net.Http.HttpConnectionPool.<SendWithVersionDetectionAndRetryAsync>d__83.MoveNext()
在 System.Threading.Tasks.ValueTask`1.get_Result()
在 System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1.ConfiguredValueTaskAwaiter.GetResult()
在 System.Net.Http.RedirectHandler.<SendAsync>d__4.MoveNext()
在 System.Net.Http.HttpClient.<<SendAsync>g__Core|83_0>d.MoveNext()
在 ChatGPT.Net.ChatGptUnofficial.<SendMessage>d__33.MoveNext() 在 E:\Mirai-console\livebot\source\ChatGPT.Net\ChatGPTUnofficial.cs 中: 第 261 行
在 ChatGPT.Net.ChatGptUnofficial.<Ask>d__30.MoveNext() 在 E:\Mirai-console\livebot\source\ChatGPT.Net\ChatGPTUnofficial.cs 中: 第 147 行

On the webpage, it can be seen that the message was successfully sent and ChatGPT replied a lot.
image
Is there any way to get such a long reply?

api json processing exception caused a crash

Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $.error | LineNumber: 0 | BytePositionInLine: 10.
---> System.InvalidOperationException: Cannot get the value of a token type 'StartArray' as a string.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType)
at System.Text.Json.Utf8JsonReader.GetString()
at System.Text.Json.Serialization.Metadata.JsonPropertyInfo1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader) at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex)
at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable1 actualByteCount) at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 json, JsonTypeInfo jsonTypeInfo)
at SocketIOClient.JsonSerializer.SystemTextJsonSerializer.Deserialize[T](String json, IList`1 bytes)
at SocketIOClient.SocketIOResponse.GetValue[T](Int32 index)
at ChatGPT.Net.Session.ChatGptClient.<>c__DisplayClass70_0.<b__1>d.MoveNext() in /home/ubuntu/Desktop/ChatGPT.Net/src/ChatGPT.Net/Session/ChatGptClient.cs:line 226
--- End of stack trace from previous location ---
at System.Threading.Tasks.Task.<>c.b__128_1(Object state)
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
[1] 4053955 abort (core dumped) dotnet ChatGPT.Net.Web.dll

Getting started example doesn't work as expected

The Getting started usage example on the README page uses the prompt "What is the weather like today?" - which gives this response: I'm sorry, but as an AI, I do not have access to real-time information. Please check your local weather forecast for the most accurate and up-to-date information. Of all the examples you could have given for new users of this library, it seems you chose an example that gives a very unsatisfactory response. As a new user of this library, I am left wondering if this is the correct response or not. Not the best developer experience.

How to define user message size limit for particlular prompt?

My case is content summarization: I provide text and chatgpt to summarize it. How can define user message size limit for this particular prompt, ideally considering language of the user message (as I assume it can also affect)? I mean, I want to identify limit before sending the request, to be able to reduce the content (user message) in advance if it is needed. I can do that using just assumable token based calculation , but maye chatgpt.net itself has some special methods for this purpose?

Another question is - is the token size the same for different requests (with the samу physical amount of symbols)? For example I can ask to summarize text, which is (as I guess) more complicated operation, than lets say to extract first sentence for each text paragraph.

How to specify system message separately from user for the request?

I am using code as below:

 ChatGptOptions options = new ChatGptOptions()
 {
     BaseUrl = "https://api.openai.com", // The base URL for the OpenAI API
     Model = "gpt-3.5-turbo",           // The specific model to use
     Temperature = 0.7,                   // Controls randomness in the response (0-1)
     TopP = 0.9,                         // Controls diversity in the response (0-1)
     MaxTokens = 3500,                   // The maximum number of tokens in the response
     Stop = null,       // Sequence of tokens that will stop generation
     PresencePenalty = 0.0,              // Penalizes new tokens based on their existing presence in the context
     FrequencyPenalty = 0.0              // Penalizes new tokens based on their frequency in the context
 };

 var openai = new ChatGpt(openAiKey, options);
 var fixedSentence = await openai.Ask($"{instruction}: {data}");
 return fixedSentence;

However cant get how to speficy system message separately. For example I want to ask to rephrase user message and keep it in the original language (not-English).

program stopped without any prompt

111

` private static async Task ChatgptNetTestAsync()
{
var chatGpt = new ChatGpt(new ChatGptConfig
{
UseCache = true
});
await chatGpt.WaitForReady();
var chatGptClient = await chatGpt.CreateClient(new ChatGptClientConfig
{
SessionToken = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..",
AccountType = AccountType.Free
});

    //init unique conversation id
    //var conversationId = Guid.NewGuid().ToString("N");
    var conversationId = "a-unique-string-id";

    while (true)
    {
        Serilog.Log.Information("pls ask a question");
        var question = Console.ReadLine();
        var response = await chatGptClient.Ask(question, conversationId);
        Serilog.Log.Information("answer:{0}", response);            
    }
}

`

Non JSON data in the response stream

An exception is thrown when I call ChatGptUnofficial.Ask.
The Message:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ChatGPT.Net.DTO.ChatGPTUnofficial.ChatGptUnofficialMessageResponse' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.

The stack trace:

在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract)
在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)
在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
在 Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
在 Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
在 Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
在 ChatGPT.Net.ChatGptUnofficial.<SendMessage>d__33.MoveNext() 在 E:\Mirai-console\livebot\source\ChatGPT.Net\ChatGPTUnofficial.cs 中: 第 271 行
在 ChatGPT.Net.ChatGptUnofficial.<SendMessage>d__33.MoveNext() 在 E:\Mirai-console\livebot\source\ChatGPT.Net\ChatGPTUnofficial.cs 中: 第 267 行
在 ChatGPT.Net.ChatGptUnofficial.<Ask>d__30.MoveNext() 在 E:\Mirai-console\livebot\source\ChatGPT.Net\ChatGPTUnofficial.cs 中: 第 147 行

I debugged and get the following response stream in ChatGptUnofficialOptions.SendMessage:

data: {"message": {"id": "ee672280-8484-4f3b-a22e-6e8aa220f872", "author": {"role": "system", "name": null, "metadata": {}}, "create_time": 1680774850.515529, "update_time": null, "content": {"content_type": "text", "parts": [""]}, "end_turn": true, "weight": 1.0, "metadata": {}, "recipient": "all"}, "conversation_id": "ed88bf93-65ef-4967-b92a-2aa018be10e5", "error": null}
data: {"message": {"id": "6ee04278-ae06-4dc6-9a23-b4ac5d3558f9", "author": {"role": "user", "name": null, "metadata": {}}, "create_time": 1680774850.522996, "update_time": null, "content": {"content_type": "text", "parts": ["Hi, chatgpt."]}, "end_turn": null, "weight": 1.0, "metadata": {"timestamp_": "absolute", "message_type": null}, "recipient": "all"}, "conversation_id": "ed88bf93-65ef-4967-b92a-2aa018be10e5", "error": null}
data: {"message": {"id": "65cc4ca3-d84a-4e89-81b4-cdce9e13de5f", "author": {"role": "assistant", "name": null, "metadata": {}}, "create_time": 1680774850.882099, "update_time": null, "content": {"content_type": "text", "parts": [""]}, "end_turn": null, "weight": 1.0, "metadata": {"message_type": "next", "model_slug": "text-davinci-002-render-sha"}, "recipient": "all"}, "conversation_id": "ed88bf93-65ef-4967-b92a-2aa018be10e5", "error": null}
data: {"message": {"id": "65cc4ca3-d84a-4e89-81b4-cdce9e13de5f", "author": {"role": "assistant", "name": null, "metadata": {}}, "create_time": 1680774850.882099, "update_time": null, "content": {"content_type": "text", "parts": ["Hello"]}, "end_turn": null, "weight": 1.0, "metadata": {"message_type": "next", "model_slug": "text-davinci-002-render-sha"}, "recipient": "all"}, "conversation_id": "ed88bf93-65ef-4967-b92a-2aa018be10e5", "error": null}
data: {"message": {"id": "65cc4ca3-d84a-4e89-81b4-cdce9e13de5f", "author": {"role": "assistant", "name": null, "metadata": {}}, "create_time": 1680774850.882099, "update_time": null, "content": {"content_type": "text", "parts": ["Hello!"]}, "end_turn": null, "weight": 1.0, "metadata": {"message_type": "next", "model_slug": "text-davinci-002-render-sha"}, "recipient": "all"}, "conversation_id": "ed88bf93-65ef-4967-b92a-2aa018be10e5", "error": null}
......
data: {"message": {"id": "65cc4ca3-d84a-4e89-81b4-cdce9e13de5f", "author": {"role": "assistant", "name": null, "metadata": {}}, "create_time": 1680774850.882099, "update_time": null, "content": {"content_type": "text", "parts": ["Hello! How can I assist you today?"]}, "end_turn": true, "weight": 1.0, "metadata": {"message_type": "next", "model_slug": "text-davinci-002-render-sha", "finish_details": {"type": "stop", "stop": "<|im_end|>"}}, "recipient": "all"}, "conversation_id": "ed88bf93-65ef-4967-b92a-2aa018be10e5", "error": null}
data: [DONE]

There is a [Done] tag at the end which cannot be deserialized to JSON.

support partial response

await the ask method for the whole message,it will takes too long,can it support resonse partial response content

questions with same conversationId are split

I've got a problem that AI always forgets the previous questions and answers, when I ask a new question.
I have set a conversationId when asking, and I'm not using the BrowserMode.
From the chat history in the browser, I find that the questions are split into multiple conversations. Only one question in each conversation.

Here‘s an example.

string conversationId = "group-78015"; //a string to distinguish users

var response1 = await chatGptClient.Ask("Explain quantum computing in simple terms", conversationId);
Console.WriteLine("response1: " + response1);

var response2 = await chatGptClient.Ask("Where can it be applied?", conversationId);
Console.WriteLine("response2: " + response2);

Console output

response1: Quantum computing is a type of computing ......

response2: Can you please clarify what you are asking about?

Chat history
image
image

Unofficial unusable

at ChatGPTUnofficial.cs line 258

  var client = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri($"{Config.BaseUrl}/backend-api/conversation"),
            Headers =
            {
                {"Authorization", $"Bearer {AccessToken}" }
            },
            Content = new StringContent(JsonConvert.SerializeObject(requestData))
            {
                Headers =
                {
                    ContentType = new MediaTypeHeaderValue("application/json")
                }
            }
        };
        var response = await client.SendAsync(request);

        response.EnsureSuccessStatusCode();
        var stream = await response.Content.ReadAsStreamAsync();
        var str = await new StreamReader(stream).ReadToEndAsync();  // always an empty string

Response streaming does not work

Response streaming does not seem to work. It still waits for the entire response to be generated before showing the answer in the console.

Converting to .NET Framework only

How difficult or effortless is to convert the project to be compatible to .NET Framework (4.7.2-4.8)?
I am trying to make a plug-in for a big project that is incompatible with .NET Standard/Core/6.0/7.0 and will never be... So my only way is to downgrade ChatGPT.Net to .NET Framework. What does it involve specifically?

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.