debugging Json中的转义字符

4xy9mtcn  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(118)

OpenAI代码转换器的转义序列不会通过大代码进行调试。像加法减法这样的小代码转换和所有工作。
我尝试使用C#创建OpenAI代码翻译器,并将Python代码(用于将英里转换为公里)分别转换为C#和Java代码。

粘贴我的OpenAI自定义代码(将2个数字的和从Python转换为c#)

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text.Json;
namespace OpenAIProgram
{
    public class CodeTranslator
    {
        public static async Task<string> TranslateCodeAsync(string apiKey, string apiUrl, string jsonBody)
        {
            string result = string.Empty;
            try
            {
                if (string.IsNullOrEmpty(apiUrl) || string.IsNullOrEmpty(jsonBody))
                    throw new Exception("Missing parameter for execution");
                using var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);
                request.Headers.Add("Connection", "keep-alive");
                request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
                //Console.WriteLine("Payload:");
                //Console.WriteLine(jsonBody);
                var response = await httpClient.SendAsync(request);
                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadAsStringAsync();
                }
                else
                {
                    throw new Exception("Response code was " + response.StatusCode);
                }
            }
            catch (Exception e)
            {
                result = e.Message;
                result += "\n" + e.GetType() + ": " + e.Message;
                if (e.StackTrace != null)
                {
                    foreach (var trace in e.StackTrace.Split("\n"))
                    {
                        result += "\n\t" + trace.Trim();
                    }
                }
            }
            return result;
        }
        public static async Task Main()
        {
            string apiKey = "";
            string apiUrl = "https://api.openai.com/v1/chat/completions";
            string jsonBody = @"
{
    ""model"": ""gpt-3.5-turbo"",
    ""messages"": [
        {
                ""role"": ""system"",
            ""content"": ""You are a genius level coder, with knowledge of all programming and scripting languages and their associated syntax.""
        },
{
                ""role"": ""system"",
            ""content"": ""Translate the code from [Python] to [c#]""`your text`
        },
        {
                ""role"": ""user"",
            ""content"": ""num1 = 1.5 num2 = 6.3 sum = num1 + num2 print(The sum of {num1} and {num2} is { sum})""
        }
        
    ],
    ""temperature"": 1.0,
      ""max_tokens"": 150
}";
    string translatedCode = await TranslateCodeAsync(apiKey, apiUrl, jsonBody);
            //string stringjson = JsonConvert.SerializeObject(jsonBody);
            //Console.WriteLine("Translated Code:");
            Console.WriteLine(translatedCode);
        }
    }
}

当我们输入具有不同逐字字面量的代码时,问题就会发生,并且必须根据我们的需要将它们从源代码转换为目标代码(输出)。
主要关注的是一个问题,在C#和Java中,我们在代码(输入)中使用'#'符号,但是一旦它被翻译成Python,情况就完全改变了,因为在Python中,符号'#'用于注解代码。
问题:
在上面给出的代码中,用户提供了2个数字之和的代码,如果我必须尝试将公里转换为英里或任何其他具有其他文字的代码,如@!,$,%,&.*./,?它会给我BadRequest的响应。
您可以尝试相同的代码,因为它工作得很好。在调试时,输入的JsonBody似乎没有被正确地带入内部。对于文字“,我们可以使用““来转义序列。

rt4zxlrg

rt4zxlrg1#

似乎真实的的问题是如何转义 JSON 字符串,而不是C#转义序列。实际的解决方案是首先不要手工创建JSON。像System.Text.JSON这样的JSON序列化器将使用比手工创建字符串少得多的内存将任何对象序列化为JSON。
给定匹配请求和响应对象的类

record AiRole(string Role,string Content);

record AiRequest(string Model,AiRole[] Messages,float Temperature,int Max_tokens);

record CompletionResponse(.... whatever...);

我们可以使用特定的key创建并重用一个HttpClient示例:

readonly HttpClient _client;

public MyClass(string key)
{
    _client=new HttpClient(){
        BaseAddress=new Uri("https://api.openai.com/v1/chat/completions")
    };
    _client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
}

调用被简化为以下几行,使用PostAsJsonAsyncReadFromJsonAsync来处理序列化样板文件:

public async CompletionResponse? GetCompletion(AiRoles[] requests)
{
    try
    {
        var request=new AiRequest("gpt-3.5-turbo",requests,1.5,150);

        var response=await _client.PostAsJsonAsync(request);
        if (response.IsSuccessStatusCode)
        {
            var responseDTO = await response.Content.ReadFromJsonAsync<CompletionResponse>();
            return responseDTO;
        }
        else
        {
            var body=await response.Content.ReadAsStringAsync();
            Console.WriteLine($"{response.StatusCode}:{response.ReasonPhrase}");
            Console.WriteLine(body);
        }
    }
    catch(Exception exc)
    {
        Console.WriteLine(exc);
    }
    return null;
}

.NET Core使用System.Text.JSON将对象序列化为JSON并填充默认的标头值。
如果发生错误,我们可以返回响应DTO或方法的错误,而不是写入控制台:

public async (CompletionResponse? Result,string? Error) GetCompletion(AiRoles[] requests)
{
    try
    {
        ...
        if (response.IsSuccessStatusCode)
        {
            var responseDTO = await response.Content.ReadFromJsonAsync<CompletionResponse>();
            return (responseDTO,null);
        }
        else
        {
            var body=await response.Content.ReadAsStringAsync();
            return (null,$"{response.StatusCode}:{response.ReasonPhrase}: {body}");
        }
    }
    catch(Exception exc)
    {
        return (null,exc.ToString());
    }
}

Exception.ToString()创建一个字符串,其中包含错误消息、内部异常、堆栈跟踪和抛出的位置

相关问题