AIFeed

使用 Google Generative AI 和 Quarkus 创建聊天机器人

Translation(model translation, not the source's own text)

使用 Google Generative AI 和 Quarkus 创建聊天机器人

我最近创建了一个 Quarkus 扩展,用于访问 Google Generative AI。在本文中,我将使用这个扩展来创建一个聊天机器人。

第一步是创建一个 Quarkus 项目,其中包含 REST 和 Google Cloud Gen AI 扩展。

以下是需要添加到依赖文件中的扩展:


        <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-rest</artifactId>
</dependency>
<dependency>
        <groupId>io.quarkiverse.googlecloudservices</groupId>
        <artifactId>quarkus-google-cloud-genai</artifactId>
</dependency>
      

或者更简单,这里有一个链接,可以让你从 code.quarkus.io 创建项目。

该扩展允许你将 Client 对象注入 Quarkus 应用程序,以访问 Google Cloud Generartive AI 服务。该服务让你可以在 Google Cloud 项目中使用 Gemini 生成式 AI 模型。

我们将在 REST 端点中使用这个扩展来构建一个聊天机器人。由于我不太热衷于开发 UI,我将使用 cURL 来调用这个聊天机器人。

以下是聊天机器人的起始代码:


        package fr.loicmathieu.google.genai;

// [...] imports omitted for brevity

// 1. Standard REST endpoint available on /chat
@Path("/chat")
public class GenAIResource {
    // 2. System message telling the LLM it is a chatbot
    private static final String SYSTEM_INSTRUCTION = """
        You are a chatbot named Loïc.
        Don't pretend you know everything,
        but be helpful with a touch of humour.""";

private GenerateContentConfig config;

// 3. Injection of the provided GenAI Client object
    @Inject
    Client client;

// 4. Init the configuration with the system instruction
    @PostConstruct
    void init() {
        var systemInstruction = Content.fromParts(Part.fromText(SYSTEM_INSTRUCTION));
        config = GenerateContentConfig.builder()
            .systemInstruction(systemInstruction).build();
    }

// 5. Generate a chat response on each call to /chat
    @GET
    public String chat(@QueryParam("prompt") String prompt) {
        return client.models
            .generateContent("gemini-3.8-flash", prompt, config).text() + "\n";
    }
}
      
  • 一个使用 JAX-RS 标准的 REST 端点,可通过应用程序中的 /chat 路径访问。
  • 系统消息,告知模型它是一个聊天机器人,并要求它以带点幽默的方式回应。
  • 注入 Client GenAI 服务,该服务由 Quarkus Google Cloud GenAI 扩展提供。
  • 在 REST 端点的 post-construct 方法中初始化配置。
  • 每次调用该端点时,我们都会调用模型并返回第一个生成的响应。真实世界的应用程序肯定会实现更高级的功能。这里,我们使用 Gemini Flash 3.8,因为 Gemini Flash 是一个兼顾性能与成本效益的模型;这正是我们想要的聊天机器人——它需要快速响应,且不需要过于复杂的推理。

要以开发模式启动应用程序,你可以使用 Quarkus CLI:quarkus dev;然后应用程序将在 8080 端口上可用。

为了调用聊天机器人,我使用以下 cURL 命令:curl -G localhost:8080/chat --data-urlencode "prompt=Tell me a joke"。对于不熟悉这一点的人,使用 -G 会强制 cURL 执行 GET 请求,然后它会将数据作为查询字符串传递到 URL 中。这通过使用 --data-urlencode 有助于避免空格带来的任何编码问题。

以下是一个对话示例:

Capture d’écran du 2026-11-13 15-42-22
Capture d’écran du 2026-11-13 15-42-22

如你所见,一切都很顺利,直到我问它我的名字是什么!尽管我刚告诉过它,但它不知道,因为它没有记忆。

我们将为聊天机器人添加记忆,以便能与它进行真正的对话;这是通过聊天会话实现的。


        package fr.loicmathieu.quarkus.vertexai;

// [...] Imports omitted for brevity

文章标题:使用 Google Generative AI 和 Quarkus 创建一个聊天机器人

正文:
// 1. 标准 REST 端点,可通过 /chat 访问
@Path("/chat")
public class GenAIResource {
    // 2. 系统消息,告诉 LLM 它是一个聊天机器人
    private static final String SYSTEM_INSTRUCTION = """
        You are a chatbot named Loïc.
        Don't pretend you know everything;
            but be helpful with a touch of humour.""";

private Chat chat;

// 3. 注入提供的 GenAI Client 对象
    @Inject
    Client client;

// 4. 使用系统指令和聊天会话初始化配置
    @PostConstruct
    void init() {
        var systemInstruction = Content.fromParts(Part.fromText(SYSTEM_INSTRUCTION));
        var config = GenerateContentConfig.builder().
            systemInstruction(systemInstruction).build();

chat = client.chats.create("gemini-3.8-flash", config);
    }

// 5. 每次调用 /chat 时生成聊天响应
    @GET
    public String chat(@QueryParam("prompt") String prompt) {
        return chat.sendMessage(prompt).text() + "\n";
    }
}
      

有了记忆,聊天机器人工作得好多了!

2026-11-13 15-46-20 的屏幕截图
2026-11-13 15-46-20 的屏幕截图

在这里,我为整个应用程序使用了一个聊天会话,存储在内存(RAM)中。在真实场景中,你当然需要为每个用户使用一个聊天会话,最好持久化存储。

今天就到这里;我们学习了如何使用 Google Generative AI 和 Gemini 模型在 Quarkus 中创建一个聊天机器人。Google GenAI 支持许多其他功能:RAG、多模态补全、工具等等。你可以在其文档中找到更多信息。

你可以在 GitHub 上找到项目代码:quarkus-gen-ai。

感谢 Google 提供 Google Cloud 额度来撰写本文。

分享:

  • 分享到 LinkedIn(在新窗口中打开)LinkedIn
  • 分享到 Bluesky(在新窗口中打开)Bluesky
  • 分享到 Mastodon(在新窗口中打开)Mastodon
  • 通过电子邮件将链接发送给朋友(在新窗口中打开)电子邮件
  • 分享到 Reddit(在新窗口中打开)Reddit
  • 分享到 X(在新窗口中打开)X
  • 分享到 Facebook(在新窗口中打开)Facebook
  • 分享到 Tumblr(在新窗口中打开)Tumblr
  • 分享到 Pinterest(在新窗口中打开)Pinterest
  • 分享到 WhatsApp(在新窗口中打开)WhatsApp
  • 分享到 Telegram(在新窗口中打开)Telegram
  • 打印(在新窗口中打开)打印
  • 分享到 Threads(在新窗口中打开)Threads
  • 分享到 Nextdoor(在新窗口中打开)Nextdoor

喜欢这个:

类似文章

The translation is machine-generated and individual terms may be off. Nothing is rewritten or cut; the original is authoritative.

Published by HN AI
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗