Skip to content

Commit becf742

Browse files
refactor(spring-ai-hunyuan): 重构代码并添加注释
- 修改类名和方法名以符合规范 - 添加必要的注释说明 - 优化代码结构和逻辑 - 更新类 HunYuanRuntimeHints 的描述- 重构 HunYuanAuthApi 类,添加新方法并优化现有方法 - 更新 HunYuanApi 类,移除未使用的代码并添加新功能
1 parent a978788 commit becf742

File tree

3 files changed

+61
-53
lines changed

3 files changed

+61
-53
lines changed

models/spring-ai-hunyuan/src/main/java/org/springframework/ai/hunyuan/aot/HunYuanRuntimeHints.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@
2626
import static org.springframework.ai.aot.AiRuntimeHints.findJsonAnnotatedClassesInPackage;
2727

2828
/**
29-
* The MoonshotRuntimeHints class is responsible for registering runtime hints for
30-
* Moonshot API classes.
29+
* The HunYuanRuntimeHints class is responsible for registering runtime hints for
30+
* HunYuan API classes.
3131
*
3232
* @author Guo Junyu
3333
*/

models/spring-ai-hunyuan/src/main/java/org/springframework/ai/hunyuan/api/HunYuanApi.java

Lines changed: 7 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
import org.springframework.web.reactive.function.client.WebClient;
4949

5050
/**
51-
* Single-class, Java Client library for Hunyuan platform. Provides implementation for
51+
* Single-class, Java Client library for HunYuan platform. Provides implementation for
5252
* the <a href="https://cloud.tencent.com/document/api/1729/105701">Chat Completion</a> APIs.
5353
* <p>
5454
* Implements <b>Synchronous</b> and <b>Streaming</b> chat completion.
@@ -135,7 +135,7 @@ public ResponseEntity<ChatCompletionResponse> chatCompletionEntity(ChatCompletio
135135
.body(chatRequest)
136136
.retrieve()
137137
.toEntity(String.class);
138-
// 使用 ObjectMapper 将响应体字符串转换为 ChatCompletionResponse 对象
138+
// Compatible Return Position text/plain
139139
logger.info("Response body: {}", retrieve.getBody());
140140
ChatCompletionResponse chatCompletionResponse = ModelOptionsUtils.jsonToObject(retrieve.getBody(), ChatCompletionResponse.class);
141141
return ResponseEntity.ok(chatCompletionResponse);
@@ -212,26 +212,11 @@ public enum ChatCompletionFinishReason {
212212
*/
213213
@JsonProperty("stop")
214214
STOP,
215-
/**
216-
* The maximum number of tokens specified in the request was reached.
217-
*/
218-
@JsonProperty("length")
219-
LENGTH,
220-
/**
221-
* The content was omitted due to a flag from our content filters.
222-
*/
223-
@JsonProperty("content_filter")
224-
CONTENT_FILTER,
225215
/**
226216
* The model called a tool.
227217
*/
228218
@JsonProperty("tool_calls")
229-
TOOL_CALLS,
230-
/**
231-
* Only for compatibility with Mistral AI API.
232-
*/
233-
@JsonProperty("tool_call")
234-
TOOL_CALL;
219+
TOOL_CALLS;
235220

236221
private final String jsonValue;
237222

@@ -244,7 +229,7 @@ public String getJsonValue() {
244229
}
245230

246231
/**
247-
* Hunyuan Chat Completion Models:
232+
* HunYuan Chat Completion Models:
248233
*
249234
* <ul>
250235
* <li><b>HUNYUAN_LITE</b> - hunyuan-lite</li>
@@ -322,9 +307,6 @@ public record Usage(
322307
*
323308
* @param model ID of the model to use.
324309
* @param messages A list of messages comprising the conversation so far.
325-
* @param maxTokens The maximum number of tokens to generate in the chat completion.
326-
* The total length of input tokens and generated tokens is limited by the model's
327-
* context length.
328310
* @param temperature What sampling temperature to use, between 0 and 1. Higher values
329311
* like 0.8 will make the output more random, while lower values like 0.2 will make it
330312
* more focused and deterministic. We generally recommend altering this or top_p but
@@ -333,22 +315,16 @@ public record Usage(
333315
* where the model considers the results of the tokens with top_p probability mass. So
334316
* 0.1 means only the tokens comprising the top 10% probability mass are considered.
335317
* We generally recommend altering this or temperature but not both.
336-
* @param n How many chat completion choices to generate for each input message. Note
337-
* that you will be charged based on the number of generated tokens across all the
338-
* choices. Keep n as 1 to minimize costs.
339-
* @param presencePenalty Number between -2.0 and 2.0. Positive values penalize new
340-
* tokens based on whether they appear in the text so far, increasing the model's
341-
* likelihood to talk about new topics.
342-
* @param frequencyPenalty Number between -2.0 and 2.0. Positive values penalize new
343-
* tokens based on their existing frequency in the text so far, decreasing the model's
344-
* likelihood to repeat the same line verbatim.
345318
* @param stop Up to 5 sequences where the API will stop generating further tokens.
346319
* @param stream If set, partial message deltas will be sent.Tokens will be sent as
347320
* data-only server-sent events as they become available, with the stream terminated
348321
* by a data: [DONE] message.
349322
* @param tools A list of tools the model may call. Currently, only functions are
350323
* supported as a tool.
351324
* @param toolChoice Controls which (if any) function is called by the model.
325+
* @param customTool A custom tool to be used by the model.
326+
* @param searchInfo Whether to include search information in the response.
327+
* @param citation Whether to include citation information in the response.
352328
*/
353329
@JsonInclude(Include.NON_NULL)
354330
public record ChatCompletionRequest(

models/spring-ai-hunyuan/src/main/java/org/springframework/ai/hunyuan/api/auth/HunYuanAuthApi.java

Lines changed: 52 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package org.springframework.ai.hunyuan.api.auth;
22

3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
35
import org.springframework.ai.hunyuan.api.HunYuanApi;
46
import org.springframework.ai.hunyuan.api.HunYuanConstants;
57
import org.springframework.ai.model.ModelOptionsUtils;
@@ -18,19 +20,38 @@
1820
import javax.xml.bind.DatatypeConverter;
1921

2022
import static org.springframework.ai.hunyuan.api.HunYuanConstants.CT_JSON;
21-
23+
/**
24+
* The HunYuanAuthApi class is responsible for handling authentication-related operations
25+
* for the HunYuan API. It provides methods to generate necessary headers and signatures
26+
* required for authenticated requests.
27+
* @author Your Name
28+
*/
2229
public class HunYuanAuthApi {
30+
31+
private static final Logger logger = LoggerFactory.getLogger(HunYuanAuthApi.class);
32+
2333
private final static Charset UTF8 = StandardCharsets.UTF_8;
2434

2535
private final String secretId;
2636

2737
private final String secretKey;
2838

39+
/**
40+
* Constructs a HunYuanAuthApi instance with the specified secret ID and secret key.
41+
* @param secretId The secret ID used for authentication.
42+
* @param secretKey The secret key used for authentication.
43+
*/
2944
public HunYuanAuthApi(String secretId, String secretKey) {
3045
this.secretId = secretId;
3146
this.secretKey = secretKey;
3247
}
3348

49+
/**
50+
* Generates an HMAC-SHA256 signature using the provided key and message.
51+
* @param key The key used for generating the HMAC-SHA256 signature.
52+
* @param msg The message to be signed.
53+
* @return The byte array of the generated HMAC-SHA256 signature.
54+
*/
3455
public byte[] hmac256(byte[] key, String msg){
3556
Mac mac = null;
3657
try {
@@ -43,6 +64,11 @@ public byte[] hmac256(byte[] key, String msg){
4364
return mac.doFinal(msg.getBytes(UTF8));
4465
}
4566

67+
/**
68+
* Computes the SHA-256 hash of the provided string and returns it as a hexadecimal string.
69+
* @param s The string to be hashed.
70+
* @return The SHA-256 hash of the input string in hexadecimal format.
71+
*/
4672
public String sha256Hex(String s) {
4773
MessageDigest md = null;
4874
try {
@@ -54,17 +80,25 @@ public String sha256Hex(String s) {
5480
return DatatypeConverter.printHexBinary(d).toLowerCase();
5581
}
5682

83+
/**
84+
* Generates the HTTP headers required for making authenticated requests to the HunYuan API.
85+
* @param host The host address of the API endpoint.
86+
* @param action The action to be performed (e.g., "ChatCompletion").
87+
* @param service The service name associated with the request.
88+
* @param payload The request payload containing the necessary parameters.
89+
* @return A MultiValueMap containing the HTTP headers needed for the authenticated request.
90+
*/
5791
public MultiValueMap<String, String> getHttpHeadersConsumer(String host, String action, String service, HunYuanApi.ChatCompletionRequest payload){
5892
String version = HunYuanConstants.DEFAULT_VERSION;
5993
String algorithm = HunYuanConstants.DEFAULT_ALGORITHM;
6094
// String timestamp = "1551113065";
6195
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
6296
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
63-
// 注意时区,否则容易出错
97+
// Pay attention to the time zone, otherwise it will be easy to make mistakes
6498
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
6599
String date = sdf.format(new Date(Long.valueOf(timestamp + "000")));
66100

67-
// ************* 步骤 1:拼接规范请求串 *************
101+
// ************* Step 1: Splice specification request strings *************
68102
String httpRequestMethod = "POST";
69103
String canonicalUri = "/";
70104
String canonicalQueryString = "";
@@ -74,22 +108,19 @@ public MultiValueMap<String, String> getHttpHeadersConsumer(String host, String
74108

75109
// String payload = "{\"Limit\": 1, \"Filters\": [{\"Values\": [\"\\u672a\\u547d\\u540d\"], \"Name\": \"instance-name\"}]}";
76110
String payloadString = ModelOptionsUtils.toJsonString(payload);
77-
System.out.println(payloadString);
78111
String hashedRequestPayload = sha256Hex(payloadString);
79112
String canonicalRequest = httpRequestMethod + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n"
80113
+ canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestPayload;
81-
// ************* 步骤 2:拼接待签名字符串 *************
114+
// ************* Step 2: Splice the string to be signed *************
82115
String credentialScope = date + "/" + service + "/" + "tc3_request";
83116
String hashedCanonicalRequest = sha256Hex(canonicalRequest);
84117
String stringToSign = algorithm + "\n" + timestamp + "\n" + credentialScope + "\n" + hashedCanonicalRequest;
85-
System.out.println(stringToSign);
86-
// ************* 步骤 3:计算签名 *************
118+
// ************* Step 3: Calculate the signature *************
87119
byte[] secretDate = hmac256(("TC3" + secretKey).getBytes(UTF8), date);
88120
byte[] secretService = hmac256(secretDate, service);
89121
byte[] secretSigning = hmac256(secretService, "tc3_request");
90122
String signature = DatatypeConverter.printHexBinary(hmac256(secretSigning, stringToSign)).toLowerCase();
91-
System.out.println(signature);
92-
// ************* 步骤 4:拼接 Authorization *************
123+
// ************* Step 4: Splice Authorization *************
93124
String authorization = algorithm + " " + "Credential=" + secretId + "/" + credentialScope + ", "
94125
+ "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature;
95126

@@ -101,17 +132,18 @@ public MultiValueMap<String, String> getHttpHeadersConsumer(String host, String
101132
headers.put("X-TC-Timestamp", timestamp);
102133
headers.put("X-TC-Version", version);
103134

104-
StringBuilder sb = new StringBuilder();
105-
sb.append("curl -X POST https://").append(host)
106-
.append(" -H \"Authorization: ").append(authorization).append("\"")
107-
.append(" -H \"Content-Type: application/json; charset=utf-8\"")
108-
.append(" -H \"Host: ").append(host).append("\"")
109-
.append(" -H \"X-TC-Action: ").append(action).append("\"")
110-
.append(" -H \"X-TC-Timestamp: ").append(timestamp).append("\"")
111-
.append(" -H \"X-TC-Version: ").append(version).append("\"")
112-
.append(" -d '").append(payloadString).append("'");
113-
System.out.println(sb.toString());
114-
135+
if (logger.isDebugEnabled()){
136+
StringBuilder sb = new StringBuilder();
137+
sb.append("curl -X POST https://").append(host)
138+
.append(" -H \"Authorization: ").append(authorization).append("\"")
139+
.append(" -H \"Content-Type: application/json; charset=utf-8\"")
140+
.append(" -H \"Host: ").append(host).append("\"")
141+
.append(" -H \"X-TC-Action: ").append(action).append("\"")
142+
.append(" -H \"X-TC-Timestamp: ").append(timestamp).append("\"")
143+
.append(" -H \"X-TC-Version: ").append(version).append("\"")
144+
.append(" -d '").append(payloadString).append("'");
145+
logger.debug(sb.toString());
146+
}
115147
return CollectionUtils.toMultiValueMap(
116148
headers.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> List.of(e.getValue()))));
117149
}

0 commit comments

Comments
 (0)