-
Notifications
You must be signed in to change notification settings - Fork 176
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #328 from erasernoob/main
fixes #253, add the googletranslate function-calling
- Loading branch information
Showing
6 changed files
with
274 additions
and
0 deletions.
There are no files selected for viewing
63 changes: 63 additions & 0 deletions
63
...unity/function-calling/spring-ai-alibaba-starter-function-calling-googletranslate/pom.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
|
||
<!-- | ||
Copyright 2024-2025 the original author or authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
https://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
--> | ||
|
||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | ||
<modelVersion>4.0.0</modelVersion> | ||
<parent> | ||
<groupId>com.alibaba.cloud.ai</groupId> | ||
<artifactId>spring-ai-alibaba</artifactId> | ||
<version>${revision}</version> | ||
<relativePath>../../../pom.xml</relativePath> | ||
</parent> | ||
|
||
<artifactId>spring-ai-alibaba-starter-function-calling-googletranslate</artifactId> | ||
<name>spring-ai-alibaba-starter-function-calling-googletranslate</name> | ||
<description>Translate tool for Spring AI Alibaba</description> | ||
<url>https://github.com/alibaba/spring-ai-alibaba</url> | ||
|
||
<dependencies> | ||
|
||
<dependency> | ||
<groupId>org.springframework.ai</groupId> | ||
<artifactId>spring-ai-spring-boot-autoconfigure</artifactId> | ||
</dependency> | ||
|
||
<dependency> | ||
<groupId>org.springframework.boot</groupId> | ||
<artifactId>spring-boot-configuration-processor</artifactId> | ||
<optional>true</optional> | ||
</dependency> | ||
|
||
<dependency> | ||
<groupId>org.springframework.boot</groupId> | ||
<artifactId>spring-boot-starter-webflux</artifactId> | ||
</dependency> | ||
|
||
<dependency> | ||
<groupId>com.fasterxml.jackson.core</groupId> | ||
<artifactId>jackson-annotations</artifactId> | ||
</dependency> | ||
|
||
</dependencies> | ||
|
||
|
||
<build> | ||
<finalName>spring-ai-alibaba-function-calling-googletranslate</finalName> | ||
</build> | ||
</project> |
42 changes: 42 additions & 0 deletions
42
...om/alibaba/cloud/ai/functioncalling/googletranslate/GoogleTranslateAutoConfiguration.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/* | ||
* Copyright 2024-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package com.alibaba.cloud.ai.functioncalling.googletranslate; | ||
|
||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; | ||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; | ||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; | ||
import org.springframework.boot.context.properties.EnableConfigurationProperties; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.context.annotation.Description; | ||
|
||
/** | ||
* @author erasernoob | ||
*/ | ||
@ConditionalOnClass({ GoogleTranslateService.class }) | ||
@EnableConfigurationProperties(GoogleTranslateProperties.class) | ||
@ConditionalOnProperty(prefix = "spring.ai.alibaba.functioncalling.googletranslate", name = "enabled", | ||
havingValue = "true") | ||
public class GoogleTranslateAutoConfiguration { | ||
|
||
@Bean | ||
@ConditionalOnMissingBean | ||
@Description("Implement natural language translation capabilities.") | ||
public GoogleTranslateService googleTranslateFunction(GoogleTranslateProperties properties) { | ||
return new GoogleTranslateService(properties); | ||
} | ||
|
||
} |
36 changes: 36 additions & 0 deletions
36
.../java/com/alibaba/cloud/ai/functioncalling/googletranslate/GoogleTranslateProperties.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
/* | ||
* Copyright 2024-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package com.alibaba.cloud.ai.functioncalling.googletranslate; | ||
|
||
import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
||
/** | ||
* @author erasernoob | ||
*/ | ||
@ConfigurationProperties(prefix = "spring.ai.alibaba.plugin.googletranslate") | ||
public class GoogleTranslateProperties { | ||
|
||
private String apiKey; | ||
|
||
public String getApiKey() { | ||
return apiKey; | ||
} | ||
|
||
public void setApiKey(String apiKey) { | ||
this.apiKey = apiKey; | ||
} | ||
|
||
} |
131 changes: 131 additions & 0 deletions
131
...ain/java/com/alibaba/cloud/ai/functioncalling/googletranslate/GoogleTranslateService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/* | ||
* Copyright 2024-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package com.alibaba.cloud.ai.functioncalling.googletranslate; | ||
|
||
import com.fasterxml.jackson.annotation.JsonClassDescription; | ||
import com.fasterxml.jackson.annotation.JsonProperty; | ||
import com.fasterxml.jackson.annotation.JsonPropertyDescription; | ||
import com.fasterxml.jackson.core.JsonProcessingException; | ||
import com.fasterxml.jackson.databind.JsonMappingException; | ||
import com.fasterxml.jackson.databind.JsonNode; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.fasterxml.jackson.databind.node.ObjectNode; | ||
import com.google.gson.Gson; | ||
import com.google.gson.reflect.TypeToken; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.util.StringUtils; | ||
import org.springframework.web.reactive.function.client.WebClient; | ||
import org.springframework.web.util.UriComponentsBuilder; | ||
import reactor.core.publisher.Mono; | ||
|
||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.function.Function; | ||
|
||
/** | ||
* @author erasernoob | ||
*/ | ||
public class GoogleTranslateService | ||
implements Function<GoogleTranslateService.Request, GoogleTranslateService.Response> { | ||
|
||
private static final Logger log = LoggerFactory.getLogger(GoogleTranslateService.class); | ||
|
||
private static final String TRANSLATE_HOST = "https://translation.googleapis.com"; | ||
|
||
private static final String TRANSLATE_PATH = "/language/translate/v2"; | ||
|
||
private final GoogleTranslateProperties properties; | ||
|
||
private final WebClient webClient; | ||
|
||
public GoogleTranslateService(GoogleTranslateProperties properties) { | ||
assert StringUtils.hasText(properties.getApiKey()); | ||
this.properties = properties; | ||
this.webClient = WebClient.builder().defaultHeader("Content-Type", "application/json").build(); | ||
} | ||
|
||
@Override | ||
public Response apply(Request request) { | ||
if (request == null || request.text == null || request.text.isEmpty() | ||
|| !StringUtils.hasText(properties.getApiKey()) || !StringUtils.hasText(request.targetLanguage)) { | ||
return null; | ||
} | ||
|
||
String requestUrl = UriComponentsBuilder.fromHttpUrl(TRANSLATE_HOST + TRANSLATE_PATH) | ||
.queryParam("key", properties.getApiKey()) | ||
.queryParam("target", request.targetLanguage) | ||
.queryParam("q", request.text) | ||
.queryParam("format", "text") | ||
.toUriString(); | ||
try { | ||
Mono<String> responseMono = webClient.post().uri(requestUrl).retrieve().bodyToMono(String.class); | ||
|
||
String responseData = responseMono.block(); | ||
assert responseData != null; | ||
log.info("GoogleTranslation request: {}, response: {}", request.text, responseData); | ||
return parseResponseData(responseData, request.text); | ||
} | ||
catch (Exception e) { | ||
log.error("Using the googleTranslate service failed due to {}", e.getMessage()); | ||
} | ||
return null; | ||
} | ||
|
||
private Response parseResponseData(String responseData, List<String> query) { | ||
ObjectMapper mapper = new ObjectMapper(); | ||
Map<String, String> translationResult = new HashMap<>(); | ||
try { | ||
JsonNode rootNode = mapper.readTree(responseData); | ||
JsonNode data = rootNode.path("data"); | ||
if (data == null || data.isNull()) { | ||
translateFailed(rootNode); | ||
return null; | ||
} | ||
JsonNode translations = data.path("translations"); | ||
assert translations != null; | ||
assert query.size() == translations.size(); | ||
for (int i = 0; i < translations.size(); i++) { | ||
translationResult.put(query.get(i), translations.get(i).asText()); | ||
} | ||
return new Response(translationResult); | ||
} | ||
catch (Exception e) { | ||
log.error("failed to convert the response to json object due to {}", e.getMessage()); | ||
return null; | ||
} | ||
} | ||
|
||
private void translateFailed(JsonNode rootNode) { | ||
String errorMessage = rootNode.path("error").path("message").asText(); | ||
String code = rootNode.path("error").path("code").asText(); | ||
log.info("Translate Text Failed. message:{} code:{}", errorMessage, code); | ||
} | ||
|
||
public record Request( | ||
@JsonProperty(required = true, | ||
value = "text") @JsonPropertyDescription("Content that needs to be translated") List<String> text, | ||
@JsonProperty(required = true, | ||
value = "targetLanguage") @JsonPropertyDescription("the target language to translate into") String targetLanguage) { | ||
} | ||
|
||
@JsonClassDescription("Response to translate text to the target language") | ||
public record Response(Map<String, String> translatedTexts) { | ||
} | ||
|
||
} |
1 change: 1 addition & 0 deletions
1
...esources/META-INF.spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
com.alibaba.cloud.ai.functioncalling.translate.GoogleTranslateAutoConfiguration |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters