### Quick Start - Run Multimodal Example Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/multimodal/README.md Runs the multimodal example from the project root using Maven wrapper. The second command shows an alternative with an explicit API key as an environment variable. ```bash # From project root ./mvnw -pl examples/multimodal spring-boot:run ``` ```bash AI_DASHSCOPE_API_KEY=your_key ./mvnw -pl examples/multimodal spring-boot:run ``` -------------------------------- ### Build the agentscope example Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/agentscope/handoffs/README.md Command to build the example project from its directory. ```bash cd examples/multiagent-patterns/agentscope ../../../../mvnw -B package -DskipTests ``` -------------------------------- ### Install agent-framework to local Maven repo Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/agentscope/handoffs/README.md Command to install the agentic-spring-ai-agent-framework module from the repo root, required before building the example. ```bash # From repo root - install agent-framework to local Maven repo ./mvnw -pl agentic-spring-ai-agent-framework -am -B install -DskipTests ``` -------------------------------- ### Complete example with metadata fields and document processing Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-gitbook/README.md Full example showing how to create a reader with metadata fields, read documents, and iterate over them to print ID, content, and metadata. ```java import io.github.agentic.spring.ai.reader.gitbook.GitbookDocumentReader; import org.springframework.ai.document.Document; import java.util.Arrays; import java.util.List; public class GitbookReaderExample { public static void main(String[] args) { // Create reader instance with metadata fields List metadataFields = Arrays.asList("title", "description"); GitbookDocumentReader reader = new GitbookDocumentReader( "your-api-token", "your-space-id", null, // Use default API URL metadataFields ); // Read documents List documents = reader.get(); // Process document content and metadata for (Document doc : documents) { System.out.println("Document ID: " + doc.getId()); System.out.println("Content: " + doc.getText()); System.out.println("Metadata: " + doc.getMetadata()); } } } ``` -------------------------------- ### Project layout tree for agentscope example Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/agentscope/handoffs/README.md Shows the directory structure of the agentscope example, including configuration, service, runner, route actions, state constants, tools, and application.yml. ```text examples/multiagent-patterns/agentscope/ ├── pom.xml ├── README.md └── src/main/ ├── java/.../agentscope/ │ ├── AgentScopeApplication.java │ ├── AgentScopeHandoffsConfig.java # StateGraph, agents, routing │ ├── AgentScopeHandoffsService.java # invokes graph │ ├── AgentScopeHandoffsRunner.java # optional demo runner │ ├── route/ │ │ ├── RouteInitialAction.java # START → sales or support │ │ ├── RouteAfterSalesAction.java # sales → support or END │ │ └── RouteAfterSupportAction.java # support → sales or END │ ├── state/ │ │ └── AgentScopeStateConstants.java │ └── tools/ │ ├── TransferToSalesTool.java # support → sales (AgentScope Toolkit) │ ├── TransferToSupportTool.java # sales → support (Spring AI) │ └── UpdateExtraStateTool.java # example: read state + update extraState └── resources/ └── application.yml ``` -------------------------------- ### Install Agentic Spring AI Extensions from Source Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/README.md Commands to clone the repository and install the project locally using Maven. ```shell git clone --depth=1 https://github.com/agentic-spring-ai/agentic-spring-ai-extensions.git cd agentic-spring-ai-extensions mvn -DskipTests install ``` -------------------------------- ### Run and open chat UI Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/agentscope/handoffs/README.md Commands to start the app and open the built-in chat UI in the browser. ```bash ./mvnw spring-boot:run # Open http://localhost:8080/chatui/index.html ``` -------------------------------- ### Initialize SQLiteResource with default connection parameters Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-sqlite/README.md Example showing how to initialize SQLiteResource using default host, port, username, and password settings. ```java // 使用所有默认连接参数 (host=127.0.0.1, port=3306, username=root, password=root) SQLiteResource resource = new SQLiteResource( "test_db", // 数据库名称 | Database name "SELECT * FROM articles", // SQL查询语句 | SQL query Arrays.asList("title", "content"), // 文档内容字段 | Document content fields Arrays.asList("id") // 元数据字段 | Metadata fields ); ``` -------------------------------- ### Initialize SQLiteResource with custom credentials Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-sqlite/README.md Example showing how to initialize SQLiteResource by explicitly providing database name, username, password, query, content columns, and metadata columns. ```java // 使用默认的host(127.0.0.1)和port(3306) SQLiteResource resource = new SQLiteResource( "test_db", // 数据库名称 | Database name "test_user", // 用户名 | Username "test_password", // 密码 | Password "SELECT * FROM articles", // SQL查询语句 | SQL query Arrays.asList("title", "content"), // 文档内容字段 | Document content fields Arrays.asList("id") // 元数据字段 | Metadata fields ); ``` -------------------------------- ### Basic SQLiteDocumentReader Query Example Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-sqlite/README.md Demonstrates initializing a SQLiteResource with a simple SELECT statement and reading documents using the SQLiteDocumentReader. ```java SQLiteResource resource = new SQLiteResource( "localhost", 3306, "test_db", "test_user", "test_password", "SELECT id, title, content FROM articles WHERE status = 'published' LIMIT 100", Arrays.asList("title", "content"), // 内容字段 | Content fields Arrays.asList("id") // 元数据字段 | Metadata fields ); SQLiteDocumentReader reader = new SQLiteDocumentReader(resource); List documents = reader.get(); ``` -------------------------------- ### Run without the demo Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/agentscope/handoffs/README.md Command to start the app without the demo runner, so it waits for your own calls. ```bash ./mvnw spring-boot:run ``` -------------------------------- ### Run the voice agent with Maven Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/voice-agent/README.md Sets the DashScope API key and runs the Spring Boot application for the voice-agent example. Requires JDK 17+ and a valid AI_DASHSCOPE_API_KEY. ```bash export AI_DASHSCOPE_API_KEY=your-api-key ./mvnw -pl examples/voice-agent spring-boot:run ``` -------------------------------- ### Use Python and shell tools with ReactAgent Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/sandbox/agentic-spring-ai-sandbox/README.md Create a SandboxService, start it, create a BaseSandbox for a user/session, and build a ReactAgent with RunPythonCodeTool and RunShellCommandTool. Clean up all sandboxes in a finally block. Requires Java 17, a running Docker daemon, and a supported chat model. ```java import io.github.agentic.spring.ai.graph.agent.ReactAgent; import io.github.agentic.spring.ai.sandbox.ToolkitInit; import io.agentscope.runtime.sandbox.box.BaseSandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import org.springframework.ai.chat.model.ChatModel; import java.util.List; ManagerConfig managerConfig = ManagerConfig.builder().build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); BaseSandbox sandbox = new BaseSandbox( sandboxService, "user-123", "session-456"); // Configure or inject the ChatModel used by the application. ReactAgent agent = ReactAgent.builder() .name("sandbox_agent") .description("An agent that executes code in an isolated sandbox.") .instruction("Use the Python or shell tool when code execution is required.") .model(chatModel) .tools(List.of( ToolkitInit.RunPythonCodeTool(sandbox), ToolkitInit.RunShellCommandTool(sandbox))) .build(); try { agent.invoke("Use Python to calculate the first 20 Fibonacci numbers."); } finally { sandboxService.cleanupAllSandboxes(); } ``` -------------------------------- ### Custom SQLiteResource Query Example Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-sqlite/README.md Shows how to configure a SQLiteResource with a complex SQL query involving joins and date filtering. ```java SQLiteResource resource = new SQLiteResource( "localhost", 3306, "blog_db", "blog_user", "blog_password", """ SELECT p.id, p.title, p.content, u.username as author, p.created_at FROM posts p JOIN users u ON p.author_id = u.id WHERE p.status = 'published' AND p.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) """, Arrays.asList("title", "content", "author"), // 内容字段 | Content fields Arrays.asList("id", "created_at") // 元数据字段 | Metadata fields ); ``` -------------------------------- ### Error Handling Example Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-mbox/README.md Wrap the document retrieval process in a try-catch block to handle potential runtime exceptions. ```java try { List documents = reader.get(); } catch (RuntimeException e) { // Handle errors / 处理错误 System.err.println("Failed to read mbox file: " + e.getMessage()); } ``` -------------------------------- ### Sample Java controller using MemcachedChatMemoryRepository Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-memcached/README.md Example REST controller that uses MemcachedChatMemoryRepository with MessageWindowChatMemory and ChatClient to handle chat requests with memory. Note: The import for MemcachedChatMemoryRepository is missing in the original snippet. ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import io.github.agentic.spring.ai.memory.mongodb.MongoDBChatMemoryRepository; import javax.servlet.http.HttpServletResponse; @RestController public class ChatController { @Autowired private MemcachedChatMemoryRepository memcachedChatMemoryRepository; @GetMapping("/memcached") public String memcachedChat( HttpServletResponse response) { // Sets response character encoding to UTF-8 to ensure proper display of Chinese and other Unicode characters response.setCharacterEncoding("UTF-8"); // Constructs a message window-based chat memory component retaining up to 10 recent messages ChatMemory chatMemory = MessageWindowChatMemory.builder() .chatMemoryRepository(memcachedChatMemoryRepository) .maxMessages(1) .build(); ChatClient chatClient = ChatClient.builder(chatModel).defaultAdvisors( new SimpleLoggerAdvisor(), MessageChatMemoryAdvisor.builder(chatMemory).conversationId("memcachedId").build()) .build(); // Initiates AI model invocation with memory capabilities enabled return chatClient.prompt().user("你好") .call().chatResponse().getResult().getOutput().getText(); } } ``` -------------------------------- ### Java usage example for EmlEmailDocumentReader Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-email/README.md Shows how to create an EmlEmailDocumentReader, retrieve documents, and access email metadata and content. The constructor takes a file path and a boolean to enable attachment processing. ```java // Create a reader instance with an EML file and enable attachment processing EmlEmailDocumentReader reader = new EmlEmailDocumentReader("path/to/email.eml", true); // Get documents (email body and attachments if any) List documents = reader.get(); // Access email metadata Document emailDoc = documents.get(0); Map metadata = emailDoc.getMetadata(); String subject = (String) metadata.get("subject"); String from = (String) metadata.get("from"); String date = (String) metadata.get("date"); // Access email content String content = emailDoc.getText(); // Access attachment content (if any) if (documents.size() > 1) { Document attachmentDoc = documents.get(1); String filename = (String) attachmentDoc.getMetadata().get("filename"); String attachmentContent = attachmentDoc.getText(); } ``` -------------------------------- ### Configure Python Tool in application.yml Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/tool-calls/agentic-spring-ai-starter-tool-calling-python/README.md Optional YAML configuration to enable or disable the Python tool and set security-related engine and context options. The tool is enabled by default; this example shows the full configuration with all options. ```yaml spring: ai: alibaba: tool-calling: python: enabled: true engine: warn-interpreter-only: false context: allow-all-access: false allow-io: false allow-native-access: false allow-create-process: false allow-host-access: true ``` -------------------------------- ### Inject ChatClient in Spring Boot controller Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/models/agentic-spring-ai-dashscope/src/test/resources/data/acme/intro.txt Example of injecting ChatClient using ChatClient.Builder and exposing a chat endpoint. ```java @RestController public class ChatController { private final ChatClient chatClient; public ChatController(ChatClient.Builder builder) { this.chatClient = builder.build(); } @GetMapping("/chat") public String chat(String input) { return this.chatClient.prompt() .user(input) .call() .content(); } } ``` -------------------------------- ### Node.js WebSocket client example Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/voice-agent/README.md Connects to the WebSocket endpoint, sends a text message, and handles incoming events. It writes agent_chunk text to stdout and notes that tts_chunk contains base64 audio to be decoded and played. ```javascript const ws = new WebSocket('ws://localhost:8080/voice/ws'); ws.onopen = () => ws.send(JSON.stringify({text: "One turkey sandwich"})); ws.onmessage = (e) => { const ev = JSON.parse(e.data); if (ev.type === 'agent_chunk') process.stdout.write(ev.text); if (ev.type === 'tts_chunk') { /* decode base64, play audio */ } }; ``` -------------------------------- ### Use auto-configured RAG components in a Spring Boot controller Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/auto-configurations/rag/agentic-spring-ai-autoconfigure-rag-elasticsearch/README.md Example controller that injects the auto-configured HybridElasticsearchRetriever, HyDeRetriever, and HyDeTransformer beans and exposes REST endpoints for hybrid retrieval, HyDE retrieval, and HyDE transformation. ```java import io.github.agentic.spring.ai.rag.preretrieval.transformation.HyDeTransformer; import io.github.agentic.spring.ai.rag.retrieval.search.HyDeRetriever; import jakarta.annotation.Resource; @RestController @RequestMapping("/test") public class TestController { @Resource private HybridElasticsearchRetriever hybridRetriever; @Resource private HyDeRetriever hyDeRetriever; @Resource private HyDeTransformer hyDeTransformer; @GetMapping("/retrieval/hybrid") public List retrievalHybrid() { Query query = Query.builder() .text("What is hybridSearch") .build(); return hybridRetriever.retrieve(query); } @GetMapping("/retrieval/hyde") public List retrievalHyde() { Query query = Query.builder() .text("What is hybridSearch") .build(); return hyDeRetriever.retrieve(query); } @GetMapping("/transform/hyde") public Query transformHyde() { Query query = Query.builder() .text("What is hybridSearch") .build(); return hyDeTransformer.transform(query); } } ``` -------------------------------- ### Run the demo on startup Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/agentscope/handoffs/README.md Commands to run the application with the demo runner enabled, using an environment variable and the packaged jar. ```bash export AGENTSCOPE_RUNNER_ENABLED=true java -jar target/agentscope-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### Get Documents from Reader Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-mysql/README.md Retrieves a list of Document objects from the reader. ```java List documents = reader.get(); ``` -------------------------------- ### Initialize TablestoreChatMemoryRepository Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-tablestore/README.md Basic initialization of the repository using the Tablestore SyncClient with environment variables. ```java void init() { // Constructs the Tablestore Java client String endPoint = System.getenv("tablestore_end_point"); String instanceName = System.getenv("tablestore_instance_name"); String accessKeyId = System.getenv("tablestore_access_key_id"); String accessKeySecret = System.getenv("tablestore_access_key_secret"); SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName); // Initializes the TablestoreChatMemoryRepository TablestoreChatMemoryRepository chatMemoryRepository = new TablestoreChatMemoryRepository(client); } ``` -------------------------------- ### Initialize and Use ChatGptDataDocumentReader Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-chatgpt-data/README.md Demonstrates how to initialize the reader with a file path, optionally limit the number of conversations, and retrieve the processed documents. ```java // 初始化 reader,加载所有对话 // Initialize reader, load all conversations ChatGptDataDocumentReader reader = new ChatGptDataDocumentReader("/path/to/chatgpt/data.json"); // 或者指定只加载前 N 条对话 // Or specify to load only the first N conversations ChatGptDataDocumentReader reader = new ChatGptDataDocumentReader("/path/to/chatgpt/data.json", 10); // 获取处理后的文档列表 // Get the processed document list List documents = reader.get(); ``` -------------------------------- ### Override Default RedissonRedisChatMemoryRepository with Config Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-redis/README.md This configuration class extends RedisChatMemoryConnectionAutoConfiguration to provide custom Redisson Config instances for both standalone and cluster Redis setups. ```java import io.github.agentic.spring.ai.autoconfigure.memory.redis.*; import io.github.agentic.spring.ai.memory.redis.RedissonRedisChatMemoryRepository; import org.redisson.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CustomRedissonRedisChatMemoryAutoConfiguration extends RedisChatMemoryConnectionAutoConfiguration { private static final Logger logger = LoggerFactory.getLogger(CustomRedissonRedisChatMemoryAutoConfiguration.class); public CustomRedissonRedisChatMemoryAutoConfiguration(RedisChatMemoryProperties properties, RedisChatMemoryConnectionDetails connectionDetails, ObjectProvider sslBundles) { super(properties, connectionDetails, sslBundles); } @Override @Bean protected RedissonRedisChatMemoryRepository buildRedisChatMemoryRepository() { return super.buildRedisChatMemoryRepository(); } @Override protected RedissonRedisChatMemoryRepository createStandaloneRepository(RedisChatMemoryStandaloneConfiguration configuration) { logger.info("Configuring Redis Standalone chat memory repository using Redisson"); return RedissonRedisChatMemoryRepository.builder() .host(configuration.hostName()) .port(configuration.port()) .username(configuration.username()) .password(configuration.password()) .timeout(configuration.timeout()) .sslBundles(configuration.sslBundles()) .useSsl(configuration.ssl().isEnabled()) .bundle(configuration.ssl().getBundle()) // using your Config here .redissonConfig(new Config()) .build(); } @Override protected RedissonRedisChatMemoryRepository createClusterRepository(RedisChatMemoryClusterConfiguration configuration) { logger.info("Configuring Redis Cluster chat memory repository using Redisson"); return RedissonRedisChatMemoryRepository.builder() .nodes(configuration.nodeAddresses()) .username(configuration.username()) .password(configuration.password()) .timeout(configuration.timeout()) .sslBundles(configuration.sslBundles()) .useSsl(configuration.ssl().isEnabled()) .bundle(configuration.ssl().getBundle()) // using your Config here .redissonConfig(new Config()) .build(); } } ``` -------------------------------- ### Advanced Configuration with MemoryStore Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-tablestore/README.md Initialize the repository using a custom MemoryStore implementation for advanced session and message management. ```java void init() { // Constructs the Tablestore Java client String endPoint = System.getenv("tablestore_end_point"); String instanceName = System.getenv("tablestore_instance_name"); String accessKeyId = System.getenv("tablestore_access_key_id"); String accessKeySecret = System.getenv("tablestore_access_key_secret"); SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName); // Initializes TablestoreChatMemoryRepository via store MemoryStoreImpl store = xxx; // For store initialization, refer to https://github.com/aliyun/alibabacloud-tablestore-for-agent-memory/blob/main/java/examples/src/main/java/com/aliyun/openservices/tablestore/agent/memory/MemoryStoreInitExample.java TablestoreChatMemoryRepository chatMemoryRepository = new TablestoreChatMemoryRepository(store); } // For implementation details of the underlying MemoryStore, refer to: https://github.com/aliyun/alibabacloud-tablestore-for-agent-memory ``` -------------------------------- ### Run Tests Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-elasticsearch/README.md Execute the module's test suite using Maven. ```bash mvn test ``` -------------------------------- ### Spring Boot demo application Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-parsers/agentic-spring-ai-starter-document-parser-markdown/src/test/resources/code.md Standard Spring Boot application entry point with main method that runs with SpringApplication.run. ```java package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` -------------------------------- ### Retrieval Filter with FilterExpressionBuilder Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/rag/agentic-spring-ai-rag/README.md Shows how to use a filter expression with HyDeRetriever to filter retrieval results. The example builds an OR condition on the 'category' metadata field and puts it into the query context. ```java @RestController @RequestMapping("/test") public class TestController { @Resource private HyDeRetriever hyDeRetriever; @GetMapping("/retrieval") public List retrieval() { Query query = new Query("What is hybridSearch"); // (metadata.category == "Technical report" or metadata.category == "HybridSearch") FilterExpressionBuilder builder = new FilterExpressionBuilder(); Filter.Expression expression = builder.or( builder.eq("category", "Technical report"), builder.eq("category", "HybridSearch") ).build(); query.context().put(HyDeRetriever.FILTER_EXPRESSION, expression); return hyDeRetriever.retrieve(query); } } ``` -------------------------------- ### Create SQLiteResource Configuration Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-sqlite/README.md Initialize the SQLiteResource with database connection details, the target SQL query, and lists of fields for document content and metadata. ```java SQLiteResource resource = new SQLiteResource( "localhost", // SQLite主机地址 | SQLite host address 3306, // SQLite端口号 | SQLite port number "your_db", // 数据库名称 | Database name "username", // 用户名 | Username "password", // 密码 | Password "SELECT * FROM your_table", // SQL查询语句 | SQL query Arrays.asList("title", "content"), // 文档内容字段 | Document content fields Arrays.asList("id", "created_at") // 元数据字段 | Metadata fields ); ``` -------------------------------- ### Use AgentScopeHandoffsService in your own code Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/agentscope/handoffs/README.md Java snippet showing how to autowire the service and run a handoff query, printing each message text. ```java @Autowired AgentScopeHandoffsService service; var result = service.run("Hi, I'm having trouble with my account login. Can you help?"); result.messages().forEach(msg -> System.out.println(msg.getText())); ``` -------------------------------- ### Basic MySQLDocumentReader Query Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-mysql/README.md Initializes a MySQLResource with connection details and a simple SELECT statement, then uses MySQLDocumentReader to retrieve documents. ```java MySQLResource resource = new MySQLResource( "localhost", 3306, "test_db", "test_user", "test_password", "SELECT id, title, content FROM articles WHERE status = 'published' LIMIT 100", Arrays.asList("title", "content"), // 内容字段 | Content fields Arrays.asList("id") // 元数据字段 | Metadata fields ); MySQLDocumentReader reader = new MySQLDocumentReader(resource); List documents = reader.get(); ``` -------------------------------- ### Full HyDeRetriever Configuration with Similarity Threshold and TopK Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/rag/agentic-spring-ai-rag/README.md Extends the basic configuration by setting similarityThreshold to 0.8 and topK to 50 on the HyDeRetriever builder. ```java @Configuration public class Config { @Bean @ConditionalOnMissingBean(HyDeTransformer.class) public HyDeTransformer hyDeTransformer(ChatClient.Builder chatClientBuilder) { return HyDeTransformer.builder() .chatClientBuilder(chatClientBuilder) .build(); } @Bean @ConditionalOnMissingBean(HyDeRetriever.class) public HyDeRetriever hyDeRetriever(HyDeTransformer hyDeTransformer, VectorStore vectorStore) { return HyDeRetriever.builder() .hyDeTransformer(hyDeTransformer) .vectorStore(vectorStore) .similarityThreshold(0.8) .topK(50) .build(); } } ``` -------------------------------- ### Declare SandboxService as a Spring bean Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/sandbox/agentic-spring-ai-sandbox/README.md In a Spring Boot application, declare SandboxService as a singleton bean with explicit lifecycle methods: initMethod = "start" and destroyMethod = "cleanupAllSandboxes". This ensures proper startup and cleanup. ```java @Bean(initMethod = "start", destroyMethod = "cleanupAllSandboxes") SandboxService sandboxService() { return new SandboxService(ManagerConfig.builder().build()); } ``` -------------------------------- ### Create MySQLResource with all default connection parameters Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-mysql/README.md Configures a MySQLResource using all default connection parameters: host=127.0.0.1, port=3306, username=root, password=root. Only database name, SQL query, content columns, and metadata columns are specified. ```java // 使用所有默认连接参数 (host=127.0.0.1, port=3306, username=root, password=root) MySQLResource resource = new MySQLResource( "test_db", // 数据库名称 | Database name "SELECT * FROM articles", // SQL查询语句 | SQL query Arrays.asList("title", "content"), // 文档内容字段 | Document content fields Arrays.asList("id") // 元数据字段 | Metadata fields ); ``` -------------------------------- ### Create MySQLDocumentReader Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-mysql/README.md Instantiates a MySQLDocumentReader with the previously created MySQLResource. ```java MySQLDocumentReader reader = new MySQLDocumentReader(resource); ``` -------------------------------- ### Create MySQLResource Configuration Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-mysql/README.md Creates a MySQLResource with host, port, database, credentials, SQL query, content fields, and metadata fields. The SQL query selects the rows to be read. ```java MySQLResource resource = new MySQLResource( "localhost", // MySQL主机地址 | MySQL host address 3306, // MySQL端口号 | MySQL port number "your_db", // 数据库名称 | Database name "username", // 用户名 | Username "password", // 密码 | Password "SELECT * FROM your_table", // SQL查询语句 | SQL query Arrays.asList("title", "content"), // 文档内容字段 | Document content fields Arrays.asList("id", "created_at") // 元数据字段 | Metadata fields ); ``` -------------------------------- ### Add Maven dependency for Elasticsearch memory starter Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-elasticsearch/README.md Add this dependency to your project to use the Elasticsearch memory repository starter. Replace ${latest.version} with the actual version. ```xml io.github.agentic.spring.ai agentic-spring-ai-starter-model-chat-memory-repository-elasticsearch ${latest.version} ``` -------------------------------- ### Add agentic-spring-ai-starter dependency Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/models/agentic-spring-ai-dashscope/src/test/resources/data/acme/intro.txt Add the agentic-spring-ai-starter dependency to your project. Requires JDK 17+ and Spring Boot 3.x. ```xml io.github.agentic.spring.ai agentic-spring-ai-starter 1.0.0-M3.2 ``` -------------------------------- ### Run Integration Tests Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-bilibili/README.md Set required environment variables and run integration tests. ```bash export BILIBILI_SESSDATA=your_sessdata export BILIBILI_BILI_JCT=your_bili_jct export BILIBILI_BUVID3=your_buvid3 mvn test -Dtest=BilibiliDocumentReaderIT ``` -------------------------------- ### Image from Local Resource Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/multimodal/README.md Uses ClassPathResource to load a local image and create a UserMessage for image description. Add your own image to 'src/main/resources/images/sample.png' to use this scenario. ```java var resource = new ClassPathResource("images/sample.png"); UserMessage userMessage = UserMessage.builder() .text("Please describe this image.") .media(new Media(MimeTypeUtils.IMAGE_PNG, resource)) .build(); ``` -------------------------------- ### Apply Spring Javaformat with Maven wrapper Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-parsers/agentic-spring-ai-starter-document-parser-markdown/src/test/resources/code.md Command to run the Spring Javaformat plugin using the Maven wrapper. ```bash ./mvnw spring-javaformat:apply ``` -------------------------------- ### Add Python Tool Starter Dependency to pom.xml Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/tool-calls/agentic-spring-ai-starter-tool-calling-python/README.md Add the agentic-spring-ai-starter-python-tool dependency to your Maven pom.xml. The version is specified using the ${agentic-spring-ai.version} property. ```xml io.github.agentic.spring.ai agentic-spring-ai-starter-python-tool ${agentic-spring-ai.version} ``` -------------------------------- ### Image Generation via Tools Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/multimodal/README.md Builds a ReactAgent with a GenerateImageTool that wraps an ImageModel. Calling the agent with a text prompt triggers image generation. ```java ReactAgent creativeAgent = ReactAgent.builder() .model(chatModel) .methodTools(generateImageTool) .build(); creativeAgent.call("Generate an image of a sunset over mountains"); ``` -------------------------------- ### Custom Elasticsearch configuration with multi-node cluster Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-elasticsearch/README.md Shows how to create an ElasticsearchChatMemoryRepository with a custom ElasticsearchConfig, including setting host, port, scheme, credentials, and a list of nodes for a multi-node cluster. ```java ElasticsearchConfig config = new ElasticsearchConfig(); config.setHost("localhost"); config.setPort(9200); config.setScheme("https"); // Use HTTPS config.setUsername("elastic"); config.setPassword("password"); // Uses multi-node cluster configuration List nodes = new ArrayList<>(); nodes.add("node1:9200"); nodes.add("node2:9200"); config.setNodes(nodes); ElasticsearchChatMemoryRepository repository = new ElasticsearchChatMemoryRepository(config); ``` -------------------------------- ### Configure Cluster Connection Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-elasticsearch/README.md Set up the ElasticsearchConfig for a cluster by providing a list of nodes. ```java ElasticsearchConfig config = new ElasticsearchConfig(); // Configure cluster nodes | 配置集群节点 config.setNodes(Arrays.asList( "node1:9200", "node2:9201", "node3:9202" )); config.setIndex("your-index"); config.setQueryField("content"); config.setScheme("https"); // Optional authentication (applied to all nodes) | 可选的认证配置(应用于所有节点) config.setUsername("your-username"); config.setPassword("your-password"); ElasticsearchDocumentReader reader = new ElasticsearchDocumentReader(config); ``` -------------------------------- ### Create SQLiteDocumentReader Instance Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-sqlite/README.md Instantiate the reader using the previously configured SQLiteResource. ```java SQLiteDocumentReader reader = new SQLiteDocumentReader(resource); ``` -------------------------------- ### Create MySQLResource with explicit connection parameters Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-mysql/README.md Configures a MySQLResource with explicit database name, username, password, SQL query, content columns, and metadata columns. Uses default host (127.0.0.1) and port (3306). ```java // 使用默认的host(127.0.0.1)和port(3306) MySQLResource resource = new MySQLResource( "test_db", // 数据库名称 | Database name "test_user", // 用户名 | Username "test_password", // 密码 | Password "SELECT * FROM articles", // SQL查询语句 | SQL query Arrays.asList("title", "content"), // 文档内容字段 | Document content fields Arrays.asList("id") // 元数据字段 | Metadata fields ); ``` -------------------------------- ### Set DashScope API Key Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/examples/multimodal/README.md Exports the DashScope API key as an environment variable for authentication. Replace 'your_api_key' with your actual key from the Alibaba Cloud Bailian Console. ```bash export AI_DASHSCOPE_API_KEY=your_api_key ``` -------------------------------- ### Configure Maven Dependencies for Agentic Spring AI Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/README.md Add the BOM to dependency management and include specific starters like DashScope in your project dependencies. ```xml io.github.agentic-spring-ai agentic-spring-ai-extensions-bom 2.1.0-dev pom import io.github.agentic-spring-ai agentic-spring-ai-starter-dashscope ``` -------------------------------- ### Basic HyDeRetriever Configuration Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/rag/agentic-spring-ai-rag/README.md Defines HyDeTransformer and HyDeRetriever beans with default settings. The HyDeTransformer uses a ChatClient.Builder, and the HyDeRetriever uses the transformer and a VectorStore. ```java @Configuration public class Config { @Bean @ConditionalOnMissingBean(HyDeTransformer.class) public HyDeTransformer hyDeTransformer(ChatClient.Builder chatClientBuilder) { return HyDeTransformer.builder() .chatClientBuilder(chatClientBuilder) .build(); } @Bean @ConditionalOnMissingBean(HyDeRetriever.class) public HyDeRetriever hyDeRetriever(HyDeTransformer hyDeTransformer, VectorStore vectorStore) { return HyDeRetriever.builder() .hyDeTransformer(hyDeTransformer) .vectorStore(vectorStore) .build(); } } ``` -------------------------------- ### Complete Standalone Redis Configuration Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-redis/README.md Complete standalone Redis configuration with authentication, timeout, database index, and key prefix. ```yaml spring: ai: memory: redis: # Supports standalone and cluster mode: standalone # Supports jedis, lettuce, and redisson client-type: jedis host: localhost port: 6379 username: yourUsername password: yourPassword timeout: 2000 database: 0 key-prefix: yourKeyPrefix ``` -------------------------------- ### Full RAG configuration with all parameters in application.yml Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/auto-configurations/rag/agentic-spring-ai-autoconfigure-rag-elasticsearch/README.md Full configuration with all available parameters for the Elasticsearch RAG module, including recall, RRF, retriever type, and weights. Defaults are shown in comments. ```yaml spring: # spring elasticsearch configuration elasticsearch: uris: http://localhost:9200 username: test password: test ai: # dashscope configuration dashscope: api-key: ${DASHSCOPE_API_KEY} chat: options: model: qwen-plus-2025-04-28 embedding: options: model: text-embedding-v1 # vector store configuration vectorstore: elasticsearch: initialize-schema: true index-name: rag_index_name similarity: cosine dimensions: 1536 # rag configuration alibaba: rag: elasticsearch: # Default value: true enabled: true # Default value: false use-rrf: false # knn recall parameter configuration recall: # Similarity threshold, default value 0.0, accepts all similarity-threshold: 0.8 # The number of neighbors, default value 50 neighbors-num: 50 # The number of candidates, default value 100 candidate-num: 100 # rrf parameter configuration rrf: # k value, default value 60 rank-constant: 60 # window size, default value 50 rank-window-size: 50 # support bm25, knn , hybrid, default value hybrid retriever-type: hybrid # return topK documents, default value 50 top-k: 50 # hybrid mode knn weight, default value 1 knn-bias: 1 # hybrid mode bm25 weight, default value 1 bm25-bias: 1 ``` -------------------------------- ### Spring Boot configuration for MySQL memory Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-jdbc/README.md Basic configuration for enabling MySQL memory and setting up the datasource. Place in application.properties or application.yml. The URL includes many MySQL-specific parameters. ```yaml spring: ai: memory: mysql: enabled: true datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&allowMultiQueries=true&tinyInt1isBit=false&allowLoadLocalInfile=true&allowLocalInfile=true&allowUrl username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` -------------------------------- ### ChatController using JDBC memory repository Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-jdbc/README.md Sample controller that uses MysqlChatMemoryRepository with MessageWindowChatMemory and MessageChatMemoryAdvisor to provide streaming chat responses. The endpoint is named /redis but uses MySQL memory. ```java import org.springframework.ai.chat.client.ChatClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import io.github.agentic.spring.ai.memory.jdbc.MysqlChatMemoryRepository; @RestController public class ChatController { @Autowired private MysqlChatMemoryRepository mysqlChatMemoryRepository; @Autowired private ChatClient chatClient; /** * Redis Stream Chat Interface (Actual implementation uses MySQL Chat Memory) * * @param prompt User-submitted prompt * @param chatId Conversation ID * @param response HTTP response object for encoding configuration * @return String streaming response */ @GetMapping("/redis") public Flux redis( @RequestParam("prompt") String prompt, @RequestParam("chatId") String chatId, HttpServletResponse response) { // Sets the response character encoding to UTF-8 response.setCharacterEncoding("UTF-8"); // Constructs a message window-based memory component with a limit of 10 retained messages ChatMemory chatMemory = MessageWindowChatMemory.builder() .chatMemoryRepository(mysqlChatMemoryRepository) .maxMessages(10) .build(); // Initiates a chat request and returns the result in streaming mode return chatClient.prompt(prompt) .advisors(new MessageChatMemoryAdvisor(chatMemory)) .advisors(a -> a .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId) .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100) ) .stream() .content(); // Retrieves the content stream } } ``` -------------------------------- ### Layout detection with Detectron2LayoutModel Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-parsers/agentic-spring-ai-starter-document-parser-bibtex/src/test/resources/layout-parser-paper.pdf Minimal API for layout detection using LayoutParser. Requires an image file path and a pre-trained model identifier in the semantic syntax lp:///. ```python import layoutparser as lp image = cv2.imread("image_file") # load images model = lp.Detectron2LayoutModel("lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config") layout = model.detect(image) ``` -------------------------------- ### Convert PEM files to PKCS12 keystore Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-redis/src/test/ABOUT-TEST.md Converts the generated PEM files into a PKCS12 keystore format for JKS configuration requirements. ```bash openssl pkcs12 -export -in src/test/resources/ssl/cert.pem -inkey src/test/resources/ssl/key.pem -out src/test/resources/ssl/keystore.p12 ``` -------------------------------- ### Full HybridElasticsearchRetriever bean configuration Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/rag/agentic-spring-ai-rag/README.md Full configuration for HybridElasticsearchRetriever with all tuning parameters: similarityThreshold, neighborsNum, candidateNum, topK, rankWindowSize, rankConstant, bm25Bias, knnBias, retrieverType, and useRrf. ```java @Configuration public class Config { @Bean public HybridElasticsearchRetriever hybridElasticsearchRetriever(ElasticsearchVectorStoreProperties vectorStoreProperties, ElasticsearchClient elasticsearchClient, EmbeddingModel embeddingModel) { ElasticsearchVectorStoreOptions elasticsearchVectorStoreOptions = new ElasticsearchVectorStoreOptions(); elasticsearchVectorStoreOptions.setIndexName(vectorStoreProperties.getIndexName()); elasticsearchVectorStoreOptions.setDimensions(vectorStoreProperties.getDimensions()); elasticsearchVectorStoreOptions.setSimilarity(vectorStoreProperties.getSimilarity()); elasticsearchVectorStoreOptions.setEmbeddingFieldName(vectorStoreProperties.getEmbeddingFieldName()); return HybridElasticsearchRetriever.builder() .vectorStoreOptions(elasticsearchVectorStoreOptions) .elasticsearchClient(elasticsearchClient) .embeddingModel(embeddingModel) .similarityThreshold(0.8) .neighborsNum(50) .candidateNum(100) .topK(50) .rankWindowSize(50) .rankConstant(60) .bm25Bias(1.0f) .knnBias(1.0f) .retrieverType(RetrieverType.HYBRID) .useRrf(true) .build(); } } ``` -------------------------------- ### Single Video Processing Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/document-readers/agentic-spring-ai-starter-document-reader-bilibili/README.md Create credentials and a resource to read a single Bilibili video by URL or BV ID. ```java // 创建凭证 // Create credentials BilibiliCredentials credentials = BilibiliCredentials.builder() .sessdata("your_sessdata") .biliJct("your_bili_jct") .buvid3("your_buvid3") .build(); // 创建资源(支持 BV 号或完整 URL) // Create resource (supports BV ID or full URL) BilibiliResource resource = new BilibiliResource( "https://www.bilibili.com/video/BV1xx411c7mD/", credentials ); // 或使用 BV 号 // Or use BV ID BilibiliResource resource = new BilibiliResource("BV1xx411c7mD", credentials); // 创建 reader 并获取文档 // Create reader and get documents BilibiliDocumentReader reader = new BilibiliDocumentReader(resource); List documents = reader.get(); ``` -------------------------------- ### Basic RAG configuration in application.yml Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/auto-configurations/rag/agentic-spring-ai-autoconfigure-rag-elasticsearch/README.md Basic configuration for enabling the Elasticsearch RAG module. Sets Elasticsearch connection, DashScope API key and models, vector store settings, and enables the RAG feature. ```yaml spring: # spring elasticsearch configuration elasticsearch: uris: http://localhost:9200 username: test password: test ai: # dashscope configuration dashscope: api-key: ${DASHSCOPE_API_KEY} chat: options: model: qwen-plus-2025-04-28 embedding: options: model: text-embedding-v1 # vector store configuration vectorstore: elasticsearch: initialize-schema: true index-name: rag_index_name similarity: cosine dimensions: 1536 # rag configuration alibaba: rag: elasticsearch: enabled: true ``` -------------------------------- ### Implement ChatController with Redis Memory Source: https://github.com/agentic-spring-ai/agentic-spring-ai-extensions/blob/main/memory-repository/agentic-spring-ai-model-chat-memory-repository-redis/README.md This controller demonstrates using BaseRedisChatMemoryRepository with MessageWindowChatMemory to maintain conversation history in Redis for a streaming ChatClient. ```java import io.github.agentic.spring.ai.memory.redis.BaseRedisChatMemoryRepository; import jakarta.servlet.http.HttpServletResponse; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor; import org.springframework.ai.chat.memory.ChatMemory; import org.springframework.ai.chat.memory.MessageWindowChatMemory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; @RestController public class ChatController { @Autowired private BaseRedisChatMemoryRepository baseRedisChatMemoryRepository; @Autowired private ChatClient chatClient; /** * Stream-based chat interface (with conversation history stored in Redis). * * @param prompt User's input question or prompt. * @param chatId Conversation ID used to identify the current session. * @param response HttpServletResponse object for setting response encoding. * @return Streamed response content (Flux), gradually output AI responses */ @GetMapping("/redis") public Flux redisChat( @RequestParam("prompt") String prompt, @RequestParam("chatId") String chatId, HttpServletResponse response) { // Sets the response character encoding to UTF-8 to ensure proper display of Chinese and other Unicode characters response.setCharacterEncoding("UTF-8"); // Constructs a message window-based chat memory component retaining up to 10 recent messages ChatMemory chatMemory = MessageWindowChatMemory.builder() .chatMemoryRepository(baseRedisChatMemoryRepository) .maxMessages(10) .build(); // Initiates AI model invocation with memory capabilities enabled return chatClient.prompt(prompt) .advisors(MessageChatMemoryAdvisor.builder(chatMemory).build()) .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId)) .stream() // Enables streaming response .content(); // Retrieves the content stream } } ```