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 github toolkit plugin #218

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 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,66 @@
<?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-github</artifactId>
<name>spring-ai-alibaba-starter-plugin-github</name>
<description>github toolkit 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>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

</dependencies>

<build>
<finalName>spring-ai-alibaba-starter-plugin-github</finalName>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* 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.github;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@JsonClassDescription("Create a pull request operation")
public class CreatePullRequestService implements Function<Request, Response> {

private static final String GITHUB_API_URL = "https://api.github.com";

private static final String REPO_ENDPOINT = "/repos/{owner}/{repo}";

protected static final String PULL_REQUESTS_ENDPOINT = "/pulls";

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

private static final ObjectMapper objectMapper = new ObjectMapper();

private final WebClient webClient;

private final GithubProperties properties;

public CreatePullRequestService(GithubProperties properties) {
assert properties.getToken() != null && properties.getToken().length() == 40;
this.properties = properties;
this.webClient = WebClient.builder()
.defaultHeader(HttpHeaders.USER_AGENT, HttpHeaders.USER_AGENT)
.defaultHeader(HttpHeaders.ACCEPT, "application/vnd.github.v3+json")
.defaultHeader("X-GitHub-Api-Version", GithubProperties.X_GitHub_Api_Version)
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + properties.getToken())
.build();
}

@Override
public Response apply(Request request) {
try {
String url = GITHUB_API_URL + REPO_ENDPOINT + PULL_REQUESTS_ENDPOINT;
Map<String, Object> body = new HashMap<>();
addIfNotNull(body, "title", request.pullRequestTitle());
addIfNotNull(body, "body", request.pullRequestBody());
addIfNotNull(body, "head", request.pullRequestHead());
addIfNotNull(body, "base", request.pullRequestBase());
addIfNotNull(body, "head_repo", request.headRepo());
addIfNotNull(body, "issue", request.issue());
addIfNotNull(body, "draft", request.draft());

Mono<String> responseMono = webClient.post()
.uri(url, properties.getOwner(), properties.getRepository())
.bodyValue(body)
.retrieve()
.bodyToMono(String.class);
String responseData = responseMono.block();
logger.info("Pull request created successfully.");
return new Response<>(parsePullRequest(responseData));
}
catch (WebClientResponseException e) {
logger.error("GitHub API error: Status {} - {}", e.getStatusCode(), e.getResponseBodyAsString());
throw new RuntimeException("GitHub API error", e);
}
catch (IOException e) {
logger.error("Error parsing pull request data: {}", e.getMessage());
throw new RuntimeException("Error parsing response", e);
}
catch (Exception e) {
logger.error("Unexpected error: {}", e.getMessage());
throw new RuntimeException("Unexpected error", e);
}
}

private void addIfNotNull(Map<String, Object> map, String key, Object value) {
if (value != null) {
map.put(key, value);
}
}

public static PullRequest parsePullRequest(String json) throws IOException {
JsonNode pullRequestNode = objectMapper.readTree(json);

long id = pullRequestNode.get("id").asLong();
String title = pullRequestNode.get("title").asText();
String state = pullRequestNode.get("state").asText();
int prNumber = pullRequestNode.get("number").asInt();
String userLogin = pullRequestNode.get("user").get("login").asText();
String body = pullRequestNode.get("body").asText();
String htmlUrl = pullRequestNode.get("html_url").asText();
String headRef = pullRequestNode.get("head").get("ref").asText();
String baseRef = pullRequestNode.get("base").get("ref").asText();

PullRequest pullRequest = new PullRequest(id, title, state, prNumber, userLogin, body, htmlUrl, headRef,
baseRef);

return pullRequest;
}

public record PullRequest(long id, String title, String state, Integer prNumber, String userLogin, String body,
String htmlUrl,

String headRef,

String baseRef) {
}

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

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

@JsonClassDescription("Get issue operation")
public class GetIssueService implements Function<Request, Response> {

private static final String GITHUB_API_URL = "https://api.github.com";

private static final String REPO_ENDPOINT = "/repos/{owner}/{repo}";

private static final String ISSUES_ENDPOINT = "/issues";

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

private static final ObjectMapper objectMapper = new ObjectMapper();

private final WebClient webClient;

private final GithubProperties properties;

public GetIssueService(GithubProperties properties) {
assert properties.getToken() != null && properties.getToken().length() == 40;
this.properties = properties;
this.webClient = WebClient.builder()
.defaultHeader(HttpHeaders.USER_AGENT, HttpHeaders.USER_AGENT)
.defaultHeader(HttpHeaders.ACCEPT, "application/vnd.github.v3+json")
.defaultHeader("X-GitHub-Api-Version", GithubProperties.X_GitHub_Api_Version)
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + properties.getToken())
.build();
}

@Override
public Response apply(Request request) {
try {
String url = GITHUB_API_URL + REPO_ENDPOINT + ISSUES_ENDPOINT + "/{issueNumber}";
Mono<String> responseMono = webClient.get()
.uri(url, properties.getOwner(), properties.getRepository(), request.issueNumber())
.retrieve()
.bodyToMono(String.class);
String responseData = responseMono.block();
logger.info("GetIssueOperation response: {}", responseData);
return new Response<>(parseIssueDetails(responseData));
}
catch (IOException e) {
logger.error("Error occurred while parsing response: {}", e.getMessage());
throw new RuntimeException(e);
}

}

public static Issue parseIssueDetails(String json) throws IOException {
JsonNode issueNode = objectMapper.readTree(json);

long id = issueNode.get("id").asLong();
String title = issueNode.get("title").asText();
String state = issueNode.get("state").asText();
String userLogin = issueNode.get("user").get("login").asText();

JsonNode labelsNode = issueNode.get("labels");
List<String> labels = new ArrayList<>();
if (labelsNode != null && labelsNode.isArray()) {
for (JsonNode labelNode : labelsNode) {
String name = labelNode.get("name").asText();
labels.add(name);
}
}
JsonNode assigneesNode = issueNode.get("assignees");
List<String> assignees = new ArrayList<>();
if (assigneesNode != null && assigneesNode.isArray()) {
for (JsonNode assigneeNode : assigneesNode) {
String assigneeLogin = assigneeNode.get("login").asText();
assignees.add(assigneeLogin);
}
}
String createdAt = issueNode.get("created_at").asText();
String updatedAt = issueNode.get("updated_at").asText();
String closedAt = issueNode.has("closed_at") && !issueNode.get("closed_at").isNull()
? issueNode.get("closed_at").asText() : null;
String closedBy = issueNode.has("closed_by") && !issueNode.get("closed_by").isNull()
? issueNode.get("closed_by").get("login").asText() : null;
int comments = issueNode.get("comments").asInt();
String htmlUrl = issueNode.get("html_url").asText();
String body = issueNode.has("body") && !issueNode.get("body").isNull() ? issueNode.get("body").asText() : null;
return new Issue(id, title, body, state, userLogin, labels, assignees, createdAt, updatedAt, closedAt, closedBy,
comments, htmlUrl);
}

public record Issue(long id, String title, String body, String state, String userLogin, List<String> labels,
List<String> assignees, String createdAt, String updatedAt, String closedAt, String closedBy, int comments,
String htmlUrl

) {
}

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

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.Description;

/**
* @author Yeaury
*/
@EnableConfigurationProperties(GithubProperties.class)
public class GithubAutoConfiguration {

@Bean
@ConditionalOnMissingBean
@Description("implement the function of get a GitHub issue operation")
public GetIssueService getIssueService(GithubProperties properties) {
return new GetIssueService(properties);
}

@Bean
@ConditionalOnMissingBean
@Description("implement the function of create GitHub pull request operation")
public CreatePullRequestService createPullRequestService(GithubProperties properties) {
return new CreatePullRequestService(properties);
}

@Bean
@ConditionalOnMissingBean
@Description("implement the function of search the list of repositories operation")
public SearchRepositoryService SearchRepositoryService(GithubProperties properties) {
return new SearchRepositoryService(properties);
}

}
Loading
Loading