Queries LibraryTranslate multiple sentences using ChatGPT
Translate multiple sentences using ChatGPT
This query fetches the content from multiple posts, and translates those strings to any language using ChatGPT.
To connect to the OpenAI API, you must provide variable $openAIAPIKey
with the API key.
You can override the $model
variable ("gpt-4o-mini"
by default) with the OpenAI model you desire to use.
query GetPostContent($limit: Int! = 5) {
posts(pagination: {limit: $limit}, sort: {by: ID, order: ASC}) {
content
@export(
as: "contentItems",
type: LIST
)
}
}
query TranslateContentWithChatGPT(
$fromLang: String!
$toLang: String!
$openAIAPIKey: String!
$systemMessage: String! = "You are a language translator"
$promptTemplate: String! = """
I'm working on internationalizing my application.
I've created a JSON with sentences in {$fromLang}. Please translate the sentences to {$toLang}. If a sentence contains HTML, do not translate inside the HTML tags.
This is the JSON:
{$encodedContentItems}
"""
$model: String! = "gpt-4o-mini"
)
@depends(on: "GetPostContent")
{
contentItems: _echo(value: $contentItems)
encodedContentItems: _arrayEncodeAsJSONString(array: $contentItems)
prompt: _strReplaceMultiple(
search: ["{$fromLang}", "{$toLang}", "{$encodedContentItems}"],
replaceWith: [$fromLang, $toLang, $__encodedContentItems],
in: $promptTemplate
)
openAIResponse: _sendJSONObjectItemHTTPRequest(input: {
url: "https://api.openai.com/v1/chat/completions",
method: POST,
options: {
auth: {
password: $openAIAPIKey
},
json: {
model: $model,
messages: [
{
role: "system",
content: $systemMessage
},
{
role: "user",
content: $__prompt
},
],
response_format: {
type: "json_schema",
json_schema: {
name: "translation_response",
strict: true,
schema: {
type: "object",
properties: {
translations: {
type: "array",
items: {
type: "string"
}
}
},
required: ["translations"],
additionalProperties: false
}
}
}
}
}
})
@underJSONObjectProperty(by: { key: "choices" })
@underArrayItem(index: 0)
@underJSONObjectProperty(by: { path: "message.content" })
@export(as: "jsonEncodedTranslatedContent")
}
query ExtractTranslatedContent
@depends(on: "TranslateContentWithChatGPT")
{
jsonEncodedTranslatedContent: _echo(value: $jsonEncodedTranslatedContent)
@remove
decodedTranslatedContent: _strDecodeJSONObject(string: $jsonEncodedTranslatedContent)
@remove
translatedContent: _objectProperty(
object: $__decodedTranslatedContent,
by: { key: "translations" }
)
}