tencent cloud

Hy API Guide

Download
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-08-28 15:02:06
Diterjemahkan oleh AI

Overview

Tencent Hy is a large language model developed by Tencent. It possesses strong capabilities in Chinese content creation, logical reasoning in complex contexts, and reliable task execution.

Prerequisites

You have registered a Tencent Cloud account and activated the TokenHub service.
You have obtained the API Key in the TokenHub console.

Hy4 preview Call Example

hy4-preview is compatible with the OpenAI Chat Completions API, OpenAI Responses, and Anthropic Messages API protocols. The general interface specifications are consistent with all language models. For more information, see Language Model Invocation Overview and API Usage Instructions.
The following is an example of calling the OpenAI Chat Completions API.
model (API Parameter)
Capability Description
Context Window
Max Input
Max Output
hy4-preview
A new-generation productivity model with comprehensively upgraded Agent and complex task execution capabilities.
1M
960k
64k
hy3
Hy3 is refined based on real-world business scenarios, balancing effectiveness and cost-effectiveness, and enhances capabilities in Coding, long-text processing, reasoning, and Agent tasks.
256k
192k
128k
Note:
All examples uniformly use Authorization: Bearer YOUR_API_KEY for authentication. Replace YOUR_API_KEY with the API Key you created in the TokenHub console.
For Python/Node.js, use the official OpenAI SDK directly. For Java/Go, call the OpenAI-compatible API using a standard HTTP client.

Basic Conversation

This example demonstrates the basic request and response structure for the simplest single-turn conversation.
cURL
Python
Java
Node.js
Go

curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{"role": "user", "content": "Hello, please briefly introduce yourself."}
],
"stream": false,
"temperature": 0.9
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

response = client.chat.completions.create(
model="hy4-preview",
messages=[
{"role": "user", "content": "Hello, please briefly introduce yourself."}
],
temperature=0.9,
)
print(response.choices[0].message.content)
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class BasicChat {
public static void main(String[] args) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("model", "hy4-preview");
body.put("messages", List.of(
Map.of("role", "user", "content", "Hello, please briefly introduce yourself.")
));
body.put("temperature", 0.9);

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body),
MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const response = await client.chat.completions.create({
model: 'hy4-preview',
messages: [
{ role: 'user', content: 'Hello, please briefly introduce yourself.' },
],
temperature: 0.9,
});
console.log(response.choices[0].message.content);
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
body, _ := json.Marshal(map[string]interface{}{
"model": "hy4-preview",
"messages": []map[string]string{
{"role": "user", "content": "Hello, please briefly introduce yourself."}
},
"temperature": 0.9,
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Response Example:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy4-preview",
"created": 1775146513,
"choices": [
{
"index": 0,
"message": {

"role": "assistant",
"content": "I am Hunyuan, a large model developed by Tencent. I can perform information processing and logical responses such as answering questions, solving problems, learning new knowledge, and creating content. I can also engage in casual conversation and support multiple communication methods including text, images, and files.",
"reasoning_content": "Okay, the user asked me to briefly introduce myself. First, I need to review my own configuration to ensure the response meets the identity requirements. The user may want to know basic information about me, such as my name, purpose, and developer.\\n\\nMy identity is \\"Hunyuan\\", a foundational model developed by Tencent. According to my core behavioral constraints, when a user asks about my identity, I need to clearly respond with \\"I am Hunyuan\\". At the same time, since this is a normal conversational question, I do not need to emphasize my identity in a special way. I can simply reflect it naturally in the introduction.\\n\\nThe user's question is about self-introduction, so the response should cover my basic features, such as information processing, logical responses, and problem solving. I should also mention that I was developed by Tencent, but avoid excessive technical details and keep it concise.\\n\\nI need to be careful not to go beyond the scope, for example, by mentioning other models or hypothetical features. I should keep the response friendly and factually accurate while conforming to the identity configuration. Now I will organize the language to ensure it is clear and easy to understand, avoiding complex terminology, so that the user can quickly understand my purpose and background."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 28,
"completion_tokens": 221,
"total_tokens": 249,
"prompt_tokens_details": {
"cached_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 175
}
}
}


Streaming Request

Set stream: true to enable streaming output. Responses are returned incrementally by token in the SSE (Server-Sent Events) format. To obtain the complete usage statistics in the final chunk, add stream_options: { "include_usage": true }.
cURL
Python
Java
Node.js
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{"role": "user", "content": "Hello"}
],
"stream": true,
"stream_options": {"include_usage": true}
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

stream = client.chat.completions.create(
model="hy4-preview",
messages=[{"role": "user", "content": "Hello"}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print("\\nusage:", chunk.usage)
import okhttp3.*;
import okhttp3.sse.*;
import com.google.gson.Gson;
import java.util.*;

public class StreamingChat {
public static void main(String[] args) {
Map<String, Object> body = new HashMap<>();
body.put("model", "hy4-preview");
body.put("messages", List.of(Map.of("role", "user", "content", "Hello")));
body.put("stream", true);
body.put("stream_options", Map.of("include_usage", true));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body),
MediaType.parse("application/json")))
.build();

EventSources.createFactory(new OkHttpClient()).newEventSource(request,
new EventSourceListener() {
@Override public void onEvent(EventSource es, String id, String type, String data) {
if (!"[DONE]".equals(data)) System.out.println(data);
}
});
}
}
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const stream = await client.chat.completions.create({
model: 'hy4-preview',
messages: [{ role: 'user', content: 'Hello' }],
stream: true,
stream_options: { include_usage: true },
});

for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
if (chunk.usage) console.log('\\nusage:', chunk.usage);
}
package main

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
)

func main() {
body, _ := json.Marshal(map[string]interface{}{
"model": "hy4-preview",
"messages": []map[string]string{
{"role": "user", "content": "Hello"},
},
"stream": true,
"stream_options": map[string]bool{"include_usage": true},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data: ") && line != "data: [DONE]" {
fmt.Println(strings.TrimPrefix(line, "data: "))
}
}
}
Response Example (SSE Fragment):
data: {"id": "REPLACED_ID", "object": "chat.completion.chunk", "created": 1779958293, "model": "hy4-preview", "choices": [{"index": 0, "delta": {"role": "assistant"}}]}

data: {"id": "REPLACED_ID", "object": "chat.completion.chunk", "created": 1779958293, "model": "hy4-preview", "choices": [{"index": 0, "delta": {"content": "Hello"}}]}

data: {"id": "REPLACED_ID", "object": "chat.completion.chunk", "created": 1779958293, "model": "hy4-preview", "choices": [{"index": 0, "delta": {"content": "Can I help you?"}}]}

data: {"id": "REPLACED_ID", "object": "chat.completion.chunk", "created": 1779958293, "model": "hy4-preview", "choices": [{"index": 0, "delta": {"content": " 😊"}, "finish_reason": "stop"}]}

data: {"id": "REPLACED_ID", "object": "chat.completion.chunk", "created": 1779958293, "model": "hy4-preview", "choices": [], "usage": {"prompt_tokens": 16, "completion_tokens": 11, "total_tokens": 27, "prompt_tokens_details": {"cached_tokens": 0}, "completion_tokens_details": {"reasoning_tokens": 0}}}

data: [DONE]

Deep Reasoning

Enable deep thinking. For detailed instructions, see Deep Thinking.
cURL
Python
Node.js
Java
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{"role": "user", "content": "Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?"}
],
"thinking": {"type": "enabled"},
"stream": false
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

response = client.chat.completions.create(
model="hy4-preview",
messages=[
{"role": "user", "content": "Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?"}
],
extra_body={"thinking": {"type": "enabled"}},
)

# The reasoning_content field is not directly declared by the OpenAI SDK, so you must access it using getattr.
msg = response.choices[0].message
if hasattr(msg, "reasoning_content"):
print("Thinking process:", getattr(msg, "reasoning_content"))
print("Final answer:", msg.content)
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

// Node.js SDK: Expand the thinking field directly to the top level.
const response = await client.chat.completions.create({
model: 'hy4-preview',
messages: [
{ role: 'user', content: 'Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?' }
],
thinking: { type: 'enabled' },
});

const msg = response.choices[0].message;
if (msg.reasoning_content) console.log('Thinking process:', msg.reasoning_content);
console.log('Final answer:', msg.content);
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class ThinkingChat {
public static void main(String[] args) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("model", "hy4-preview");
body.put("messages", List.of(
Map.of("role", "user", "content", "Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?")
));
body.put("thinking", Map.of("type", "enabled"));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body), MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
// In the response body, the message.reasoning_content field represents the thinking process, and the message.content field represents the final answer.
System.out.println(response.body().string());
}
}
}
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
body, _ := json.Marshal(map[string]interface{}{
"model": "hy4-preview",
"messages": []map[string]string{
{"role": "user", "content": "Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?"}
},
"thinking": map[string]string{"type": "enabled"},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
// In the response body, the message.reasoning_content field represents the thinking process, and the message.content field represents the final answer.
fmt.Println(string(data))
}
Response Example:
After thinking is enabled, the response includes a reasoning_content thinking process field.
{
"id": "REPLACED_ID",
"object": "chat.completion",
"created": 1775146546,
"model": "hy4-preview",
"choices": [
{
"index": 0,
"message": {

"role": "assistant",
"content": "Xiaoming finally has **6** apples left.\\n\\nCalculation process:\\n1. Initially, he had 5 apples;\\n2. After giving 2 to Xiaohong, the remaining number was: 5 - 2 = 3;\\n3. After buying 3 more, the total became: 3 + 3 = 6."
"reasoning_content": "The user asked: Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?\\nLet's calculate step by step:\\nInitially: 5 apples\\nAfter giving 2 to Xiaohong: 5 - 2 = 3 apples\\nAfter buying 3 more: 3 + 3 = 6 apples\\nFinally, 6 apples are left.\\n\\nCheck for any language traps. \\"Gave 2 to Xiaohong\\" means subtraction, and \\"bought 3 more\\" means addition.\\n5 - 2 + 3 = 6.\\nThe answer should be 6."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 31,
"completion_tokens": 178,
"total_tokens": 209,
"prompt_tokens_details": {
"cached_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 106
}
}
}
Reasoning Depth Configuration
hy4-preview and hy3 default to high. For details, see Deep Thinking.
Attention:
In the tool call scenario, the Hy3 official version model has adaptive thinking capability, meaning it can autonomously determine the reasoning depth based on task complexity. When a request carries tools, for compatibility reasons, if reasoning_effort is set to low in this scenario, the API automatically maps low to high.
cURL
Python
Node.js
Java
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{"role": "user", "content": "Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?"}
],
"stream": false,
"temperature": 0.9,
"reasoning_effort": "high"
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

response = client.chat.completions.create(
model="hy4-preview",
messages=[
{"role": "user", "content": "Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?"}
],
temperature=0.9,
extra_body={"reasoning_effort": "high"},
)

msg = response.choices[0].message
if hasattr(msg, "reasoning_content"):
print("Thinking process:", getattr(msg, "reasoning_content"))
print("Final answer:", msg.content)
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const response = await client.chat.completions.create({
model: 'hy4-preview',
messages: [
{ role: 'user', content: 'Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?' }
],
temperature: 0.9,
reasoning_effort: 'high',
});

const msg = response.choices[0].message;
if (msg.reasoning_content) console.log('Thinking process:', msg.reasoning_content);
console.log('Final answer:', msg.content);
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class ReasoningEffortChat {
public static void main(String[] args) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("model", "hy4-preview");
body.put("messages", List.of(
Map.of("role", "user", "content", "Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?")
));
body.put("temperature", 0.9);
body.put("reasoning_effort", "high");

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body), MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
body, _ := json.Marshal(map[string]interface{}{
"model": "hy4-preview",
"messages": []map[string]string{
{"role": "user", "content": "Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?"}
},
"temperature": 0.9,
"reasoning_effort": "high",
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Response Example:
After thinking is enabled, the response includes a reasoning_content thinking process field.
{
"id": "c95dc87ecce440678c3bb08f5868fee6",
"object": "chat.completion",
"created": 1775146546,
"model": "hy4-preview",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Xiaoming originally had 5 apples. After giving 2 to Xiaohong, he had: \\n5 - 2 = 3 (apples) \\nHe then bought 3 more, and now has: \\n3 + 3 = 6 (apples) \\n\\nTherefore, he finally has **6** apples left."
"reasoning_content": "We were asked: \\"Xiaoming had 5 apples, gave 2 to Xiaohong, bought 3 more, and finally, how many are left?\\" We need to calculate step by step.\\n\\nInitial: 5 apples.\\nGave 2 to Xiaohong: 5 - 2 = 3 apples.\\nBought 3 more: 3 + 3 = 6 apples.\\nTherefore, 6 apples are left in the end.\\n\\nAnswer: 6."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 3,
"completion_tokens": 136,
"total_tokens": 167
}
}

Interleaved Reasoning (Deep Reasoning + Tool Calling)

This example is provided solely to illustrate the complete workflow and field return logic. In actual use, adjust the specific values according to your business deployment environment and business fields. (This case is for understanding the workflow only and does not represent the model's capability boundaries.) For detailed information, see Interleaved Thinking.
Round 1 - User Question:
Request:
cURL
Python
Node.js
Java
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{ "role": "system", "content": "You are an Agent and must reason step by step and call tools to complete tasks." },
{ "role": "user", "content": "What is the weather like in Shenzhen today?" }
],
"stream": false,
"tool_choice": "auto",
"reasoning_effort": "high",
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Obtain weather information for a location. Input the location."
"parameters": {
"type": "object",
"properties": { "location": { "type": "string" } },
"required": ["location"]
}
}
}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Obtain weather information for a location. Input the location."
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
},
}]

messages = [
{"role": "system", "content": "You are an Agent and must reason step by step and call tools to complete tasks."},
{"role": "user", "content": "What is the weather like in Shenzhen today?"},
]

# The OpenAI Python SDK has strict type signatures. Non-standard fields, such as reasoning_effort, must be passed through via the extra_body parameter.
resp1 = client.chat.completions.create(
model="hy4-preview",
messages=messages,
tools=tools,
tool_choice="auto",
extra_body={"reasoning_effort": "high"},
)
msg1 = resp1.choices[0].message
print("Round 1 assistant.reasoning_content:", getattr(msg1, "reasoning_content", ""))
print("Round 1 tool_calls:", msg1.tool_calls)
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const tools = [{
type: 'function',
function: {
name: 'get_weather',
description: 'Obtain weather information for a location. Input the location.',
parameters: {
type: 'object',
properties: { location: { type: 'string' } },
required: ['location'],
},
},
}];

const messages = [
{ role: 'system', content: 'You are an Agent and must reason step by step and call tools to complete tasks.' },
{ role: 'user', content: 'What is the weather like in Shenzhen today?' },
];

const resp1 = await client.chat.completions.create({
model: 'hy4-preview',
messages,
tools,
tool_choice: 'auto',
reasoning_effort: 'high',
});

const msg1 = resp1.choices[0].message;
console.log('Round 1 reasoning_content:', msg1.reasoning_content);
console.log('Round 1 tool_calls:', msg1.tool_calls);
import okhttp3.*;
import com.google.gson.*;
import java.util.*;

public class InterleavedThinking {
static final String URL = "https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions";
static final String API_KEY = "YOUR_API_KEY";
static final OkHttpClient HTTP = new OkHttpClient();
static final Gson GSON = new Gson();

/** A generic chat call that returns the raw JSON response string. */
static String chat(List<Map<String, Object>> messages, List<Map<String, Object>> tools) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("model", "hy4-preview");
body.put("messages", messages);
body.put("tools", tools);
body.put("tool_choice", "auto");
body.put("reasoning_effort", "high");
body.put("stream", false);

Request req = new Request.Builder()
.url(URL)
.header("Authorization", "Bearer " + API_KEY)
.post(RequestBody.create(GSON.toJson(body), MediaType.parse("application/json")))
.build();
try (Response resp = HTTP.newCall(req).execute()) {
return resp.body().string();
}
}

public static void main(String[] args) throws Exception {
List<Map<String, Object>> tools = List.of(Map.of(
"type", "function",
"function", Map.of(
"name", "get_weather",
"description", "Obtain weather information for a location. Input the location.",
"parameters", Map.of(
"type", "object",
"properties", Map.of("location", Map.of("type", "string")),
"required", List.of("location")
)
)
));

List<Map<String, Object>> messages = new ArrayList<>();
messages.add(Map.of("role", "system", "content", "You are an Agent and must reason step by step and call tools to complete tasks."));
messages.add(Map.of("role", "user", "content", "What is the weather like in Shenzhen today?"));

// Round 1: The model decides whether to call a tool
String r1 = chat(messages, tools);
System.out.println("Round 1 response: " + r1);
// Next, backfill the reasoning_content / tool_calls from the response into the messages. Refer to Step 2.
}
}
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

const (
URL = "https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions"
APIKEY = "YOUR_API_KEY"
)

// Generic chat call
func chat(messages []map[string]interface{}, tools []map[string]interface{}) (map[string]interface{}, error) {
body, _ := json.Marshal(map[string]interface{}{
"model": "hy4-preview",
"messages": messages,
"tools": tools,
"tool_choice": "auto",
"reasoning_effort": "high",
"stream": false,
})
req, _ := http.NewRequest("POST", URL, bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer "+APIKEY)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
var out map[string]interface{}
json.Unmarshal(data, &out)
return out, nil
}

func main() {
tools := []map[string]interface{}{{
"type": "function",
"function": map[string]interface{}{
"name": "get_weather",
"description": "Obtain weather information for a location. Input the location.",
"parameters": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"location": map[string]string{"type": "string"},
},
"required": []string{"location"},
},
},
}}

messages := []map[string]interface{}{
{"role": "system", "content": "You are an Agent and must reason step by step and call tools to complete tasks."},
{"role": "user", "content": "What is the weather like in Shenzhen today?"},
}

// Round 1: The model decides whether to call a tool
r1, _ := chat(messages, tools)
fmt.Printf("Round 1 response: %+v\\n", r1)
// Next, backfill the reasoning_content / tool_calls from the response into the messages. Refer to Step 2.
}
Response:
{
"id": "31be91fe574e41e49616352366b4fa1b",
"object": "chat.completion",
"created": 1776057110,
"model": "hy4-preview",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "I will help you check the weather in Shenzhen today.",
"reasoning_content": "The user asks, \\"What is the weather like in Shenzhen today?\\" This is a simple weather query request. I need to use the get_weather function to obtain the weather information for Shenzhen. According to the function description, this function requires a location parameter, and the user has explicitly provided \\"Shenzhen\\" as the location. Therefore, I should directly call the get_weather function with the location parameter set to \\"Shenzhen\\". No additional reasoning steps are required because the user's question is straightforward. Now, I am ready to call the function.",
"tool_calls": [
{
"id": "chatcmpl-tool-b39c6375f812783a",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\\"location\\": \\"Shenzhen\\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 209,
"completion_tokens": 111,
"total_tokens": 320
}
}
Round 2 - Backfill Tool Results (Continuing the Chain of Thought within the Same Round):
Assume the result returned by the tool execution is: Cloudy, temperature 7~13°C. In the request, you need to backfill the tool execution result while retaining the reasoning_content obtained from the response body of the initial request.
Request:
cURL
Python
Node.js
Java
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{ "role": "system", "content": "You are an Agent and must reason step by step and call tools to complete tasks." },
{"role": "user", "content": "What is the weather like in Shenzhen today?"},
{
"role": "assistant",
"content": "I will help you check the weather in Shenzhen today.",
"reasoning_content": "The user asks, \\"What is the weather like in Shenzhen today?\\"...",
"tool_calls": [
{
"id": "chatcmpl-tool-b39c6375f812783a",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\\"location\\": \\"Shenzhen\\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "chatcmpl-tool-b39c6375f812783a",
"content": "Cloudy, temperature 7~13°C"
}
],
"stream": false,
"tool_choice": "auto",
"reasoning_effort": "high",
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Obtain weather information for a location. Input the location."
"parameters": {
"type": "object",
"properties": { "location": { "type": "string" } },
"required": ["location"]
}
}
}
]
}'
# Continuing from the previous step: Add the assistant message from Round 1 (containing reasoning_content + tool_calls)
# Backfill into the messages along with the tool result
import json

# Backfill of the assistant message from Round 1: reasoning_content must be retained
assistant_msg = {
"role": "assistant",
"content": msg1.content,
"reasoning_content": getattr(msg1, "reasoning_content", ""),
"tool_calls": [
{
"id": tc.id,
"type": tc.type,
"function": {
"name": tc.function.name,
"arguments": tc.function.arguments,
},
} for tc in (msg1.tool_calls or [])
],
}
messages.append(assistant_msg)

# Execute the business-side tool and backfill the result with role=tool
for tc in (msg1.tool_calls or []):
args = json.loads(tc.function.arguments)
# Replace with actual business logic here
tool_result = "Cloudy, temperature 7~13°C"
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": tool_result,
})

# Round 2: Send the tool result back to the model, which then continues to think and outputs the final answer
resp2 = client.chat.completions.create(
model="hy4-preview",
messages=messages,
tools=tools,
tool_choice="auto",
extra_body={"reasoning_effort": "high"},
)
print("Final answer:", resp2.choices[0].message.content)
// Continuing from the previous step: Add the assistant message from Round 1 (containing reasoning_content + tool_calls)
// Backfill into the messages along with the tool result

const assistantMsg = {
role: 'assistant',
content: msg1.content,
reasoning_content: msg1.reasoning_content,
tool_calls: msg1.tool_calls,
};
messages.push(assistantMsg);

for (const tc of msg1.tool_calls || []) {
const args = JSON.parse(tc.function.arguments);
// Replace with actual business logic here
const toolResult = 'Cloudy, temperature 7~13°C';
messages.push({
role: 'tool',
tool_call_id: tc.id,
content: toolResult,
});
}

const resp2 = await client.chat.completions.create({
model: 'hy4-preview',
messages,
tools,
tool_choice: 'auto',
reasoning_effort: 'high',
});
console.log('Final answer:', resp2.choices[0].message.content);
// Following main(): Backfill the assistant message and tool result from Round 1, then initiate the Round 2 request
// Complete flow illustration (only message construction is shown; the HTTP call reuses the chat() function from the previous step)

// 1. Parse the Round 1 response
JsonObject r1Obj = JsonParser.parseString(r1).getAsJsonObject();
JsonObject msg1 = r1Obj.getAsJsonArray("choices").get(0).getAsJsonObject()
.getAsJsonObject("message");

// 2. Backfill the assistant message (including reasoning_content) as a whole into messages
Map<String, Object> assistantEntry = new LinkedHashMap<>();
assistantEntry.put("role", "assistant");
assistantEntry.put("content", msg1.has("content") ? msg1.get("content").getAsString() : "");
if (msg1.has("reasoning_content")) {
assistantEntry.put("reasoning_content", msg1.get("reasoning_content").getAsString());
}
if (msg1.has("tool_calls")) {
assistantEntry.put("tool_calls", GSON.fromJson(msg1.get("tool_calls"), List.class));
}
messages.add(assistantEntry);

// 3. Execute the tool on the business side and backfill the tool result with role=tool
for (JsonElement el : msg1.getAsJsonArray("tool_calls")) {
JsonObject call = el.getAsJsonObject();
String toolResult = "Cloudy, temperature 7~13°C"; // Replace with actual business logic here
messages.add(Map.of(
"role", "tool",
"tool_call_id", call.get("id").getAsString(),
"content", toolResult
));
}

// 4. Round 2: Send the tool result back to the model
String r2 = chat(messages, tools);
System.out.println("Round 2 response: " + r2);
// Following main(): Backfill the assistant message and tool result from Round 1, then initiate the Round 2 request
// Complete flow illustration (only message construction is shown; the HTTP call reuses the chat() function from the previous step)

// 1. Extract the assistant message from the Round 1 response
msg1Wrap := r1["choices"].([]interface{})[0].(map[string]interface{})
msg1 := msg1Wrap["message"].(map[string]interface{})

// 2. Backfill the assistant message (including reasoning_content) as a whole into messages
messages = append(messages, msg1)

// 3. Execute the tool on the business side and backfill the tool result with role=tool
toolCalls, _ := msg1["tool_calls"].([]interface{})
for _, c := range toolCalls {
call := c.(map[string]interface{})
toolResult := "Cloudy, temperature 7~13°C" // Replace with actual business logic here
messages = append(messages, map[string]interface{}{
"role": "tool",
"tool_call_id": call["id"],
"content": toolResult,
})
}

// 4. Round 2: Send the tool result back to the model
r2, _ := chat(messages, tools)
fmt.Printf("Round 2 response: %+v\\n", r2)
Response:
Afterwards, the model continues to output based on the actual reasoning results (which may involve further tool_calls or output the final answer). Before the final answer is obtained, the above process must be followed for each call to maintain the Large Language Model's chain of thought by "preserving reasoning_content + backfilling tool output".
{
"id": "ae8941415e154a3c9749f0cf897469a4",
"object": "chat.completion",
"created": 1776057913,
"model": "hy4-preview",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "According to the query results, the weather in Shenzhen today is **cloudy**, with temperatures ranging from **7°C to 13°C**. The weather is relatively cool today, so it is advisable to add appropriate clothing and keep warm! 🧥",
"reasoning_content": "The user inquired about today's weather in Shenzhen. I have called the get_weather tool to obtain the weather information for Shenzhen. The result shows \\"Cloudy, temperature 7~13°C\\".\\n\\nNow I need to reply to the user in Chinese, informing them of today's weather conditions in Shenzhen. The weather is cloudy (Cloudy), with temperatures ranging from 7 to 13 degrees Celsius.\\n\\nI should reply to the user concisely and clearly."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 340,
"completion_tokens": 114,
"total_tokens": 454
}
}

Multi-Turn Conversations

System prompts and conversation history are passed via the messages array. The model understands the context sequentially and continues the conversation. The message sequence must be system (optional) → user → assistant → user → ... and must end with user.
cURL
Python
Java
Node.js
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{"role": "system", "content": "You are a professional AI coding assistant."},
{"role": "user", "content": "How to read a JSON file in Python?"},
{"role": "assistant", "content": "You can use the built-in json module: import json; with open(\\"data.json\\") as f: data = json.load(f)"},
{"role": "user", "content": "What should I do if the JSON file is very large?"}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

response = client.chat.completions.create(
model="hy4-preview",
messages=[
{"role": "system", "content": "You are a professional AI coding assistant."},
{"role": "user", "content": "How to read a JSON file in Python?"},
{"role": "assistant", "content": "You can use the built-in json module: import json; with open('data.json') as f: data = json.load(f)"},
{"role": "user", "content": "What should I do if the JSON file is very large?"},
],
)
print(response.choices[0].message.content)
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class MultiTurn {
public static void main(String[] args) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("model", "hy4-preview");
body.put("messages", List.of(
Map.of("role", "system", "content", "You are a professional AI coding assistant."),
Map.of("role", "user", "content", "How to read a JSON file in Python?"),
Map.of("role", "assistant", "content", "You can use the built-in json module: import json; with open(\\"data.json\\") as f: data = json.load(f)"),
Map.of("role", "user", "content", "What should I do if the JSON file is very large?"),
));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body),
MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const response = await client.chat.completions.create({
model: 'hy4-preview',
messages: [
{ role: 'system', content: 'You are a professional AI coding assistant.' },
{ role: 'user', content: 'How to read a JSON file in Python?' },
{ role: 'assistant', content: 'You can use the built-in json module: import json; with open("data.json") as f: data = json.load(f)' },
{ role: 'user', content: 'What should I do if the JSON file is very large?' },
],
});
console.log(response.choices[0].message.content);
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
body, _ := json.Marshal(map[string]interface{}{
"model": "hy4-preview",
"messages": []map[string]string{
{"role": "system", "content": "You are a professional AI coding assistant."},
{"role": "user", "content": "How to read a JSON file in Python?"},
{"role": "assistant", "content": "You can use the built-in json module: import json; with open(\\"data.json\\") as f: data = json.load(f)"},
{"role": "user", "content": "What should I do if the JSON file is very large?"},
},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Note:
When the conversation history contains reasoning-type responses, it is recommended that the assistant message being written back include both the content and reasoning_content fields to prevent the loss of reasoning context.

Tool Calling (Function Calling)

By defining a list of callable functions via tools, the model returns tool_calls when it determines a tool needs to be invoked. After the business logic is executed, the result is backfilled as a role: "tool" message, and the model then generates the final answer based on this.
cURL
Python
Java
Node.js
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{"role": "user", "content": "What is the weather like in Shenzhen today?"}
],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Obtain current weather information for a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example: Beijing"}
},
"required": ["city"]
}
}
}],
"tool_choice": "auto"
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Obtain current weather information for a specified city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string", "description": "City name, for example: Beijing"}},
"required": ["city"],
},
},
}]

response = client.chat.completions.create(
model="hy4-preview",
messages=[{"role": "user", "content": "What is the weather like in Shenzhen today?"}],
tools=tools,
tool_choice="auto",
)
print(response.choices[0].message)
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class FunctionCalling {
public static void main(String[] args) throws Exception {
Map<String, Object> tool = Map.of(
"type", "function",
"function", Map.of(
"name", "get_weather",
"description", "Obtain current weather information for a specified city",
"parameters", Map.of(
"type", "object",
"properties", Map.of("city", Map.of("type", "string", "description", "City name, for example: Beijing")),
"required", List.of("city")
)
)
);

Map<String, Object> body = new HashMap<>();
body.put("model", "hy4-preview");
body.put("messages", List.of(Map.of("role", "user", "content", "What is the weather like in Shenzhen today?")));
body.put("tools", List.of(tool));
body.put("tool_choice", "auto");

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body),
MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const tools = [{
type: 'function',
function: {
name: 'get_weather',
"description": "Obtain current weather information for a specified city",
parameters: {
type: 'object',
"properties": {"city": {"type": "string", "description": "City name, for example: Beijing"}},
required: ['city'],
},
},
}];

const response = await client.chat.completions.create({
model: 'hy4-preview',
messages: [{ role: 'user', content: 'What is the weather like in Shenzhen today?' }],
tools,
tool_choice: 'auto',
});
console.log(response.choices[0].message);
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
tool := map[string]interface{}{
"type": "function",
"function": map[string]interface{}{
"name": "get_weather",
"description": "Obtain current weather information for a specified city",
"parameters": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"city": map[string]interface{}{"type": "string", "description": "City name, for example: Beijing"},
},
"required": []string{"city"},
},
},
}

body, _ := json.Marshal(map[string]interface{}{
"model": "hy4-preview",
"messages": []map[string]string{{"role": "user", "content": "What is the weather like in Shenzhen today?"}},
"tools": []map[string]interface{}{tool},
"tool_choice": "auto",
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Response when the model decides to call a tool:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy4-preview",
"created": 1775146513,
"choices": [
{
"index": 0,
"message": {

"role": "assistant",
"content": "I will help you check the weather in Shenzhen today.",
"reasoning_content": "The user asks about the weather in Shenzhen today. I need to call the get_weather function to obtain the weather information for Shenzhen.",
"tool_calls": [
{
"id": "REPLACED_ID",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\\"city\\": \\"Shenzhen\\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 199,
"completion_tokens": 43,
"total_tokens": 242,
"prompt_tokens_details": {
"cached_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 19
}
}
}
Continue the conversation by backfilling the tool execution result:
{
"model": "hy4-preview",
"messages": [
{"role": "user", "content": "What is the weather like in Shenzhen today?"},
{
"role": "assistant",
"content": "I will help you check the weather in Shenzhen today.",
"tool_calls": [{
"id": "REPLACED_ID",
"type": "function",
"function": {"name": "get_weather", "arguments": "{\\"city\\": \\"Shenzhen\\"}"}
}]
},
{
"role": "tool",
"tool_call_id": "REPLACED_ID",
"content": "{\\"temperature\\":28,\\"weather\\":\\"Sunny\\",\\"humidity\\":\\"65%\\"}"
}
]
}
Attention:
When making tool calls in the reasoning_effort=low/high slow-thinking mode, backfill the historical  reasoning_content for each request to obtain the best results.

Structured Output

By using response_format to constrain the model to output according to the specified JSON Schema, it is commonly used in scenarios such as information extraction and structured data generation.
cURL
Python
Java
Node.js
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy4-preview",
"messages": [
{"role": "user", "content": "Please extract the person information from the following text: Zhang San, 35 years old, is a senior software engineer proficient in Python, Java, and machine learning."}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "person_info",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Person's name"},
"age": {"type": "integer", "description": "Age"},
"occupation": {"type": "string", "description": "Occupation"},
"skills": {"type": "array", "items": {"type": "string"}, "description": "List of skills"}
},
"required": ["name", "age", "occupation", "skills"]
}
}
}
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

schema = {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Person's name"},
"age": {"type": "integer", "description": "Age"},
"occupation": {"type": "string", "description": "Occupation"},
"skills": {"type": "array", "items": {"type": "string"}, "description": "List of skills"},
},
"required": ["name", "age", "occupation", "skills"],
}

response = client.chat.completions.create(
model="hy4-preview",
messages=[
{"role": "user", "content": "Please extract the person information from the following text: Zhang San, 35 years old, is a senior software engineer proficient in Python, Java, and machine learning."},
],
response_format={
"type": "json_schema",
"json_schema": {"name": "person_info", "schema": schema},
},
)
print(response.choices[0].message.content)
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class StructuredOutput {
public static void main(String[] args) throws Exception {
Map<String, Object> schema = Map.of(
"type", "object",
"properties", Map.of(
"name", Map.of("type", "string", "description", "Person's name"),
"age", Map.of("type", "integer", "description", "Age"),
"occupation", Map.of("type", "string", "description", "Occupation"),
"skills", Map.of("type", "array", "items", Map.of("type", "string"), "description", "List of skills")
),
"required", List.of("name", "age", "occupation", "skills")
);

Map<String, Object> body = new HashMap<>();
body.put("model", "hy4-preview");
body.put("messages", List.of(Map.of("role", "user", "content",
"Please extract the person information from the following text: Zhang San, 35 years old, is a senior software engineer proficient in Python, Java, and machine learning."
body.put("response_format", Map.of(
"type", "json_schema",
"json_schema", Map.of("name", "person_info", "schema", schema)
));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body),
MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const schema = {
type: 'object',
properties: {
name: { type: 'string', description: 'Person\\'s name' },
age: { type: 'integer', description: 'Age' },
occupation: { type: 'string', description: 'Occupation' },
skills: { type: 'array', items: { type: 'string' }, description: 'List of skills' },
},
required: ['name', 'age', 'occupation', 'skills'],
};

const response = await client.chat.completions.create({
model: 'hy4-preview',
messages: [
{ role: 'user', content: 'Please extract the person information from the following text: Zhang San, 35 years old, is a senior software engineer proficient in Python, Java, and machine learning.' },
],
response_format: {
type: 'json_schema',
json_schema: { name: 'person_info', schema },
},
});
console.log(response.choices[0].message.content);
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
schema := map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]interface{}{"type": "string", "description": "Person's name"},
"age": map[string]interface{}{"type": "integer", "description": "Age"},
"occupation": map[string]interface{}{"type": "string", "description": "Occupation"},
"skills": map[string]interface{}{
"type": "array", "items": map[string]string{"type": "string"}, "description": "List of skills",
},
},
"required": []string{"name", "age", "occupation", "skills"},
}

body, _ := json.Marshal(map[string]interface{}{
"model": "hy3",
"messages": []map[string]string{
{"role": "user", "content": "Please extract the person information from the following text: Zhang San, 35 years old, is a senior software engineer proficient in Python, Java, and machine learning."},
},
"response_format": map[string]interface{}{
"type": "json_schema",
"json_schema": map[string]interface{}{
"name": "person_info",
"schema": schema,
},
},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Response Example:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy4-preview",
"created": 1775146513,
"choices": [
{
"index": 0,
"message": {

"role": "assistant",
"content": "{\\n \\"name\\": \\"Zhang San\\",\\n \\"age\\": 35,\\n \\"occupation\\": \\"Senior Software Engineer\\",\\n \\"skills\\": [\\"Python\\", \\"Java\\", \\"Machine Learning\\"]\\n}",
"reasoning_content": "We need to answer in Chinese. The user asks: \\"Please extract the person information from the following text: Zhang San, 35 years old, is a senior software engineer proficient in Python, Java, and machine learning.\\" We need to extract the person information. We can present structured fields: Name: Zhang San; Age: 35; Occupation/Position: Senior Software Engineer; Skills: Python, Java, Machine Learning. We could also mention that we can format the output. The task is simple, so we should not overcomplicate it. We need to Ensure the answer is direct. We might include a table or JSON. Since the user asked to extract person information, we can output JSON and/or a bullet list. Let's keep it concise and Use Chinese. We could say: \\"Extraction results are as follows:\\" followed by a bullet list. We do not need to include the raw text. Let's provide structured information.\\n\\nWe need to consider potential ambiguity: \\"Senior Software Engineer\\" is a job title, and \\"proficient in\\" refers to skills or proficiencies. The age is 35. The name is Zhang San. Good.\\n\\nLet's finalize the output:\\n{\\n \\"Name\\": \\"Zhang San\\",\\n \\"Age\\": 35,\\n \\"Occupation\\": \\"Senior Software Engineer\\",\\n \\"Skills\\": [\\"Python\\", \\"Java\\", \\"Machine Learning\\"]\\n}\\nOr include units. We might note the age unit as years. That's it."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 45,
"completion_tokens": 294,
"total_tokens": 339,
"prompt_tokens_details": {
"cached_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 252
}
}
}

Translation Model

Hy-MT2 is a family of "fast-thinking" multilingual translation models designed for complex real-world scenarios. It includes three model sizes: 1.8B, 7B, and 30B-A3B (MoE), all of which support translation among 33 languages and effectively follow translation instructions in multiple languages. Multi-dimensional evaluations show that Hy-MT2 delivers outstanding performance across general, real-world business, domain-specific, and instruction-following translation tasks.

Supported Models

model (API Parameter)
Capability Description
Context Window
Max Input
Max Output
hy-mt2-pro
Hy's flagship translation model, with 30B-A3B parameters, suitable for professional domains and other scenarios that demand high translation quality, and featuring excellent instruction-following capability. It supports a comprehensive range of languages, with a focus on 33 languages for mutual translation, and supports 5 ethnic minority languages/Chinese dialects.
8k
4k
4k
hy-mt2-plus
Hy translation model, with 7B parameters. It delivers leading performance in the industry, excels on open-source test sets such as Flores 200 and WMT25, and performs excellently in professional domains and real-world business scenarios. It supports a comprehensive range of languages, with a focus on 33 languages for mutual translation, and supports 5 ethnic minority languages/Chinese dialects.
8k
4k
4k
hy-mt2-lite
Hy lightweight translation model, with 1.8B parameters. It is suitable for scenarios that have high requirements for latency. It supports a comprehensive range of languages, with a focus on 33 languages for mutual translation, and supports 5 ethnic minority languages/Chinese dialects.
8k
4k
4k

Default Translation

In the most common translation scenario, the target language is explicitly specified within the user message (target_lang should use the full Chinese name, such as "English", "French", or "Chinese").
"messages": [{"role": "user", "content": "Translate the following text into {target_lang}. Note: Output only the translated result without any additional explanation: {source_text}"}]
cURL
Python
Java
Node.js
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy-mt2-plus",
"messages": [
{"role": "user", "content": "Translate the following text into French. Note: Output only the translated result without any additional explanation: Please ensure that all attendees have received the agenda before the meeting starts."}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

target_lang = "French"
source_text = "Please ensure that all attendees have received the agenda before the meeting starts."

prompt = f"""Translate the following text into {target_lang}. Only output the translated result, without any additional explanation:
{source_text}"""

response = client.chat.completions.create(
model="hy-mt2-plus",
messages=[{"role": "user", "content": prompt}],
)
print(response.choices[0].message.content)
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class TranslationDemo {
public static void main(String[] args) throws Exception {
String targetLang = "French";
String sourceText = "Please ensure that all attendees have received the agenda before the meeting starts.";
String prompt = "Translate the following text into " + targetLang + ". Only output the translated result, without any additional explanation:\\n" + sourceText;

Map<String, Object> body = new HashMap<>();
body.put("model", "hy-mt2-plus");
body.put("messages", List.of(
Map.of("role", "user", "content", prompt)
));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body),
MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const targetLang = 'French';
const sourceText = 'Please ensure that all attendees have received the agenda before the meeting starts.';
const prompt = `Translate the following text into ${targetLang}. Only output the translated result, without any additional explanation:\\n${sourceText}`;

const response = await client.chat.completions.create({
model: 'hy-mt2-plus',
messages: [{ role: 'user', content: prompt }],
});
console.log(response.choices[0].message.content);
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
targetLang := "French"
sourceText := "Please ensure that all attendees have received the agenda before the meeting starts."
prompt := "Translate the following text into " + targetLang + ". Only output the translated result, without any additional explanation:\\n" + sourceText

body, _ := json.Marshal(map[string]interface{}{
"model": "hy-mt2-plus",
"messages": []map[string]string{
{"role": "user", "content": prompt},
},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Response Example:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy-mt2-plus",
"created": 1775146513,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Veuillez vous assurer que tous les participants ont reçu l’ordre du jour avant le début de la réunion."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 26,
"completion_tokens": 28,
"total_tokens": 54,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 0}
}
}

Structured Data Translation

When the original text is structured data such as JSON / Markdown / HTML / XML, the model "locks the structure, translates only the visible values, and retains all keys and placeholders."
"messages": [{"role": "user", "content": "
# Task Objective
Translate the {format_type} format data in the following {source_text} into {target_lang}.

# Strict Constraints
1. Structure Locking: Absolutely keep the original {format_type} data structure, indentation, and hierarchy completely unchanged.
2. Selective Translation: Translate only the visible text content that is displayed to users.
3. No Modification: Do not translate or alter any code tags, key names (Key), variable placeholders (such as {{var}}, ${var}, %s, %d, etc.), or code attributes.

# Data Input
{source_text}"}]
cURL
Python
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy-mt2-plus",
"messages": [
{"role": "user", "content": "# Task Objective\\nTranslate the JSON format data in the following source_text into French.\\n\\n# Strict Constraints\\n1. Structure Locking: Absolutely keep the original JSON data structure, indentation, and hierarchy completely unchanged.\\n2. Selective Translation: Translate only the visible text content that is displayed to users.\\n3. No Modification: Do not translate or alter any code tags, key names (Key), variable placeholders (such as {{var}}, ${var}, %s, %d, etc.), or code attributes.\\n\\n# Data Input\\n{\\"title\\": \\"West Lake Scenic Area\\", \\"description\\": \\"Located in the heart of Hangzhou, it is a national 5A-level tourist attraction known for its pleasant scenery throughout the four seasons.\\", \\"tags\\": [\\"Natural Scenery\\", \\"World Heritage\\", \\"Free Admission\\"]}"}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

target_lang = "French"
format_type = "JSON"
source_text = '{"title": "West Lake Scenic Area", "description": "Located in the heart of Hangzhou, it is a national 5A-level tourist attraction known for its pleasant scenery throughout the four seasons.", "tags": ["Natural Scenery", "World Heritage", "Free Admission"]}'

prompt = f"""# Task Objective
Translate the {format_type} format data in the following source_text into {target_lang}.

# Strict Constraints
1. Structure Locking: Absolutely keep the original {format_type} data structure, indentation, and hierarchy completely unchanged.
2. Selective Translation: Translate only the visible text content that is displayed to users.
3. No Modification: Do not translate or alter any code tags, key names (Key), variable placeholders (such as {{var}}, ${{var}}, %s, %d, etc.), or code attributes.

# Data Input
{source_text}"""

response = client.chat.completions.create(
model="hy-mt2-plus",
messages=[{"role": "user", "content": prompt}],
)
print(response.choices[0].message.content)
Response Example:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy-mt2-plus",
"created": 1779966611,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{\\"title\\": \\"Zone panoramique du lac de l’Ouest\\", \\"description\\": \\"Située au cœur de Hangzhou, il s’agit d’une attraction touristique nationale de niveau 5A réputée pour ses paysages magnifiques tout au long des quatre saisons.\\", \\"tags\\": [\\"Paysages naturels\\", \\"Patrimoine mondial\\", \\"Entrée gratuite\\"]}"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 145,
"completion_tokens": 87,
"total_tokens": 232,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 0}
}
}

Delimiters Translation

When you need to compare sentences side-by-side or translate multiple text segments in batches, instruct the model to retain an equal number of delimiters without omission, escaping, or translation, to facilitate alignment by index on the business side.
It is recommended to use tags such as <SEP> and ### that do not conflict with target language punctuation as delimiters. Tags like ||| and --- can be recognized as exclamation marks, dashes, or other punctuation marks in some languages, making the translated text unsplittable.
"messages": [{"role": "user", "content": "Please accurately translate the following text into {target_lang}.
You must retain an equal number of delimiters in the translation. Do not omit, escape, or translate this symbol, and pay attention to the delimiter positions. {source_text}"}]
cURL
Python
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy-mt2-plus",
"messages": [
{"role": "user", "content": "Please accurately translate the following text into French. You must retain an equal number of delimiters in the translation. Do not omit, escape, or translate this symbol, and pay attention to the delimiter positions.\\nGetting eight hours of sleep every day is beneficial for good health<SEP>Properly planning work and rest can improve efficiency<SEP>Moderate exercise can effectively relieve stress"}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

target_lang = "French"
SEP = "<SEP>"
source_segments = ["Getting eight hours of sleep every day is beneficial for good health", "Properly planning work and rest can improve efficiency", "Moderate exercise can effectively relieve stress"]
source_text = SEP.join(source_segments)

prompt = f"""Please accurately translate the following text into {target_lang}. You must retain an equal number of delimiters in the translation. Do not omit, escape, or translate this symbol, and pay attention to the delimiter positions.
{source_text}"""

response = client.chat.completions.create(
model="hy-mt2-plus",
messages=[{"role": "user", "content": prompt}],
)

translated = response.choices[0].message.content.split(SEP)
for src, tgt in zip(source_segments, translated):
print(f"{src.strip()} → {tgt.strip()}")
Response Example:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy-mt2-plus",
"created": 1779966612,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Dormir huit heures par jour est bénéfique pour une bonne santé<SEP>Planifier correctement le travail et les moments de repos peut améliorer l’efficacité<SEP>Une activité physique modérée peut soulager efficacement le stress"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 74,
"completion_tokens": 59,
"total_tokens": 133,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 0}
}
}

Contextual Translation

When the original text contains polysemous words, proper nouns, or pronoun references that require contextual disambiguation, providing "background information" enables the model to select terminology consistent with the context.
"messages": [{"role": "user", "content": "
[Background Information] {background_text}
Please translate the following text into {target_lang} by incorporating the background information.
[Text to be translated] {source_text}"}]
cURL
Python
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy-mt2-plus",
"messages": [
{"role": "user", "content": "[Background Information]\\nThis is a technical document introducing database systems. The transaction mentioned above refers to database transactions, and index refers to database indexes.\\nPlease translate the following text into French by incorporating the background information.\\n[Text to be translated]\\nAfter a transaction is committed, the index is asynchronously flushed to disk."}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

target_lang = "French"
background_text = "This is a technical document introducing database systems. The transaction mentioned above refers to database transactions, and index refers to database indexes."
source_text = "After a transaction is committed, the index is asynchronously flushed to disk."

prompt = f"""[Background Information]
{background_text}
Please translate the following text into {target_lang} by incorporating the background information.
[Text to be translated]
{source_text}"""

response = client.chat.completions.create(
model="hy-mt2-plus",
messages=[{"role": "user", "content": prompt}],
)
print(response.choices[0].message.content)
Response Example:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy-mt2-plus",
"created": 1779966614,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Une fois une transaction validée, l’index est écrit de manière asynchrone sur le disque."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 65,
"completion_tokens": 24,
"total_tokens": 89,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 0}
}
}

Terminology Translation

When the business side possesses a domain glossary (containing product names, brand terms, proprietary nouns, and so on, which require fixed translations), you can preload the term comparison list as a reference. The model then prioritizes using the specified translations.
"messages": [{"role": "user", "content": "
Refer to the translation below:
{text} translated into {text}
{text} translated into {text}
{text} translated into {text}
Translate the following text into {target_lang}. Only output the translated result, without any additional explanation: {source_text}"}]
cURL
Python
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy-mt2-plus",
"messages": [
{"role": "user", "content": "Refer to the translation below:\\npremiere translated to première\\nratings translated to audiences\\nTranslate the following text into French. Note: Output only the translated result without any additional explanation:\\nThe audiences for this drama kept rising after its première on media platforms."}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

target_lang = "French"
glossary = [
("premiere", "première"),
("ratings", "audiences"),
]
source_text = "The ratings for this drama kept rising after its premiere on media platforms."

glossary_text = "\\n".join(f"{src} translated into {tgt}" for src, tgt in glossary)
prompt = f"""Refer to the translation below:
{glossary_text}
Translate the following text into {target_lang}. Only output the translated result, without any additional explanation:
{source_text}"""

response = client.chat.completions.create(
model="hy-mt2-plus",
messages=[{"role": "user", "content": prompt}],
)
print(response.choices[0].message.content)
Response Example:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy-mt2-plus",
"created": 1779967706,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Les audiences de cette série ont continué d’augmenter après sa première diffusion sur les plateformes médiatiques."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 58,
"completion_tokens": 28,
"total_tokens": 86,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 0}
}
}

Style Translation

Different business scenarios require different translation styles (colloquial / formal / marketing copy / legal contracts / academic / classical Chinese). Describe the target style, and the model will adjust its vocabulary and sentence structures accordingly.
"messages": [{"role": "user", "content": "
Please translate the following text into {target_lang}.
Ensure the translation style strictly adheres to {target_style}.
{source_text}"}]
cURL
Python
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy-mt2-plus",
"messages": [
{"role": "user", "content": "Please translate the following text into French. Ensure the translation style strictly adheres to [popular science copy: concise, impactful, and engaging language].\\nModerate outdoor activities help regulate emotions and alleviate mental stress."}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

target_lang = "French"
target_style = "popular science copy: concise, impactful, and engaging language"
source_text = "Moderate outdoor activities help regulate emotions and alleviate mental stress."

prompt = f"""Please translate the following text into {target_lang}. Ensure the translation style strictly adheres to {target_style}.
{source_text}"""

response = client.chat.completions.create(
model="hy-mt2-plus",
messages=[{"role": "user", "content": prompt}],
)
print(response.choices[0].message.content)
Response Example:
{
"id": "REPLACED_ID",
"object": "chat.completion",
"model": "hy-mt2-plus",
"created": 1779966617,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Les activités physiques modérées en plein air aident à réguler les émotions et à réduire le stress mental."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 43,
"completion_tokens": 30,
"total_tokens": 73,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 0}
}
}

Glossary

Unlike the Terminology Translation approach (embedding terms in prompts) described above, this section uses a dedicated translation API and a persistent glossary, making it more suitable for engineering scenarios with large volumes of frequently reused terms.
Attention:
Currently, only the OpenAPI protocol supports using the translation glossary. API endpoint: https://tokenhub-intl.tencentcloudmaas.com/v1/api/translations
You can refer to glossary management APIs to create, modify, and query glossary.
The glossary feature is currently available only for the Hy-MT2-Plus model. Hy-MT2-Pro and Hy-MT2-Lite are not supported yet.
Request Parameter Description
Parameter
Type
Required
Description
model
string
Yes
The model parameter, for example hy-mt2-plus
text
string
Yes
The text to be translated
target
string
Yes
Target language code
source
string
No
The source language code. If not provided, the model automatically identifies it.
stream
bool
No
Whether to return in streaming mode. The default value is false.
context
string
No
Context information for making the translation more coherent.
references
list of object
No
Reference examples (sentences or terms), up to 10.
glossary_ids
list of string
No
A list of glossary IDs, up to 10
Response Field Description
Field
Type
Description
id
string
id of this request
Created
integer
Unix timestamp
choices
list
Returned replies, supporting multiple
choices[n].finish_reason
string
stop indicates normal termination, and sensitive indicates review failure.
choices[n].message
json
Returned content
choices[n].message.role
string
Role Name
choices[n].message.content
string
Translated text
choices[n].delta
json
Returned content (streaming)
choices[n].delta.role
string
Role Name (streaming)
choices[n].delta.content
string
Translated text (streaming)
source
string
Source language of the request
target
string
Target language
usage
object
token usage
Example Requests
cURL
Python
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/api/translations' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{
"model": "hy-mt2-plus",
"text": "This model is equipped with an advanced Battery Management System (BMS), offering a driving range of over 600 kilometers along with fast charging support.",
"source": "en",
"target": "fr",
"glossary_ids": ["YOUR_GLOSSARY_ID"]
}'
import requests

url = "https://tokenhub-intl.tencentcloudmaas.com/v1/api/translations"
headers = {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
}
payload = {
"model": "hy-mt2-plus",
"text": "This model is equipped with an advanced Battery Management System (BMS), offering a driving range of over 600 kilometers along with fast charging support.",
"source": "en",
"target": "fr",
"glossary_ids": ["YOUR_GLOSSARY_ID"],
}

response = requests.post(url, headers=headers, json=payload)
data = response.json()
print(data["choices"][0]["message"]["content"])
Response Example
{
"id": "REPLACED_ID",
"created": 1781604284,
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "Ce modèle est équipé d’un système avancé de gestion de batterie (BMS), qui lui permet d’atteindre une autonomie de plus de 600 kilomètres, tout en offrant une fonction de charge rapide."
}
}
],
"source": "en",
"target": "fr",
"usage": {
"prompt_tokens": 85,
"completion_tokens": 46,
"total_tokens": 131
}
}

Supported Languages

Language
English Name
Code
Simplified Chinese
Chinese
zh
Traditional Chinese
Traditional Chinese
zh-TR
English
English
en
French
French
fr
Portuguese
Portuguese
pt
Spanish
Spanish
es
Japanese
Japanese
ja
Turkish
Turkish
tr
Russian
Russian
ru
Arabic
Arabic
ar
Korean
Korean
ko
Thai
Thai
th
Italian
Italian
it
German
German
de
Vietnamese
Vietnamese
vi
Malay
Malay
ms
Indonesian
Indonesian
id
Filipino
Filipino
fil
Hindi
Hindi
hi
Polish
Polish
pl
Czech
Czech
cs
Dutch
Dutch
nl
Khmer
Khmer
km
Burmese
Burmese
my
Persian
Persian
fa
Gujarati
Gujarati
gu
Urdu
Urdu
ur
Telugu
Telugu
te
Marathi
Marathi
mr
Hebrew
Hebrew
he
Bengali
Bengali
bn
Tamil
Tamil
ta
Ukrainian
Ukrainian
uk
Tibetan
Tibetan
bo
Kazakh
Kazakh
kk
Mongolian
Mongolian
mn
Uyghur
Uyghur
ug
Cantonese
Cantonese
yue


Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan