### Install and Run Development Server (Bash) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/frontend/packages/main/README.md Commands to install dependencies and start the development server for the main Umi application. Assumes the user is in the 'frontend_studio' directory. ```bash cd frontend_studio npm install npm run dev -w packages/main ``` -------------------------------- ### Install All Project Dependencies (Bash) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/frontend/README.md Installs all project dependencies across the monorepo. This command should be run in the root directory after initial setup or cloning. ```bash npm run re-install ``` -------------------------------- ### Configure API Key and Run ChatBot Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/chatbot/README.md Commands to set the required environment variable for the LLM provider and execute the Spring Boot application. This process assumes the user has JDK 17+ installed and a valid API key. ```shell export AI_DASHSCOPE_API_KEY=your-api-key git clone https://github.com/alibaba/spring-ai-alibaba.git cd examples/chatbot mvn spring-boot:run ``` -------------------------------- ### Clone Chatbot Example Repository Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/README.md This snippet demonstrates how to clone the spring-ai-alibaba repository and navigate to the chatbot example directory using git. It's the initial step for setting up the project locally. ```shell git clone --depth=1 https://github.com/alibaba/spring-ai-alibaba.git cd spring-ai-alibaba/examples/chatbot ``` -------------------------------- ### Start Spring AI Alibaba Admin Frontend Service Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/README.md This command initiates the frontend development server for the Spring AI Alibaba Admin project. It requires navigating to the `packages/main` directory and running `npm run dev` after installing dependencies. ```bash cd packages/main npm run dev ``` -------------------------------- ### Setup and Run Standalone Agent Chat UI Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-studio/agent-chat-ui/README.md Commands to clone the repository, install necessary Node.js dependencies, and start the development server for the standalone UI. ```bash git clone https://github.com/alibaba/spring-ai-alibaba.git cd spring-ai-alibaba/spring-ai-alibaba-studio/agent-chat-ui pnpm install pnpm dev ``` -------------------------------- ### Run Spring Boot Application Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multimodal/README.md Commands to launch the multimodal example application using Maven. ```bash ./mvnw -pl examples/multimodal spring-boot:run AI_DASHSCOPE_API_KEY=your_key ./mvnw -pl examples/multimodal spring-boot:run ``` -------------------------------- ### Start Spring AI Alibaba Admin Server (Bash) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/spring-ai-alibaba-admin-server-start/README.md Executes the startup script for the Spring AI Alibaba Admin Server, which helps in starting database-related services. This is followed by starting the application itself using Maven. ```bash sh start.sh ``` -------------------------------- ### Install Development Dependencies (Bash) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/frontend/README.md Installs necessary development dependencies for the project, including rimraf, copyfiles, and cross-env. These are essential for build and development scripts. ```bash npm install rimraf copyfiles cross-env --save-dev ``` -------------------------------- ### Spring AI MCP Agent with Manual Client Setup Source: https://context7.com/kehynote/spring-ai-alibaba/llms.txt This Java code snippet illustrates manual setup of an MCP client and subsequent integration with a Spring AI agent. It involves creating an HTTP client, configuring the MCP transport, and then building an MCP sync client. The retrieved MCP tools are converted into Spring AI ToolCallbacks, allowing the agent to use them. ```java import io.modelcontextprotocol.client.McpClient; import io.modelcontextprotocol.client.McpSyncClient; import io.modelcontextprotocol.client.transport.HttpClientSseClientTransport; import io.modelcontextprotocol.spec.McpSchema; import org.springframework.ai.chat.model.ChatModel; import org.springframework.ai.விலான.tool.ToolCallback; import org.springframework.ai.விலான.tool.FunctionToolCallback; import org.springframework.ai.விலான.agent.ReactAgent; import org.springframework.ai.விலான.memory.MemorySaver; import org.springframework.beans.factory.annotation.Autowired; import java.net.http.HttpClient; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; // Method 2: Manual MCP client setup (without Spring Boot) public class ManualMcpIntegration { @Autowired private ChatModel chatModel; public void setupAndRunManualMcpAgent() throws Exception { HttpClient.Builder httpBuilder = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(60)); McpClientTransport transport = HttpClientSseClientTransport.builder("https://mcp.example.com") .clientBuilder(httpBuilder) .sseEndpoint("sse") .build(); McpSyncClient mcpClient = McpClient.sync(transport) .requestTimeout(Duration.ofSeconds(60)) .capabilities(McpSchema.ClientCapabilities.builder().roots(true).build()) .build(); mcpClient.initialize(); McpSchema.ListToolsResult toolsResult = mcpClient.listTools(); // Convert MCP tools to Spring AI ToolCallbacks List toolCallbacks = new ArrayList<>(); for (McpSchema.Tool mcpTool : toolsResult.tools()) { ToolCallback callback = FunctionToolCallback.builder( mcpTool.name(), (Map input) -> { McpSchema.CallToolResult result = mcpClient.callTool( new McpSchema.CallToolRequest(mcpTool.name(), input) ); return result.content().stream() .filter(c -> c instanceof McpSchema.TextContent) .map(c -> ((McpSchema.TextContent) c).text()) .collect(Collectors.joining()); }) .description(mcpTool.description()) .inputType(Map.class) .build(); toolCallbacks.add(callback); } ReactAgent agent = ReactAgent.builder() .name("manual_mcp_agent") .model(chatModel) .tools(toolCallbacks.toArray(new ToolCallback[0])) .build(); agent.call("Get current weather information."); } } ``` -------------------------------- ### Start Middleware Services with Docker Compose Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/README.md This command navigates to the middleware directory and executes a shell script to start essential middleware services like MySQL, Elasticsearch, Nacos, Redis, and RocketMQ using Docker Compose. This is a prerequisite for running the backend service. ```bash cd docker/middleware sh run.sh ``` -------------------------------- ### Run Development Server (Bash) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/frontend/README.md Starts the development server for the main workbench application. Changes to files in `main/src` will trigger automatic updates. ```bash npm run dev ``` -------------------------------- ### Build and Run Routing Graph Application Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/routing/src/main/java/com/alibaba/cloud/ai/examples/multiagents/routing/graph/README.md Commands to build the project using Maven and execute the application, including options for enabling the demo runner. ```bash # Build the project ./mvnw -pl :routing-graph -am -B package -DskipTests # Run the application java -jar target/routing-graph-0.0.1-SNAPSHOT.jar # Run with demo enabled export routing-graph.runner.enabled=true ./mvnw -pl :routing-graph spring-boot:run ``` -------------------------------- ### Configure Custom Template Delimiters with SaaStTemplateRenderer Source: https://context7.com/kehynote/spring-ai-alibaba/llms.txt Demonstrates how to instantiate a custom TemplateRenderer with specific start and end delimiters and apply it to a ReactAgent. This setup allows the use of custom placeholder syntax (e.g., [[variable]]) within system prompts and instructions. ```java import com.alibaba.cloud.ai.graph.agent.renderer.SaaStTemplateRenderer; import org.springframework.ai.template.TemplateRenderer; // Create custom template renderer with [[ ]] delimiters TemplateRenderer customRenderer = SaaStTemplateRenderer.builder() .startDelimiter("[[") .endDelimiter("]]") .build(); // Use custom placeholders in prompts ReactAgent agent = ReactAgent.builder() .name("custom_template_agent") .model(chatModel) .systemPrompt(""" You are a professional [[role]] assistant. Your expertise is in [[domain]]. Please respond in [[language]]. """) .instruction(""" The user's topic is: [[topic]] Requirements: 1. Be professional 2. Provide examples 3. Keep it [[style]] """) .templateRenderer(customRenderer) .build(); // Variables are resolved from input map Map inputs = Map.of( "input", "Explain Spring framework core features", "role", "technical expert", "domain", "Java enterprise development", "language", "English", "topic", "Spring Framework", "style", "concise and clear" ); Optional result = agent.invoke(inputs); ``` -------------------------------- ### Run Chatbot Application with Maven Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/README.md This command uses Maven to run the Spring Boot application. It starts the chatbot service, making it accessible via a web interface. ```shell mvn spring-boot:run ``` -------------------------------- ### Copy Environment File (Bash/PowerShell) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/frontend/README.md Copies the example environment file to a new file named '.env'. This file is used to configure environment-specific variables for the application. ```bash cp .env.example .env ``` ```powershell Copy-Item .env.example .env ``` -------------------------------- ### Configure Environment Variables (Text) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/frontend/README.md Example environment variables for the web server URL, backend type, and default login credentials. These should be customized in the '.env' file. ```text # Web server URL WEB_SERVER="http://127.0.0.1:8080" # Backend type, e.g., java, python BACK_END="java" # Default username for application login DEFAULT_USERNAME=saa # Default password for application login DEFAULT_PASSWORD=123456 ``` -------------------------------- ### Configure Environment Variable for DashScope API Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/routing/src/main/java/com/alibaba/cloud/ai/examples/multiagents/routing/graph/README.md Sets the required DashScope API key as an environment variable for the Spring AI Alibaba application. ```bash export AI_DASHSCOPE_API_KEY=your-dashscope-api-key ``` -------------------------------- ### Invoke RoutingGraphService in Application Code Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/routing/src/main/java/com/alibaba/cloud/ai/examples/multiagents/routing/graph/README.md Demonstrates how to inject the RoutingGraphService into a Spring component and execute a query through the routing graph. ```java @Autowired RoutingGraphService routingGraphService; var result = routingGraphService.run("How do I authenticate API requests?"); System.out.println("Final answer: " + result.finalAnswer()); ``` -------------------------------- ### Add Chatbot Dependencies to Maven Project Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/README.md These XML snippets define the necessary dependencies for the spring-ai-alibaba chatbot example in a Maven project. It includes the agent framework and a starter for the DashScope model. ```xml com.alibaba.cloud.ai spring-ai-alibaba-agent-framework 1.1.2.0 com.alibaba.cloud.ai spring-ai-alibaba-starter-dashscope 1.1.2.1 ``` -------------------------------- ### AgentScope Tool Registration with Toolkit Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/agentscope/handoffs/README.md This example illustrates how to register tools for an AgentScope ReActAgent. It shows the use of `io.agentscope.core.tool.Toolkit` and how tools are defined using `@Tool` and `@ToolParam`. The `ToolContext` is automatically injected into the tool methods. ```java import io.agentscope.core.tool.Toolkit; import io.agentscope.core.agent.ReActAgent; // ... other imports // Assuming 'transferToSales' and other tools are defined elsewhere Toolkit toolkit = Toolkit.builder() .addTool(new TransferToSalesTool()) // Add other tools as needed .build(); ReActAgent supportAgent = ReActAgent.builder() .toolkit(toolkit) // ... other configurations .build(); ``` -------------------------------- ### WebSocket Client Interaction Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/voice-agent/README.md A Node.js example demonstrating how to connect to the voice agent WebSocket, send a text request, and handle incoming streaming events like agent chunks and TTS audio. ```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 */ } }; ``` -------------------------------- ### Clone Spring AI Alibaba Admin Project (Bash) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/spring-ai-alibaba-admin-server-start/README.md Clones the Spring AI Alibaba Admin project from GitHub and navigates into the project directory. This is the initial step for setting up the project locally. ```bash git clone https://github.com/spring-ai-alibaba/spring-ai-alibaba-admin.git cd admin ``` -------------------------------- ### Build for Java Backend Deployment (Bash) Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/frontend/README.md Builds the project for deployment when the backend is Java. This command generates a distributable artifact in the `./packages/main/dist` directory. ```bash npm run build:subtree:java ``` -------------------------------- ### Invoke Multi-Agent Handoffs Service Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/handoffs-multiagent/README.md Example of how to inject and use the MultiAgentHandoffsService in a Spring component to process user queries through the multi-agent graph. ```java @Autowired MultiAgentHandoffsService 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())); ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multimodal/README.md Sets the required API key for DashScope services in the shell environment. ```bash export AI_DASHSCOPE_API_KEY=your_api_key ``` -------------------------------- ### Environment and Build Commands Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/skills/README.md Shell commands for setting the required DashScope API key and building the Spring Boot application using Maven. ```bash export AI_DASHSCOPE_API_KEY=your-dashscope-api-key ./mvnw -pl :skills -am -B package -DskipTests ``` -------------------------------- ### Clone Spring AI Alibaba Admin Project Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/README.md This code snippet demonstrates how to clone the Spring AI Alibaba Admin project repository using Git and navigate into the project directory. It's the first step in setting up the project from source code. ```bash git clone https://github.com/spring-ai-alibaba/spring-ai-alibaba-admin.git cd spring-ai-alibaba-admin ``` -------------------------------- ### Build and Run Supervisor Application Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/supervisor/README.md Commands to build the project using Maven and execute the Spring Boot application. ```bash mvn -B package -DskipTests java -jar target/supervisor-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### Configure ReactAgent with DashScope Chat Model in Java Source: https://context7.com/kehynote/spring-ai-alibaba/llms.txt This snippet demonstrates the basic configuration of a ReactAgent using the DashScopeChatModel. It shows how to initialize the DashScope API, configure chat options, and build the agent with a system prompt, instructions, and conversation memory. The agent can then be invoked for simple queries or with thread IDs for maintaining conversation context. ```java import com.alibaba.cloud.ai.dashscope.api.DashScopeApi; import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel; import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions; import com.alibaba.cloud.ai.graph.agent.ReactAgent; import com.alibaba.cloud.ai.graph.checkpoint.savers.MemorySaver; import org.springframework.ai.chat.model.ChatModel; import com.alibaba.cloud.ai.graph.runnable.RunnableConfig; import org.springframework.ai.chat.messages.AssistantMessage; // Create DashScope API and ChatModel DashScopeApi dashScopeApi = DashScopeApi.builder() .apiKey(System.getenv("AI_DASHSCOPE_API_KEY")) .build(); ChatModel chatModel = DashScopeChatModel.builder() .dashScopeApi(dashScopeApi) .defaultOptions(DashScopeChatOptions.builder() .temperature(0.7) .maxToken(2000) .topP(0.9) .enableThinking(true) .build()) .build(); // Create ReactAgent with system prompt and memory ReactAgent agent = ReactAgent.builder() .name("my_assistant") .model(chatModel) .systemPrompt("You are a helpful technical assistant.") .instruction(""" You are an experienced software architect. When answering questions: 1. First understand the user's core requirements 2. Analyze possible technical solutions 3. Provide clear recommendations with reasoning """) .saver(new MemorySaver()) // Enable conversation memory .build(); // Simple invocation AssistantMessage response = agent.call("How do I implement a singleton pattern in Java?"); System.out.println(response.getText()); // Invocation with thread ID for conversation continuity RunnableConfig config = RunnableConfig.builder() .threadId("user_session_123") .build(); agent.call("My name is Alice", config); agent.call("What is my name?", config); // Will remember: "Your name is Alice" ``` -------------------------------- ### Run Voice Agent Application Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/voice-agent/README.md Commands to configure the DashScope API key and execute the Spring Boot application using Maven. ```bash export AI_DASHSCOPE_API_KEY=your-api-key ./mvnw -pl examples/voice-agent spring-boot:run ``` -------------------------------- ### Configure Skill Registry and Agent Hook Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/skills/README.md Demonstrates the initialization of the ClasspathSkillRegistry to load skills from the resources directory and the SkillsAgentHook to provide the read_skill tool and system prompt augmentation. ```java SkillRegistry registry = ClasspathSkillRegistry.builder() .classpathPath("skills") .build(); SkillsAgentHook skillsAgentHook = SkillsAgentHook.builder() .skillRegistry(registry) .build(); ReactAgent sqlAssistantAgent = ReactAgent.builder() .hooks(List.of(skillsAgentHook)) .build(); ``` -------------------------------- ### Output Format Configuration Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multimodal/README.md Configuration guidelines for the outputFormat parameter used in generate_image and AudioService endpoints. ```APIDOC ## Configuration: Output Format Parameter ### Description This parameter controls how the service returns generated media (images or audio). It is applicable to `generate_image` and `AudioService` (TTS) operations. ### Parameters #### Request Body - **outputFormat** (string) - Optional - The format of the returned media. Options: "url" (default) or "base64". ### Usage Guidelines - **url**: Recommended for model-friendly workflows. The tool result is sent to the model as context, minimizing token usage. - **base64**: Recommended for direct client consumption (e.g., when `returnDirect=true`). Note: Base64 significantly increases token usage if sent back to the model. ### Request Example { "prompt": "A futuristic city", "outputFormat": "url" } ### Response #### Success Response (200) - **result** (string) - The URL or base64 encoded string of the generated content. #### Response Example { "result": "https://api.example.com/media/image123.png" } ``` -------------------------------- ### Build and Run Spring AI Handoffs Application Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/handoffs-singleagent/README.md Commands to build the project using Maven and execute the application. Includes instructions for enabling the four-turn demo via environment variables. ```bash cd examples/multiagent-patterns/handoffs-singleagent ./mvnw -B package -DskipTests # Run with demo enabled export HANDOFFS_RUN_EXAMPLES=true java -jar target/handoffs-singleagent-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### Set DashScope API Key for Chatbot Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/README.md This command sets the necessary API key for the DashScope model, which is used by the 'spring-ai-alibaba-starter-dashscope'. Ensure you replace 'your-api-key' with your actual Aliyun Bailian API key. ```shell # this example uses 'spring-ai-alibaba-starter-dashscope', visit https://java2ai.com to learn how to use OpenAI/DeepSeek. export AI_DASHSCOPE_API_KEY=your-api-key ``` -------------------------------- ### Build and Deploy Agent Chat UI Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-studio/agent-chat-ui/README.md Command to build the UI project and copy the resulting static files into the Spring Boot resource directory. ```shell pnpm run deploy ``` -------------------------------- ### Build and Run Multi-Agent Handoffs Application Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multiagent-patterns/handoffs-multiagent/README.md Commands to build the Maven project and execute the application, including options for enabling the demo runner or running the service directly. ```bash cd examples/multiagent-patterns/handoffs-multiagent ./mvnw -B package -DskipTests export HANDOFFS_RUNNER_ENABLED=true java -jar target/handoffs-multiagent-0.0.1-SNAPSHOT.jar ./mvnw spring-boot:run ``` -------------------------------- ### Analyze Images with ChatModel Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multimodal/README.md Demonstrates how to pass images to the ChatModel using either a public URL or a local resource. ```java // Image from URL UserMessage userMessage = UserMessage.builder() .text("Explain what do you see in this picture?") .media(List.of(new Media(MimeTypeUtils.IMAGE_PNG, URI.create("https://example.com/image.png")))) .build(); ChatResponse response = chatModel.call(new Prompt(userMessage)); // Image from Local Resource var resource = new ClassPathResource("images/sample.png"); UserMessage userMessage = UserMessage.builder() .text("Please describe this image.") .media(new Media(MimeTypeUtils.IMAGE_PNG, resource)) .build(); ``` -------------------------------- ### Configure Maven Dependencies for Spring AI Alibaba Agent Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/spring-ai-alibaba-admin/README.md Includes the required dependencies for Nacos integration, observability via Micrometer and OpenTelemetry, and Spring AI auto-configuration modules. These dependencies enable dynamic prompt loading and telemetry reporting. ```xml com.alibaba.cloud.ai spring-ai-alibaba-agent-nacos {spring.ai.alibaba.version} com.alibaba.cloud.ai spring-ai-alibaba-autoconfigure-arms-observation {spring.ai.alibaba.version} org.springframework.boot spring-boot-starter-actuator io.micrometer micrometer-registry-otlp io.micrometer micrometer-tracing-bridge-otel io.opentelemetry opentelemetry-exporter-otlp org.springframework.ai spring-ai-autoconfigure-model-tool 1.0.0 ``` -------------------------------- ### Image Generation via Tools Source: https://github.com/kehynote/spring-ai-alibaba/blob/main/examples/multimodal/README.md Configures a ReactAgent with a GenerateImageTool to enable creative image generation capabilities. ```java ReactAgent creativeAgent = ReactAgent.builder() .model(chatModel) .methodTools(generateImageTool) .build(); creativeAgent.call("Generate an image of a sunset over mountains"); ```