Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat]: add the googletranslate function-calling #328

Merged
merged 6 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>

<!--
erasernoob marked this conversation as resolved.
Show resolved Hide resolved
Copyright 2023-2024 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>

erasernoob marked this conversation as resolved.
Show resolved Hide resolved
<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>
<scm>
erasernoob marked this conversation as resolved.
Show resolved Hide resolved
<url>https://github.com/alibaba/spring-ai-alibaba</url>
<connection>git://github.com/alibaba/spring-ai-alibaba.git</connection>
<developerConnection>[email protected]:alibaba/spring-ai-alibaba.git</developerConnection>
</scm>

<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>
<dependency>
erasernoob marked this conversation as resolved.
Show resolved Hide resolved
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

</dependencies>


<build>
<finalName>spring-ai-alibaba-plugin-googletranslate</finalName>
erasernoob marked this conversation as resolved.
Show resolved Hide resolved
</build>
</project>
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.googletranlate", name = "enabled",
erasernoob marked this conversation as resolved.
Show resolved Hide resolved
havingValue = "true")
public class GoogleTranslateAutoConfiguration {

@Bean
@ConditionalOnMissingBean
@Description("Implement natural language translation capabilities.")
public GoogleTranslateService googleTranslateFunction(GoogleTranslateProperties properties) {
return new GoogleTranslateService(properties);
}

}
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;
}

}
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) {
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
com.alibaba.cloud.ai.functioncalling.translate.GoogleTranslateAutoConfiguration
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
<module>community/function-calling/spring-ai-alibaba-starter-function-calling-sinanews</module>
<module>community/function-calling/spring-ai-alibaba-starter-function-calling-toutiaonews</module>
<module>community/function-calling/spring-ai-alibaba-starter-function-calling-yuque</module>
<module>community/function-calling/spring-ai-alibaba-starter-function-calling-googletranslate</module>

<module>community/document-readers/github-document-reader</module>
<module>community/document-readers/poi-document-reader</module>
Expand Down