-1

The escape sequence for the OpenAI code translator is not debugging through big codes. small codes like addition, subtraction. conversion and all are working.

I tried to create OpenAI code translator using C#, and got the result in converting python code( for converting miles to kms) - to c# and Java Codes respectively.

Pasting my OpenAI custom code (Translating sum of 2 numbers from Python to 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);
        }
    }
}

The issue happens when we input codes having different verbatim literals , and they must be translated from their origin code to the destination code(output) as we need.

The main concern is in an issue , where as in c# and Java we use '#' symbol inside the code(input), but once it gets translated to Python the scenario totally changes as in Python the symbol '#' is using for commenting the code.

Issue:

In the code given above, the user provides the code of sum of 2 numbers and if i have to try to convert kilometers to miles or anyother code which have other literals like @,!,$,%,&.*./,? it gives me the response of BadRequest.

You can try on the same code, as it was working perfectly. The inputting JsonBody seems to be not taken properly inside while debugging. For the literal " we can use " " to escape the sequence.

Jes
  • 1
  • 2
  • What's the actual question? Post *only* the relevant code and the actual error. It seems you tried to use a URL or JSON string with invalid characters. This has nothing to do with C# escape sequences and everything to do with creating proper URLs and JSON strings. None of this code is needed to begin with. Almost all of it can be replaced with `HttpClient.PostAsJsonAsync` and a class that matches the expected JSON format. `PostAsJsonAsync` uses System.Text.Json to serialize the DTO into JSON – Panagiotis Kanavos Jun 28 '23 at 13:16
  • 1
    ""content"": ""Translate the code from [Python] to [c#]""`your text` is not a valid json string. What do you expect? – Serge Jun 28 '23 at 13:23
  • The method i Have used is giving me proper output, but when i use different codes, it throws badrequest error – Jes Jun 29 '23 at 09:04
  • ""content"": ""Translate the code from [Python] to [c#]""your text , sorry for the mistake. In this --"your text -- , this part is not there. It wasn't there in the actual code – Jes Jun 29 '23 at 09:06

1 Answers1

0

It seems the real question is how to escape JSON strings, not C# escape sequences. The actual solution is to not create JSON by hand in the first place. JSON serializers like System.Text.Json will serialize any object to JSON using far less memory than creating the string by hand.

Given classes that match the request and response objects

record AiRole(string Role,string Content);

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

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

We can create and reuse an HttpClient instance with a specific key:

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}");
}

The call is reduced to these lines, using PostAsJsonAsync and ReadFromJsonAsync to handle the serialization boilerplate:

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 uses System.Text.Json to serialize the object to JSON and fills the default header values.

Instead of writing to the console in case of error, we can return either the response DTO or the error from the method :

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() creates a string that contains the error message,inner exceptions, stack trace and the location that threw

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236