Skip to content

Commit

Permalink
feat: Migrate baiduMap plugin to the function calling directory and i…
Browse files Browse the repository at this point in the history
…mplement regional surrounding information retrieval
  • Loading branch information
CoderSerio committed Dec 22, 2024
1 parent ad8d86f commit 81fec15
Show file tree
Hide file tree
Showing 6 changed files with 365 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?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 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-baidumap</artifactId>
<name>spring-ai-alibaba-starter-function-calling-baidumap</name>
<description>Bai Du Map tool for Spring AI Alibaba</description>

<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>

<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>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>

</dependencies>

<build>
<finalName>spring-ai-alibaba-functioncalling-baidumap</finalName>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@

/*
* 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.functioncalling.baidumap;

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 Carbon
*/
@Configuration
@ConditionalOnClass(MapSearchService.class)
@EnableConfigurationProperties(BaiDuMapProperties.class)
@ConditionalOnProperty(prefix = "spring.ai.alibaba.functioncalling.baidumap", name = "enabled", havingValue = "true")
public class BaiDuMapConfiguration {

@Bean
@ConditionalOnMissingBean
@Description("Get detail information of a address and facility query with baidu map.")
public MapSearchService baiDuMapGetAddressInformationFunction(BaiDuMapProperties baiDuMapProperties) {
return new MapSearchService(baiDuMapProperties);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* 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.functioncalling.baidumap;

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

/**
* @author Carbon
*/
@ConfigurationProperties(prefix = "spring.ai.alibaba.functioncalling.baidumap")
public class BaiDuMapProperties {

// Official Document URL: https://lbs.baidu.com/faq/api?title=webapi/ROS2/prepare
private String webApiKey;

public BaiDuMapProperties(String webApiKey) {
this.webApiKey = webApiKey;
}

public String getWebApiKey() {
return webApiKey;
}

public void setWebApiKey(String webApiKey) {
this.webApiKey = webApiKey;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* 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.functioncalling.baidumap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;

import java.util.function.Function;

/**
* @author Carbon
*/
public class MapSearchService implements Function<MapSearchService.Request, MapSearchService.Response> {

private final MapTools mapTools;

public MapSearchService(BaiDuMapProperties baiDuMapProperties) {
this.mapTools = new MapTools(baiDuMapProperties);
}

@Override
public Response apply(Request request) {
try {
JSONObject jsonObject = new JSONObject();

String addressCityCodeResponse = mapTools.getAddressCityCode(request.address);
JSONObject cityCodeJson = JSON.parseObject(addressCityCodeResponse);
JSONArray districtsArray = cityCodeJson.getJSONArray("districts");

if (districtsArray != null && !districtsArray.isEmpty()) {
for (int i = 0; i < districtsArray.size(); i++) {
JSONObject district = districtsArray.getJSONObject(i);
String adcode = district.getString("adcode");

if (adcode != null && !adcode.isEmpty()) {
String weather = mapTools.getWeather(adcode);
jsonObject.put("weather", weather);
}
}

String facilityInformationJson = mapTools.getFacilityInformation(request.address, request.facilityType);
JSONArray facilityResults = JSON.parseObject(facilityInformationJson).getJSONArray("results");
if (facilityResults != null) {
jsonObject.put("facilityInformation", facilityResults.toJSONString());
}
else {
jsonObject.put("facilityInformation", "No facility information found.");
}
}
else {
return new Response("No districts found in the response.");
}

return new Response(jsonObject.toJSONString());
}
catch (Exception e) {
return new Response("Error occurred while processing the request: " + e.getMessage());
}
}

@JsonClassDescription("Get the weather conditions for a specified address and facility type.")
public record Request(
@JsonProperty(required = true, value = "address") @JsonPropertyDescription("The address") String address,

@JsonProperty(required = true,
value = "facilityType") @JsonPropertyDescription("The type of facility (e.g., bank, airport, restaurant)") String facilityType) {
}

public record Response(String message) {
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* 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.functioncalling.baidumap;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
* @author Carbon
*/
public class MapTools {

private final String baseUrl = "https://api.map.baidu.com";

private final BaiDuMapProperties baiDuMapProperties;

private final HttpClient httpClient;

public MapTools(BaiDuMapProperties baiDuMapProperties) {
this.baiDuMapProperties = baiDuMapProperties;

this.httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();

if (Objects.isNull(baiDuMapProperties.getWebApiKey())) {
throw new RuntimeException("Please configure your BaiDuMap API key in the application.yml file.");
}
}

/**
* Geographic/Inverse Geocoding
* @param address
* @return https://lbs.baidu.com/faq/api?title=webapi/district-search/base
*/
public String getAddressCityCode(String address) {

String path = String.format("/api_region_search/v1/?ak=%s&keyword=%s&sub_admin=0&extensions_code=1",
baiDuMapProperties.getWebApiKey(), address);

HttpRequest httpRequest = createGetRequest(path);

CompletableFuture<HttpResponse<String>> responseFuture = httpClient.sendAsync(httpRequest,
HttpResponse.BodyHandlers.ofString());

HttpResponse<String> response = responseFuture.join();

if (response.statusCode() != 200) {
throw new RuntimeException("Failed to get address city code");
}

return response.body();
}

/**
* Weather Information
* @param cityCode
* @return https://lbs.baidu.com/faq/api?title=webapi/weather/base
*/
public String getWeather(String cityCode) {
String path = String.format("/weather/v1/?ak=%s&district_id=%s&data_type=%s", baiDuMapProperties.getWebApiKey(),
cityCode, "all");

HttpRequest httpRequest = createGetRequest(path);

CompletableFuture<HttpResponse<String>> responseFuture = httpClient.sendAsync(httpRequest,
HttpResponse.BodyHandlers.ofString());

HttpResponse<String> response = responseFuture.join();

if (response.statusCode() != 200) {
throw new RuntimeException("Failed to get weather information");
}

return response.body();
}

/**
* Public Facility Information
* @param address
* @param facilityType
* @return https://lbsyun.baidu.com/faq/api?title=webapi/guide/webservice-placeapi/district
*/
public String getFacilityInformation(String address, String facilityType) {
String path = String.format("/place/v2/search?query=%s&region=%s&output=json&ak=%s", facilityType, address,
baiDuMapProperties.getWebApiKey());

HttpRequest httpRequest = createGetRequest(path);

CompletableFuture<HttpResponse<String>> responseFuture = httpClient.sendAsync(httpRequest,
HttpResponse.BodyHandlers.ofString());

HttpResponse<String> response = responseFuture.join();

if (response.statusCode() != 200) {
throw new RuntimeException("Failed to get facility information");
}

return response.body();
}

private HttpRequest createGetRequest(String path) {
URI uri = URI.create(baseUrl + path);

return HttpRequest.newBuilder().uri(uri).GET().build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
com.alibaba.cloud.ai.functioncalling.baidumap.BaiDuMapConfiguration

0 comments on commit 81fec15

Please sign in to comment.