跳到主内容
@wquguru
精选75GitHub 博客(RSS)技巧与观点

GitHub Copilot SDK for Java:框架无关的 Java

Using the GitHub Copilot SDK for Java

原文
发到 X

Java developers no longer have to rely on Java framework-specific approaches to drive AI from their enterprise apps.

Java 开发者不再需要依赖特定于 Java 框架的方法来从企业应用中驱动 AI。

While it is true that Langchain4j empowered developers by disintermediating specific AI vendors, you still had a dependency on Langchain4j. And with Spring AI, well, of course you had a dependency on design choices made by Spring, if not on Spring itself.

诚然,Langchain4j 通过去中介化特定的 AI 供应商,赋予了开发者能力,但你仍然依赖于 Langchain4j。而对于 Spring AI,当然,你依赖于 Spring 的设计选择,如果不是依赖于 Spring 本身的话。

Now, GitHub Copilot SDK for Java is the first truly framework agnostic way to drive AI from Java. And with its BYOK support, GitHub Copilot SDK for Java is also AI vendor neutral.

现在,GitHub Copilot SDK for Java 是第一个真正与框架无关的从 Java 驱动 AI 的方式。并且凭借其 BYOK 支持,GitHub Copilot SDK for Java 也是 AI 供应商中立的。

💡 Even though it’s called GitHub Copilot SDK, you can use it with any direct model provider, such as OpenAI, Azure, Anthropic, or OpenAI-compatible endpoints, by passing a provider/ProviderConfig with your own baseUrl + apiKey (or bearer token). No Copilot subscription required.

💡 尽管它被称为 GitHub Copilot SDK,你可以将其与任何直接模型提供商(如 OpenAI、Azure、Anthropic 或兼容 OpenAI 的端点)一起使用,只需传递带有你自己的 baseUrl 和 apiKey(或 bearer token)的 provider/ProviderConfig。无需 Copilot 订阅。

The GitHub Copilot SDK for Java is a client library that empowers your server-side Java code to create Copilot agent sessions, register tools, send prompts, and receive structured responses—all programmatically. It works in server environments, including Jakarta EE and Spring. If you’ve been building enterprise Java for any length of time, this SDK will feel like home: CompletableFuture, annotations, lambdas, virtual threads, it’s all here.

GitHub Copilot SDK for Java 是一个客户端库,它使你的服务器端 Java 代码能够以编程方式创建 Copilot 代理会话、注册工具、发送提示并接收结构化响应。它适用于服务器环境,包括 Jakarta EE 和 Spring。如果你一直在构建企业级 Java 应用,这个 SDK 会让你感到熟悉:CompletableFuture、注解、lambda、虚拟线程,一应俱全。

This post shows you how to use the SDK, walks through a complete Jakarta EE 11 sample application, and leaves you with concrete next steps to try it yourself. I chose Jakarta EE 11 for my demo because I was the lead release coordinator for that release. I believe in open standards as the best way to empower developers. For more on Jakarta EE 11 see this InfoQ article.

这篇文章展示了如何使用该 SDK,逐步讲解一个完整的 Jakarta EE 11 示例应用,并为你提供具体的后续步骤,以便你自己尝试。我选择 Jakarta EE 11 作为演示,因为我是该版本的首席发布协调员。我相信开放标准是赋能开发者的最佳方式。有关 Jakarta EE 11 的更多信息,请参阅这篇 InfoQ 文章。

This sample app is an agent harness using Jakarta EE 11. But, of course, developers can build their own agent harness using the well-known Java frameworks and libraries of their choice.

这个示例应用是一个使用 Jakarta EE 11 的代理框架。当然,开发者可以使用他们熟悉的 Java 框架和库来构建自己的代理框架。

Clone the sample app and try it yourself >

克隆示例应用并亲自尝试 >

Where to get it

获取方式

The SDK is available as a Maven dependency:

该 SDK 可作为 Maven 依赖项使用:

代码 · 5 行
<dependency>
    <groupId>com.github</groupId>
    <artifactId>copilot-sdk-java</artifactId>
    <version>1.0.7-preview.1</version>
</dependency>

Prerequisites:

前提条件:

  • JDK 17 or 25 (25 recommended — unlocks virtual threads and other modern features)
  • Maven 3.9+
  • A GitHub account with an active Copilot subscription
  • The Copilot CLI installed locally at version 1.0.71 or later.
  • JDK 17 或 25(推荐 25——解锁虚拟线程和其他现代特性)
  • Maven 3.9+
  • 具有有效 Copilot 订阅的 GitHub 账户
  • 本地安装的 Copilot CLI 版本 1.0.71 或更高。

Walk through the sample app

逐步了解示例应用

The best way to see the SDK in action is to run this sample application.

查看 SDK 实际运行的最佳方式是运行此示例应用。

Get the code

获取代码

代码 · 4 行
git clone https://github.com/microsoft/Build26-BRK206-your-agent-anywhere-multiclient-multidevice-with-github-copilot-sdk.git
cd Build26-BRK206-your-agent-anywhere-multiclient-multidevice-with-github-copilot-sdk/src/java-agent-orchestrator
mvn clean package liberty:run
# Open http://localhost:9080/index.xhtml

The Java demo is built on:

Java 演示基于:

ConcernTechnology
RuntimeOpen Liberty 26.0.0.5
PlatformJakarta EE 11 (Faces 4.1, CDI 4.1, WebSocket 2.2, Data 1.0, Persistence 3.2)
UIPrimeFaces 15.0.16
AI orchestrationCopilot SDK for Java 1.0.7-preview.1
DatabaseH2 in-memory (10 seed property listings)
关注点技术
运行时Open Liberty 26.0.0.5
平台Jakarta EE 11 (Faces 4.1, CDI 4.1, WebSocket 2.2, Data 1.0, Persistence 3.2)
UIPrimeFaces 15.0.16
AI 编排Copilot SDK for Java 1.0.7-preview.1
数据库H2 内存数据库(10 条种子房产列表)

What the app does

应用功能

The application is a real-estate lead-management agent pipeline. A customer submits an enquiry (“I’m looking for a 3-bedroom house in London under £800,000”), and the system spins up an isolated Copilot Agent on a virtual thread to process it through a pipeline:

该应用是一个房地产线索管理代理管道。客户提交咨询(“我在伦敦寻找一套三居室、价格低于 80 万英镑的房子”),系统会在虚拟线程上启动一个隔离的 Copilot 代理,通过管道处理该咨询:

The architecture uses Jakarta WebSocket to push real-time status updates from the server to the browser, so you can watch agents progress through phases as the model calls tools:

架构使用 Jakarta WebSocket 将实时状态更新从服务器推送到浏览器,因此您可以观察代理在模型调用工具时逐步推进各个阶段:

Submit multiple inquiries simultaneously to see concurrent virtual-thread agents in action. Each one processes independently with its own Copilot session.

同时提交多个咨询,以查看并发虚拟线程代理的运行情况。每个代理都独立处理,拥有自己的 Copilot 会话。

SDK features in action

SDK 功能演示

Let’s walk through the key SDK features as they appear in the sample code.

让我们逐一介绍示例代码中出现的 SDK 关键功能。

Defining tools with @CopilotTool

使用 @CopilotTool 定义工具

This is the headline API. If you’ve ever written a @GET endpoint in JAX-RS or an @MessageDriven bean, this will feel instantly familiar:

这是核心 API。如果您曾经在 JAX-RS 中编写过 @GET 端点或 @MessageDriven bean,您会立刻感到熟悉:

代码 · 10 行
@CopilotTool(value = "Sets the current phase of the agent. Use this to report progress.",
             name = "set_current_phase")
public String setCurrentPhase(
        @CopilotToolParam("The phase to transition to (VALIDATING, SEARCHING, "
                + "WRITING_REPORT, REJECTED_GARBAGE, REJECTED_NO_MATCHES, or DONE)")
        String phaseName) {
    phase = Phase.valueOf(phaseName.trim().toUpperCase(Locale.ROOT));
    notifyUi();
    return "Phase set to " + phase.getLabel();
}

The @CopilotTool annotation declares the method as a tool the model can call. The @CopilotToolParam annotation describes each parameter so the model knows what to pass. The SDK handles all the JSON Schema generation, argument parsing, and dispatch. You just write a normal Java method.

@CopilotTool 注解将方法声明为模型可调用的工具。@CopilotToolParam 注解描述每个参数,以便模型知道要传递什么。SDK 处理所有 JSON Schema 生成、参数解析和调度。您只需编写一个普通的 Java 方法。

Two build prerequisites for @CopilotTool. The annotation-based tool API is currently an experimental feature of the SDK, so you need to configure two things in your Maven build:

@CopilotTool 的两个构建前提。基于注解的工具 API 目前是 SDK 的实验性功能,因此您需要在 Maven 构建中配置两项内容:

  • Enable experimental APIs: pass -Acopilot.experimental.allowed=true to the compiler. Without this flag, the annotation processor will refuse to generate the tool metadata. For more details on the experimental APIs see Copilot SDK documentation.
  • Register the annotation processor: add the SDK as an annotationProcessorPath so the compiler can find the @CopilotTool processor and generate the $$CopilotToolMeta classes at compile time.
  • 启用实验性 API:向编译器传递 -Acopilot.experimental.allowed=true。如果没有此标志,注解处理器将拒绝生成工具元数据。有关实验性 API 的更多详细信息,请参阅 Copilot SDK 文档。
  • 注册注解处理器:将 SDK 添加为 annotationProcessorPath,以便编译器能够找到 @CopilotTool 处理器并在编译时生成 $$CopilotToolMeta 类。

Both are configured in the maven-compiler-plugin:

两者都在 maven-compiler-plugin 中配置:

代码 · 17 行
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.15.0</version>
    <configuration>
        <compilerArgs>
            <arg>-Acopilot.experimental.allowed=true</arg>
        </compilerArgs>
        <annotationProcessorPaths>
            <path>
                <groupId>com.github</groupId>
                <artifactId>copilot-sdk-java</artifactId>
                <version>1.0.7-preview.1</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

To register all annotated tools from an object:

要注册对象中的所有注解工具:

代码 · 1 行
List<ToolDefinition> annotatedTools = ToolDefinition.fromObject(this);

Inline lambda tools with ToolDefinition.from(...)

使用 ToolDefinition.from(...) 的内联 Lambda 工具

When you want a tool defined at the call site without a dedicated method, use the lambda style:

当您希望在调用点定义工具而不使用专门的方法时,可以使用 Lambda 风格:

代码 · 11 行
ToolDefinition reportIntentTool = ToolDefinition
        .from("report_intent",
              "Reports the current intent of the agent",
              Param.of(String.class, "intent", "Intent in max 4 words"),
              (String intent) -> {
                  currentIntent = intent;
                  addEvent(Instant.now(), "intent", "Intent updated", intent);
                  notifyUi();
                  return "ok";
              })
        .overridesBuiltInTool(true);

Notice .overridesBuiltInTool(true). This tells the SDK that our report_intent tool deliberately replaces a built-in tool of the same name. This is useful when you need custom behaviour for a tool the model already knows about.

注意 .overridesBuiltInTool(true)。这告诉 SDK,我们的 report_intent 工具故意替换了同名内置工具。当你需要对模型已知的工具进行自定义行为时,这很有用。

Cross-class tool scanning

跨类工具扫描

Tools don’t have to live in the same class as your agent logic. Here’s searchProperties defined in a separate CDI bean:

工具不必与你的代理逻辑位于同一个类中。这里是在单独的 CDI bean 中定义的 searchProperties:

代码 · 13 行
@ApplicationScoped
public class PropertyDatabase {
    @CopilotTool(value = "Searches the real estate listings database. "
                       + "Returns up to 10 matching properties.",
                 name = "search_properties")
    public List<Property> searchProperties(
            @CopilotToolParam("Property type substring (e.g. 'flat', 'house')") String type,
            @CopilotToolParam("City substring (e.g. 'London', 'Bristol')") String city,
            @CopilotToolParam("Minimum number of bedrooms (0 for no minimum)") int minBedrooms,
            @CopilotToolParam("Maximum price in GBP (0 for no maximum)") double maxPriceGbp) {
        // ... filter and return matching properties ...
    }
}

更进一步:量化金融体系

看懂新闻只是起点——沿量化金融路径,把它变成能交付的工程能力

进入量化体系 →

相似阅读

关联信息,但可能不是同一事件