Translate language (Json / Web Request)

this is what I have modified so far but still can’t get the result

import sys
import clr
import System
from System.Text import *
from System.Net import *
clr.AddReference("System.Net.Http")
from System.Net.Http import *
import json

def translate_OpenAI(text="maison", source="french", target="english"):
	input = "Hello translate this {0} word '{2}' in {1}".format(source, target, text)
	client = HttpClient()
	client.DefaultRequestHeaders.Add("Authorization", r"Bearer key")
	content = {\
    "model": "gpt-3.5-turbo", \
    "messages": [{"role": "user", "content": input}], \
	}
	response = client.PostAsync("https://api.openai.com/v1/chat/completions", StringContent(json.dumps(content)))
	result = response.Result.Content.ReadAsStringAsync().Result
	return result

OUT = translate_OpenAI(IN[0])

hi, since the key is hidden under its initial python (IronPython3), I think you have to put your hand in your pocket if you want to use
but wait for confirmation from Mr. Poupin, I may be talking nonsense

Sincerely
christian.stan

@newshunhk

replace

StringContent(json.dumps(content))

by

StringContent(json.dumps(content), Encoding.UTF8, "application/json")

example with Newtonsoft.Json

import sys
import clr
import System
from System.Text import *
from System.Net import *
clr.AddReference("System.Net.Http")
from System.Net.Http import *

clr.AddReference('Newtonsoft.Json')
import Newtonsoft.Json;

clr.AddReference("System.Core")
clr.ImportExtensions(System.Linq)


apikey = "sk-bC.............." # YOUR_API_KEY

def translate_OpenAI(text="maison", source="french", target="english"):
    input = "Hello translate this {0} word '{2}' in {1}.Write only the answer (word or expression)".format(source, target, text)
    result = None
    with HttpClient() as client:
        client.DefaultRequestHeaders.Add("Authorization", "Bearer {}".format(apikey))
        content = {\
        "model": "gpt-3.5-turbo", \
        'max_tokens': 100 ,\
        "messages": [{"role": "user", "content": input}], \
        }
        jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(content);
        httpContent = StringContent(jsonRequest, Encoding.UTF8, "application/json");
        response = client.PostAsync("https://api.openai.com/v1/chat/completions", httpContent)
        jsonResponse = response.Result.Content.ReadAsStringAsync().Result
        #print(jsonResponse)
        data = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResponse);
        result = data["choices"][0]["message"]["content"].ToString()
    return result

OUT = translate_OpenAI(IN[0])

1 Like

@c.poupin it works perpectly! thanks a lot :slight_smile:
now let me try to embed the function calling