pawanosman / chatgpt.net Goto Github PK
View Code? Open in Web Editor NEWC# library for ChatGPT using official OpenAI API
Home Page: https://www.nuget.org/packages/ChatGPT.Net
License: MIT License
C# library for ChatGPT using official OpenAI API
Home Page: https://www.nuget.org/packages/ChatGPT.Net
License: MIT License
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);
}
is there ssr function in the sdk?
Trying to join the server all day today:
Cannot connect to server 'https://gpt.pawan.krd/'
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
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?");
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.'
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)
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
How to get SessionToken?
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 ?
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.
Is there any way to get such a long reply?
We had an issue maintaining context correctly via the NuGet package. After some investigation it seems the chat gpt response side of the conversion was not being passed back in subsequent calles to the api.
You can see an example of how this should work here:
https://cobusgreyling.medium.com/when-using-the-chatgpt-api-users-will-have-to-manage-the-context-ba5869238913
I have submitted a pull request that seems to fix the issue.
#36
Thanks for the hard work!
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.ObjectDefaultConverter
1.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.JsonConverter
1.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](ReadOnlySpan
1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable1 actualByteCount) at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan
1 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
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.
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.
During the day I get the answer: We're currently processing too many requests. Please try again later.
But in the ChatGPT interface, it successfully answers questions.
In the paid GPT4 version there is a file upload available to upload images. Is this possible with your impelementation?
CacheException caught: Cannot connect to server 'https://gpt.pawan.krd/'
Retrying in 10 second...
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).
` 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);
}
}
`
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.
Hi there, I cant seem to get the api to get past await chatGpt.WaitForReady();
it just hangs forever, any ideas?
Thanks
James
how designed the server with cookie
await the ask method for the whole message,it will takes too long,can it support resonse partial response content
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?
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
Displays "Disconnected from the Bypass Node! Reconnecting .. "can never re-establish the connection in the program, but restarting the program can.
I want to use api key instead of __Secure-next-auth.session-token.
Because __Secure-next-auth.session-token will expire in 7 days.
How can I use api key .
It'd be great to have the possibility to fine-tune the models. Do you have a plan to support it in this package?
It's still relevant. AI forgets previous conversation (#6)
Cannot specify whether the pro chat model uses default or Legacy
Response streaming does not seem to work. It still waits for the entire response to be generated before showing the answer in the console.
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.