openai: System.Text.Json.JsonException The JSON value could not be converted to System.String. Path: $.error.code | LineNumber: 0 | BytePositionInLine: 20.

Describe the bug I use the api as normal, but it shows System.Text.Json.JsonException The JSON value could not be converted to System.String. Path: $.error.code | LineNumber: 0 | BytePositionInLine: 20.

Your code piece

ChatCompletionCreateRequest chatCompletionCreateRequest = new ChatCompletionCreateRequest {
    Messages = new List<ChatMessage>(),
    Model = Model,
};

ChatCompletionCreateResponse chatCompletionCreateResponse;
try {
    chatCompletionCreateResponse = await openAiService.ChatCompletion.CreateCompletion(chatCompletionCreateRequest);
} catch (Exception ex) {
    Console.WriteLine($"{ex.GetType().FullName}<br>{ex.Message}");
    throw;
}

Result System.Text.Json.JsonException The JSON value could not be converted to System.String. Path: $.error.code | LineNumber: 0 | BytePositionInLine: 20. InvalidOperationException: Cannot get the value of a token type ‘Number’ as a string. at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex) at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ContinueDeserialize[TValue](ReadBufferState& bufferState, JsonReaderState& jsonReaderState, ReadStack& readStack, JsonTypeInfo jsonTypeInfo) at System.Text.Json.JsonSerializer.ReadFromStreamAsync[TValue](Stream utf8Json, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken) at System.Net.Http.Json.HttpContentJsonExtensions.ReadFromJsonAsyncCore[T](HttpContent content, Encoding sourceEncoding, JsonSerializerOptions options, CancellationToken cancellationToken) at OpenAI.Extensions.HttpClientExtensions.PostAndReadAsAsync[TResponse](HttpClient client, String uri, Object requestModel, CancellationToken cancellationToken) at OpenAI.Managers.OpenAIService.CreateCompletion(ChatCompletionCreateRequest chatCompletionCreateRequest, String modelId, CancellationToken cancellationToken) at 【MyCode】

Expected behavior API returns ChatGPT’s reply

Screenshots image

Desktop (please complete the following information):

  • OS: Windows 11
  • Language C#

About this issue

  • Original URL
  • State: closed
  • Created 8 months ago
  • Reactions: 1
  • Comments: 32 (12 by maintainers)

Most upvoted comments

For analysis I enhanced in HttpClientExtensions the method with a try-catch to get the JsonException and include HTTP status code:

    try
      {
          return await response.Content.ReadFromJsonAsync<TResponse>(cancellationToken: cancellationToken) ?? throw new InvalidOperationException();
      }
  	catch (System.Text.Json.JsonException ex)
      {
          string content = "<<unknown>>";
          try { content = response.Content.ReadAsStringAsync().Result; } catch { }
  		throw new InvalidOperationException($"{ex.Message}, Http {response.StatusCode} {response.ReasonPhrase}: {content}", ex);
  	}

I most cases it has been a ‘bad gateway’ http error status and reason, which was the cause of the JsonException.

I have added this catch JsonException to find the cause. In the cases I had, it was always HTTP status code >299 (like 502 bad gateway). To me it makes sense that in http error cases there’s no valid Json.

@roldengarm OpenAI is supposed to return an error message and code when encountering issues. These fields are available through the SDK response. However, in cases where a proper response cannot be returned due to an outage or internal error, the SDK is unable to provide more details. I am planning to improve this behavior in the future, but for now, my suggestion is to return an unexpected error message 😕