Skip to content

Commit

Permalink
Merge pull request #144 from Yeaury/main
Browse files Browse the repository at this point in the history
Feat:add translate plugin
  • Loading branch information
chickenlj authored Dec 10, 2024
2 parents eabb4b8 + 831915a commit 10d4f7a
Show file tree
Hide file tree
Showing 9 changed files with 297 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>

<!--
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 https://maven.apache.org/xsd/maven-4.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-plugin-translate</artifactId>
<name>spring-ai-alibaba-starter-plugin-translate</name>
<description>Translate tool for Spring AI Alibaba</description>

<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.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>

</dependencies>


<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${maven-deploy-plugin.version}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>

<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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.plugin.translate;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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;

@Configuration
@ConditionalOnClass(TranslateService.class)
@EnableConfigurationProperties(TranslateProperties.class)
public class TranslateAutoConfiguration {

@Bean
@ConditionalOnMissingBean
@Description("Implement natural language translation capabilities") // function
public TranslateService translateService(TranslateProperties properties) {
return new TranslateService(properties);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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.plugin.translate;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "spring.ai.alibaba.plugin.translate")
public class TranslateProperties {

public static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key";

// translate api key for Ocp-Apim-Subscription-Key
// https://learn.microsoft.com/en-us/azure/ai-services/translator/reference/v3-0-translate
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,117 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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.plugin.translate;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
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;

public class TranslateService implements Function<TranslateService.Request, TranslateService.Response> {

private static final Logger logger = LoggerFactory.getLogger(TranslateService.class);

private static final String TRANSLATE_HOST_URL = "https://api.cognitive.microsofttranslator.com";

private static final String TRANSLATE_PATH = "/translate?api-version=3.0";

private final WebClient webClient;

public TranslateService(TranslateProperties properties) {
assert StringUtils.hasText(properties.getApiKey());
this.webClient = WebClient.builder()
.defaultHeader(TranslateProperties.OCP_APIM_SUBSCRIPTION_KEY, properties.getApiKey())
.defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
}

@Override
public Response apply(Request request) {
if (request == null || !StringUtils.hasText(request.text) || !StringUtils.hasText(request.targetLanguage)) {
return null;
}
String url = UriComponentsBuilder.fromHttpUrl(TRANSLATE_HOST_URL + TRANSLATE_PATH)
.queryParam("to", request.targetLanguage)
.toUriString();
try {
String body = constructRequestBody(request);
Mono<String> responseMono = webClient.post().uri(url).bodyValue(body).retrieve().bodyToMono(String.class);

String responseData = responseMono.block();
assert responseData != null;
logger.info("Translation request: {}, response: {}", request.text, responseData);

return parseResponse(responseData);
}
catch (Exception e) {
logger.error("Failed to invoke translate API due to: {}", e.getMessage());
return null;
}
}

private String constructRequestBody(Request request) {
return "[{\"Text\": \"" + request.text + "\"}]";
}

private Response parseResponse(String responseData) {
Gson gson = new Gson();
List<Map<String, Object>> responseList = gson.fromJson(responseData,
new TypeToken<List<Map<String, Object>>>() {
}.getType());
Map<String, String> translations = new HashMap<>();
for (Map<String, Object> item : responseList) {
if (item.containsKey("translations")) {
List<Map<String, Object>> translationsList = (List<Map<String, Object>>) item.get("translations");
for (Map<String, Object> translation : translationsList) {
String to = (String) translation.get("to");
String translatedText = (String) translation.get("text");
translations.put(to, translatedText);
logger.info("Translated text to {}: {}", to, translatedText);
}
}
}

return new Response(translations);
}

@JsonClassDescription("Request to translate text to a target language")
public record Request(
@JsonProperty(required = true,
value = "text") @JsonPropertyDescription("Content that needs to be translated") String text,
@JsonProperty(required = true,
value = "targetLanguage") @JsonPropertyDescription("Target language to translate into") String targetLanguage) {
}

@JsonClassDescription("Response to translate text to a 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.plugin.translate.TranslateAutoConfiguration
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<module>community/plugins/spring-ai-alibaba-starter-plugin-gaode</module>
<module>community/plugins/spring-ai-alibaba-starter-plugin-weather</module>
<module>community/plugins/spring-ai-alibaba-starter-plugin-larksuite</module>
<module>community/plugins/spring-ai-alibaba-starter-plugin-translate</module>
<module>community/document-readers/github-reader</module>
<module>community/document-readers/poi-document-reader</module>
<module>community/document-readers/tencent-cos-reader</module>
Expand Down
6 changes: 6 additions & 0 deletions spring-ai-alibaba-examples/function-calling-example/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@
<version>${spring-ai-alibaba.version}</version>
</dependency>

<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-plugin-translate</artifactId>
<version>${spring-ai-alibaba.version}</version>
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,13 @@ public String getWeather(@RequestParam String text) {
.content();
}

@GetMapping("/translate")
public String translate(@RequestParam String text) {
return chatClient.prompt()
.functions("translateService")
.user(text)
.call()
.content();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ spring:
web-api-key: ${GaoDe_Web_API_Key}
weather:
api-key: ${AI_WEATHER_API_KEY}
translate:
api-key: ${AI_TRANSLATE_API_KEY}

0 comments on commit 10d4f7a

Please sign in to comment.