成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

SpringAI正式版1.0發布!核心內容和智能體詳解

人工智能
Spring AI 1.0 的發布標志著企業級 Java 應用程序開發進入了一個新時代,使開發者能夠輕松地將最先進的 AI 能力集成到他們的 Spring 應用程序中。

在經歷了八個里程碑式的版本之后(M1~M8),Spring AI 1.0 正式版本,終于在 2025 年 5 月 20 日正式發布了,這是另一個新高度的里程碑式的版本,標志著 Spring 生態系統正式全面擁抱人工智能技術,并且意味著 Spring AI 將會給企業帶來穩定 API 支持。

1.核心特性

Spring AI 1.0 的核心是 ChatClient 接口,這是一個可移植且易于使用的 API,是與 AI 模型交互的主要接口。

它支持調用 20 多種 AI 模型,從 Anthropic 到 ZhiPu AI,并支持多模態輸入和輸出(當底層模型支持時)以及結構化響應(通常以 JSON 格式,便于應用程序處理輸出)。

1.1 單模型ChatClient使用

在項目中只有一個模型時,創建全局的 ChatClient:

@RestController
class MyController {

    privatefinal ChatClient chatClient;

    public MyController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @GetMapping("/ai")
    String generation(String userInput) {
        returnthis.chatClient.prompt()
            .user(userInput)
            .call()
            .content();
    }
}

1.2 多模型ChatClient使用

在項目中有多個模型時,為這一個模型創建全局的 ChatClient:

// Create ChatClient instances programmatically
ChatModel myChatModel = ... // already autoconfigured by Spring Boot
ChatClient chatClient = ChatClient.create(myChatModel);

// Or use the builder for more control
ChatClient.Builder builder = ChatClient.builder(myChatModel);
ChatClient customChatClient = builder
    .defaultSystemPrompt("You are a helpful assistant.")
    .build();

1.3 不同模型類型的ChatClients

當項目中有多個模型時,為每個模型定義單獨的 ChatClient:

import org.springframework.ai.chat.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
publicclass ChatClientConfig {

    @Bean
    public ChatClient openAiChatClient(OpenAiChatModel chatModel) {
        return ChatClient.create(chatModel);
    }

    @Bean
    public ChatClient anthropicChatClient(AnthropicChatModel chatModel) {
        return ChatClient.create(chatModel);
    }
}

然后,您可以使用 @Qualifier 指定大模型對應的 ChatClient:

@Configuration
publicclass ChatClientExample {

    @Bean
    CommandLineRunner cli(
            @Qualifier("openAiChatClient") ChatClient openAiChatClient,
            @Qualifier("anthropicChatClient") ChatClient anthropicChatClient) {

        return args -> {
            var scanner = new Scanner(System.in);
            ChatClient chat;

            // Model selection
            System.out.println("\nSelect your AI model:");
            System.out.println("1. OpenAI");
            System.out.println("2. Anthropic");
            System.out.print("Enter your choice (1 or 2): ");

            String choice = scanner.nextLine().trim();

            if (choice.equals("1")) {
                chat = openAiChatClient;
                System.out.println("Using OpenAI model");
            } else {
                chat = anthropicChatClient;
                System.out.println("Using Anthropic model");
            }

            // Use the selected chat client
            System.out.print("\nEnter your question: ");
            String input = scanner.nextLine();
            String response = chat.prompt(input).call().content();
            System.out.println("ASSISTANT: " + response);

            scanner.close();
        };
    }
}

2.主要功能亮點

  • 檢索增強生成(RAG):Spring AI 提供了便攜式向量存儲抽象,支持 20 種不同的向量數據庫,從 Azure Cosmos DB 到 Weaviate,像常見的 Cassandra、PostgreSQL/PGVector、MongoDB Atlas、Milvus、Pinecone 和 Redis 等向量數據庫存儲都是支持的。還包括一個輕量級、可配置的 ETL 框架,用于將數據導入向量存儲。
  • 對話記憶:通過 ChatMemory 接口管理消息的存儲和檢索,支持 JDBC、Cassandra 和 Neo4j 等持久化存儲。
  • 工具調用:通過 @Tool 注解可以輕松定義工具,讓 AI 模型能夠獲取外部信息或執行實際動作。
  • 評估與測試:提供 Evaluator 接口和內置的 RelevancyEvaluator、FactCheckingEvaluator,幫助開發者評估 AI 生成內容的準確性和相關性。
  • 可觀測性:與 Micrometer 集成,提供模型延遲、令牌使用情況等關鍵指標的詳細遙測數據。

3.模型上下文協議(MCP)支持

Spring AI 1.0 全面支持 Model Context Protocol (MCP),這是一個標準化協議,使 AI 模型能夠與外部工具、提示和資源進行交互。Spring AI 提供了客戶端和服務器端的 MCP支持,簡化了 MCP 工具的使用和創建。

最簡單的 MCP 自定義服務器端實現:

@Service
publicclass WeatherService {

    @Tool(description = "Get weather information by city name")
    public String getWeather(String cityName) {
        // 偽代碼
        return"The weather in " + cityName + " is 21°C and sunny.";
    }
}

@SpringBootApplication
publicclass McpServerApplication {

    privatestaticfinal Logger logger = LoggerFactory.getLogger(McpServerApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(McpServerApplication.class, args);
    }

@Bean
public ToolCallbackProvider weatherTools(WeatherService weatherService) {
return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
 }
}

最簡單的 MCP 客戶端核心代碼實現:

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
publicclass ClientController {
    @Autowired
    private ChatClient chatClient;

    @RequestMapping("/chat")
    public String chat(@RequestParam(value = "msg",defaultValue = "今天天氣如何?") String msg) {
        String response = chatClient.prompt()
        .user(msg)
        .call()
        .content();
        System.out.println("響應結果: " + response);
        return response;
    }
}

4.AI Agent(智能體)支持

AI Agent 的核心是“利用 AI 模型與其環境交互,以解決用戶定義的任務”。有效的 AI Agent 將規劃、記憶和作相結合,以完成用戶分配的任務。

Spring AI 1.0 支持兩種主要類型的 Agent:

  • 工作流驅動代理:通過預定義路徑編排 LLM 和工具,一種更可控的 Agents 實現方法,其中 LLM 和工具通過預定義的路徑進行編排。這些工作流是規范性的,可指導 AI 完成既定的作序列以實現可預測的結果。
  • 自主驅動代理:允許 LLM 自主規劃和執行處理步驟。這種方式代理將自己決定要調用的路徑,決定使用哪些工具以及以什么順序使用。

雖然完全自主代理的靈活性很有吸引力,但工作流為定義明確的任務提供了更好的可預測性和一致性。具體使用哪種類型,取決于您的具體要求和風險承受能力。

讓我們看看 Spring AI 如何通過五種基本模式來實現這些概念,每種模式都服務于特定的用例:

4.1 Chain 工作流模式

該模式將復雜任務分解為一系列步驟,其中每個 LLM 調用都會處理前一個 LLM 調用的輸出。

Chain Workflow 模式體現了將復雜任務分解為更簡單、更易于管理的步驟的原則。

圖片圖片

使用場景

  • 具有明確順序步驟的任務。
  • 當您想用延遲換取更高的準確性時。
  • 當每個步驟都基于上一步的輸出時。

以下是 Spring AI 實現中的一個實際示例:

public class ChainWorkflow {
    privatefinal ChatClient chatClient;
    privatefinal String[] systemPrompts;

    public String chain(String userInput) {
        String response = userInput;
        for (String prompt : systemPrompts) {
            String input = String.format("{%s}\n {%s}", prompt, response);
            response = chatClient.prompt(input).call().content();
        }
        return response;
    }
}

此實現演示了幾個關鍵原則:

  • 每個步驟都有重點。
  • 一個步驟的輸出成為下一個步驟的輸入。
  • 該鏈易于擴展和維護。

4.2 并行化工作流

LLM 可以同時處理任務,并以編程方式聚合其輸出。

圖片

使用場景

  • 處理大量相似但獨立的項目。
  • 需要多個獨立視角的任務。
  • 當處理時間至關重要且任務可并行化時。

簡單代碼實現:

List<String> parallelResponse = new ParallelizationWorkflow(chatClient)
.parallel(
    "Analyze how market changes will impact this stakeholder group.",
    List.of(
        "Customers: ...",
        "Employees: ...",
        "Investors: ...",
        "Suppliers: ..."
    ),
    4
);

4.3 路由工作流

路由模式實現了智能任務分配,從而支持對不同類型的輸入進行專門處理。

圖片

使用場景

  • 具有不同輸入類別的復雜任務。
  • 當不同的輸入需要專門處理時。
  • 何時可以準確處理分類。

簡單代碼實現:

@Autowired
private ChatClient chatClient;

RoutingWorkflow workflow = new RoutingWorkflow(chatClient);

Map<String, String> routes = Map.of(
    "billing", "You are a billing specialist. Help resolve billing issues...",
    "technical", "You are a technical support engineer. Help solve technical problems...",
    "general", "You are a customer service representative. Help with general inquiries..."
);

String input = "My account was charged twice last week";
String response = workflow.route(input, routes);

4.4 編排器

圖片

使用場景

  • 無法預先預測子任務的復雜任務。
  • 需要不同方法或觀點的任務。
  • 需要適應性問題解決的情況。

簡單實現代碼:

public class OrchestratorWorkersWorkflow {
    public WorkerResponse process(String taskDescription) {
        // 1. Orchestrator analyzes task and determines subtasks
        OrchestratorResponse orchestratorResponse = // ...

        // 2. Workers process subtasks in parallel
        List<String> workerResponses = // ...

        // 3. Results are combined into final response
        return new WorkerResponse(/*...*/);
    }
}

使用示例:

ChatClient chatClient = // ... initialize chat client
OrchestratorWorkersWorkflow workflow = new OrchestratorWorkersWorkflow(chatClient);

WorkerResponse response = workflow.process(
    "Generate both technical and user-friendly documentation for a REST API endpoint"
);

System.out.println("Analysis: " + response.analysis());
System.out.println("Worker Outputs: " + response.workerResponses());

4.5 評估器-優化器

圖片圖片

使用場景

  • 存在明確的評估標準。
  • 迭代優化提供可衡量的價值。
  • 任務受益于多輪批評。
public class EvaluatorOptimizerWorkflow {
    public RefinedResponse loop(String task) {
        Generation generation = generate(task, context);
        EvaluationResponse evaluation = evaluate(generation.response(), task);
        return new RefinedResponse(finalSolution, chainOfThought);
    }
}

使用示例:

ChatClient chatClient = // ... initialize chat client
EvaluatorOptimizerWorkflow workflow = new EvaluatorOptimizerWorkflow(chatClient);

RefinedResponse response = workflow.loop(
    "Create a Java class implementing a thread-safe counter"
);

System.out.println("Final Solution: " + response.solution());
System.out.println("Evolution: " + response.chainOfThought());

5.開始使用SpringAI

開發者可以通過 Maven 中央倉庫獲取 Spring AI 1.0 的所有組件。使用提供的 bom 導入依賴:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-bom</artifactId>
      <version>1.0.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

也可以在 Spring Initializr 網站上創建 1.0 GA 應用程序,并參考參考文檔中的"Getting Started"部分。

小結

Spring AI 1.0 的發布標志著企業級 Java 應用程序開發進入了一個新時代,使開發者能夠輕松地將最先進的 AI 能力集成到他們的 Spring 應用程序中。


責任編輯:武曉燕 來源: Java和磊哥
相關推薦

2013-06-24 09:11:22

Windows 8.1

2009-12-01 09:41:57

NetBeans 6.

2011-09-07 16:24:01

Windows Int

2014-12-09 09:41:46

谷歌Android Stu

2021-08-26 16:51:51

谷歌PixelAndroid

2012-01-13 10:20:32

Windows 8微軟

2009-06-08 13:29:36

NetBeans 6.NetBeans ID

2011-07-01 14:12:57

SEO

2016-01-05 13:41:59

物聯網內容硬件

2010-06-01 14:16:09

PylonsPython

2025-05-16 16:00:15

Spring AI大模型) 人工智能

2009-02-22 09:25:40

Vista RC SP正式版發布日期

2010-04-08 09:51:37

Windows 7 S發布日期

2023-01-24 16:44:49

iOSiOS 16.3蘋果

2009-12-02 11:05:26

Spring 3.0

2009-03-23 07:36:43

Ubuntu 9.10win7正式版

2009-02-16 17:33:52

銀光LinuxMoonlight 1

2010-03-08 14:21:00

phpMyAdmin

2011-05-17 09:10:26

Scala

2011-09-05 09:03:09

Python
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 嫩草视频免费 | 久久中文高清 | 天天干夜夜操视频 | 午夜爽爽男女免费观看hd | 国产高清视频在线观看 | 国产在线观看av | 亚洲精品一区二区三区四区高清 | 精品国产乱码久久久久久丨区2区 | 国产.com| 一级久久久久久 | 日韩欧美不卡 | 成年人在线观看视频 | 狠狠干天天干 | 一级毛片色一级 | 日韩精品区 | 亚洲天堂网站 | 久久中文字幕电影 | 欧美激情一区二区三区 | 欧美精品一区二区三区在线播放 | 精品国产一级 | 成人精品高清 | 国产福利资源在线 | 99精品欧美一区二区三区 | 国产视频中文字幕在线观看 | 亚洲精品乱码久久久久久久久 | 国产日韩欧美一区二区 | 国产精品永久免费视频 | 日韩一区二区黄色片 | 日韩欧美一级精品久久 | 成人不卡视频 | 精品www | 婷婷综合| 日韩视频国产 | 欧美在线综合 | 午夜在线免费观看 | 国产精品一区二区三区在线 | 亚洲日韩欧美一区二区在线 | 一区欧美| 亚洲视频免费在线播放 | 国产真实精品久久二三区 | 欧美激情精品久久久久 |