### Example: Initialize ChatModel with System Prompt for Ollama Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/01-ChatModel-API-参考.md Demonstrates initializing an Ollama ChatModel and setting a system prompt to guide the AI as a programming assistant. ```java ChatModel chatModel = ChatModel.of("http://localhost:11434/api/chat") .provider("ollama") .model("qwen2.5") .systemPrompt("你是一个专业的编程助手,擅长 Java 和 Python") .build(); ``` -------------------------------- ### v2 API Example with Default Configuration Source: https://github.com/opensolon/solon-ai/blob/main/solon-ai-rag-repositorys/solon-ai-repo-chroma/Chroma-API-v1-v2-Difference.md This example shows how to access the collections endpoint using the v2 API with default tenant and database configurations. ```http http://localhost:8000/api/v2/tenants/default_tenant/databases/default_database/collections ``` -------------------------------- ### Full ChatModel Usage Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/01-ChatModel-API-参考.md A comprehensive example demonstrating ChatModel initialization, simple and multi-turn conversations, and tool usage. ```java import org.noear.solon.ai.chat.*; import org.noear.solon.ai.chat.message.*; import java.time.Duration; public class ChatModelExample { public static void main(String[] args) { // 1. 创建模型 ChatModel chatModel = ChatModel.of("http://127.0.0.1:11434/api/chat") .provider("ollama") .model("qwen2.5:1.5b") .systemPrompt("你是一个有用的编程助手") .timeout(Duration.ofSeconds(60)) .build(); // 2. 简单对话 ChatResponse response = chatModel .prompt("请解释什么是反应堆模式(ReAct)") .call(); System.out.println(response.getMessage()); // 3. 多轮对话 List messages = new ArrayList<>(); messages.add(ChatMessage.ofSystem("你是数据分析专家")); messages.add(ChatMessage.ofUser("数据集中有多少行?")); messages.add(ChatMessage.ofAssistant("请提供数据集以便我分析")); messages.add(ChatMessage.ofUser("这是数据集...")); ChatResponse response2 = chatModel .prompt(messages) .call(); // 4. 带工具的对话 response = chatModel .prompt("今天北京的天气如何?") .options(op -> op.toolAdd(new WeatherTool())) .call(); } } ``` -------------------------------- ### Complete YAML Configuration Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/08-配置参考-Configuration.md A comprehensive example of an `application.yml` file showing configurations for Solon AI (chat, embedding, reranking, RAG, agent), Solon Web, Solon Database, and Solon Cache. ```yaml # application.yml solon: app: name: solon-ai-app version: 1.0.0 ai: # 聊天模型配置 chat: apiUrl: https://api.openai.com/v1/chat/completions apiKey: ${OPENAI_API_KEY} provider: openai model: gpt-4-turbo contextLength: 128000 timeout: 60s userAgent: SolonAI/1.0 headers: X-Custom-Header: value # 嵌入模型配置 embedding: apiUrl: http://localhost:11434/api/embed provider: ollama model: bge-m3 batchSize: 50 timeout: 120s # 重排模型配置 reranking: apiUrl: https://api.cohere.com apiKey: ${COHERE_API_KEY} provider: cohere model: rerank-english-v3.0 # RAG 知识库配置 rag: repository: memory # memory, file, redis textSplitter: type: token_size chunkSize: 512 overlap: 50 # 智能体配置 agent: react: maxIterations: 10 timeout: 300s team: protocol: hierarchical # Solon Web 配置 web: port: 8080 mvc: view-prefix: / view-suffix: .html # Solon 数据库配置(用于持久化) datasource: url: jdbc:mysql://localhost:3306/solon_ai username: root password: password driverClassName: com.mysql.cj.jdbc.Driver maxActive: 20 # Solon 缓存配置 cache: default: memory memory: capacity: 10000 ``` -------------------------------- ### Basic Autopilot Pipeline Usage Source: https://github.com/opensolon/solon-ai/blob/main/solon-ai-loop/README.md Demonstrates how to initialize and start an Autopilot pipeline with default configurations. It shows how to create a request, start the pipeline asynchronously, and retrieve HUD information. ```java PipelineConfig pipelineConfig = PipelineConfig.builder() .expansionEnabled(true) .planningEnabled(true) .executionEnabled(true) .qaEnabled(true) .validationEnabled(true) .build(); AutopilotExecutor autopilot = new AutopilotExecutor(engine, pipelineConfig); // 启动 Pipeline AutopilotExecutor.PipelineRequest request = AutopilotExecutor.PipelineRequest.create( java.util.UUID.randomUUID().toString(), "Build feature X"); java.util.concurrent.CompletableFuture future = autopilot.startPipeline(request); // 获取 HUD 信息 String sessionId = request.sessionId; System.out.println(autopilot.formatPipelineHUD(sessionId)); ``` -------------------------------- ### Get Document v2 API Request Example Source: https://github.com/opensolon/solon-ai/blob/main/solon-ai-rag-repositorys/solon-ai-repo-chroma/Chroma-API-v1-v2-Difference.md This example demonstrates how to fetch documents using the v2 API, which includes tenant and database identifiers in the URL. Specify the collection ID, tenant, database, and document IDs. ```http POST http://localhost:8000/api/v2/tenants/default_tenant/databases/default_database/collections/{collection_id}/get Content-Type: application/json { "ids": ["doc1", "doc2"], "include": ["documents", "metadatas"] } ``` -------------------------------- ### Complete RAG Pipeline Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/05-RAG-知识库-API-参考.md Demonstrates the full RAG workflow, including document loading, splitting, embedding, storage, retrieval, reranking, and response generation with a chat model. This example requires setting up local Ollama services for embedding and chat models, and a PDF file named 'knowledge.pdf' in the same directory. ```java import org.noear.solon.ai.embedding.*; import org.noear.solon.ai.rag.*; import org.noear.solon.ai.rag.repository.*; import org.noear.solon.ai.rag.loader.*; import org.noear.solon.ai.rag.splitter.*; import org.noear.solon.ai.chat.*; import org.noear.solon.ai.chat.message.*; import java.io.IOException; import java.util.*; public class RAGExample { public static void main(String[] args) throws IOException { // 1. 创建嵌入模型 EmbeddingModel embeddingModel = EmbeddingModel.of("http://localhost:11434/api/embed") .provider("ollama") .model("bge-m3") .batchSize(10) .build(); // 2. 创建文本分割器 TextSplitter splitter = new TokenSizeTextSplitter(512, 50); // 3. 创建知识库 Repository repository = new InMemoryRepository(embeddingModel); // 4. 加载文档 System.out.println("正在加载文档..."); List allDocs = new PdfLoader("knowledge.pdf").load(); // 分割文档 List splitDocs = new ArrayList<>(); for (Document doc : allDocs) { List chunks = splitter.split(doc.getContent()); for (String chunk : chunks) { splitDocs.add(new Document( doc.getTitle(), chunk, doc.getMetadata() )); } } // 5. 插入知识库 repository.insert(splitDocs); System.out.println("已插入 " + repository.count() + " 个文档"); // 6. 创建重排模型(可选) RerankingModel rerankingModel = RerankingModel.of("https://api.cohere.com") .apiKey("your-api-key") .model("rerank-english-v3.0") .build(); // 7. 创建聊天模型 ChatModel chatModel = ChatModel.of("http://localhost:11434/api/chat") .provider("ollama") .model("qwen2.5:1.5b") .systemPrompt("你是一个基于知识库的专家助手。使用提供的参考信息回答问题。") .build(); // 8. 处理用户查询 String userQuery = "如何优化数据库查询性能?"; // 搜索相关文档 List searchResults = repository.search(userQuery, 10); // 使用重排模型排序 List rerankedResults = rerankingModel.rerank(userQuery, searchResults); System.out.println("\n=== 搜索结果 ==="); for (int i = 0; i < Math.min(3, rerankedResults.size()); i++) { Document doc = rerankedResults.get(i); System.out.println((i + 1) + ". " + doc.getTitle()); System.out.println(" " + doc.getContent().substring(0, 100) + "..."); } // 9. 增强用户消息 UserMessage augmentedMessage = ChatMessage.ofUserAugment(userQuery, rerankedResults); // 10. 调用 LLM 生成回复 System.out.println("\n=== AI 回复 ==="); ChatResponse response = chatModel .prompt(augmentedMessage) .call(); System.out.println(response.getMessage().getContent()); // 11. 可选:多轮对话 List messages = new ArrayList<>(); messages.add(ChatMessage.ofSystem("你是基于知识库的专家")); messages.add(augmentedMessage); messages.add(response.getMessage()); String followUp = "还有其他优化建议吗?"; List followUpResults = repository.search(followUp, 5); messages.add(ChatMessage.ofUser(followUp)); ChatResponse response2 = chatModel .prompt(messages) .call(); System.out.println("\n=== 后续回复 ==="); System.out.println(response2.getMessage().getContent()); } } ``` -------------------------------- ### Basic Chat with ChatModel Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/00-目录和导览.md Demonstrates how to initialize and use the ChatModel for basic text prompting. Refer to API and Quickstart guides for more details. ```java // 详见: 01-ChatModel-API-参考.md 和 10-快速入门指南.md ChatModel chatModel = ChatModel.of(apiUrl) .provider("ollama") .model("qwen2.5") .build(); ChatResponse response = chatModel.prompt("你好").call(); ``` -------------------------------- ### Full Agent API Usage Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Demonstrates the creation of a basic chat model, a single ReAct agent with tools, and a team of agents. Includes examples of executing agents, calling team tasks, and handling streaming responses. ```java import org.noear.solon.ai.chat.*; import org.noear.solon.ai.agent.react.*; import org.noear.solon.ai.agent.team.*; import org.noear.solon.ai.chat.tool.*; public class AgentExample { public static void main(String[] args) { // 1. 创建基础聊天模型 ChatModel chatModel = ChatModel.of("http://127.0.0.1:11434/api/chat") .provider("ollama") .model("qwen2.5:1.5b") .build(); // 2. 创建单个 ReAct 智能体 ReActAgent weatherAgent = ReActAgent.of(chatModel) .name("weather_expert") .role("天气查询专家,能查询全球任何地点的天气") .defaultToolAdd(new WeatherTool()) .build(); // 3. 执行智能体 ReActResponse response = weatherAgent .prompt("请告诉我北京未来一周的天气预报") .call(); System.out.println("结果: " + response.getText()); // 4. 创建团队智能体 ReActAgent planner = ReActAgent.of(chatModel) .name("planner") .role("项目计划专家") .defaultToolAdd(new PlanningTools()) .build(); ReActAgent developer = ReActAgent.of(chatModel) .name("developer") .role("开发工程师") .defaultToolAdd(new DevelopmentTools()) .build(); TeamAgent team = TeamAgent.of(chatModel) .name("project_team") .role("项目交付团队") .protocol(TeamProtocols.HIERARCHICAL) .agentAdd(planner) .agentAdd(developer) .build(); // 5. 执行团队任务 TeamResponse teamResponse = team .prompt("规划并实现一个用户认证系统") .call(); System.out.println("团队结果: " + teamResponse.getText()); // 6. 流式执行 weatherAgent.stream( weatherAgent.prompt("天气如何?"), chunk -> { if (chunk instanceof ThoughtChunk) { System.out.println("思考: " + ((ThoughtChunk) chunk).getContent()); } else if (chunk instanceof ActionChunk) { System.out.println("行动: " + ((ActionChunk) chunk).getToolCall()); } } ); } } ``` -------------------------------- ### Example: Initialize ChatModel with different providers Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/01-ChatModel-API-参考.md Shows how to initialize ChatModel instances for both Ollama and OpenAI, specifying their respective provider details. ```java ChatModel ollama = ChatModel.of("http://localhost:11434/api/chat") .provider("ollama") .model("qwen2.5") .build(); ChatModel openai = ChatModel.of("https://api.openai.com/v1/chat/completions") .provider("openai") .apiKey("sk-...") .model("gpt-4") .build(); ``` -------------------------------- ### MCP Resource URI Format Examples Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/07-MCP-集成-API-参考.md Illustrates the structure of resource URIs used in MCP, showing examples for databases, files, and APIs. ```plaintext resource://domain/path?param=value 示例: - resource://database/users/123 - resource://files/documents/report.pdf - resource://api/weather?city=beijing ``` -------------------------------- ### MCP Server Implementation Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/07-MCP-集成-API-参考.md Example of an MCP server implementation using annotations to define tools, resources, and prompts. Supports WebSocket communication. ```java import org.noear.solon.ai.mcp.annotation.*; @McpServerEndpoint(channel = McpChannel.STREAMABLE, mcpEndpoint = "/mcp") public class MyMcpServer { // 定义工具 @ToolMapping(description = "查询天气信息") public String getWeather( @Param(description = "城市名称") String city ) { return "天气: 晴朗, 温度: 25°C"; } // 定义资源 @ResourceMapping(uri = "file://documents", description = "文档资源") public String getDocument( @Param(description = "文档 ID") String docId ) { return "文档内容..."; } // 定义提示 @PromptMapping(name = "coding_expert", description = "编程专家提示词") public String getCodingPrompt() { return "你是一个高级编程专家..."; } } ``` -------------------------------- ### Initialize HarnessEngine with Core Configurations Source: https://github.com/opensolon/solon-ai/blob/main/www/1427-harness-配置参考.md Example of initializing HarnessEngine with essential settings like workspace, system prompt, session window size, and tool permissions. ```java HarnessEngine engine = HarnessEngine.of("work", ".soloncode/") .systemPrompt("你是一个 AI 助手") .sessionWindowSize(8) .compressionThreshold(30, 30_000) .toolsAdd(ToolPermission.TOOL_ALL_FULL) // 设定工具权限 .build(); ``` -------------------------------- ### Example: Initialize ChatModel with Ollama Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/01-ChatModel-API-参考.md Demonstrates initializing a ChatModel for use with Ollama, setting the API URL, provider, model, and API key. ```java ChatModel chatModel = ChatModel.of("http://127.0.0.1:11434/api/chat") .provider("ollama") .model("qwen2.5:1.5b") .apiKey("your-api-key") .build(); ``` -------------------------------- ### Execute ReActAgent Synchronously Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Example of initializing a ReActAgent with a calculator tool and then using the `call` method to get a synchronous response to a math problem. ```java ReActAgent agent = ReActAgent.of(chatModel) .name("math_solver") .role("数学问题求解器") .defaultToolAdd(new CalculatorTool()) .build(); ReActResponse response = agent .prompt("计算 sqrt(2) + sqrt(3) 的和,精确到小数点后 4 位") .call(); System.out.println(response.getText()); ``` -------------------------------- ### Example: Set specific model for OpenAI Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/01-ChatModel-API-参考.md Demonstrates setting a specific model, 'gpt-4-turbo', for an OpenAI ChatModel. ```java chatModel = ChatModel.of("http://api.example.com") .provider("openai") .model("gpt-4-turbo") .build(); ``` -------------------------------- ### Solon AI Configuration Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/00-目录和导览.md Example configuration for Solon AI chat and embedding services, specifying API URLs, providers, and models. Useful for setting up LLM interactions. ```yaml solon: ai: chat: apiUrl: http://localhost:11434/api/chat provider: ollama model: qwen2.5:1.5b embedding: apiUrl: http://localhost:11434/api/embed provider: ollama model: bge-m3 ``` -------------------------------- ### Example: Configure DashScope Model Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md An example of configuring an embedding model using the DashScope provider, specifying the API URL and model identifier. ```java EmbeddingModel model = EmbeddingModel.of("http://api.example.com") .provider("dashscope") .model("text-embedding-v2") .build(); ``` -------------------------------- ### OrderToolProvider Implementation Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/06-Tool-工具系统-API-参考.md An example implementation of the ToolProvider interface, providing a predefined set of order-related tools. ```APIDOC ### 自定义工具提供者 ```java public class OrderToolProvider implements ToolProvider { @Override public List getTools() { return Arrays.asList( new CreateOrderTool(), new QueryOrderTool(), new UpdateOrderTool(), new CancelOrderTool() ); } } ``` ``` -------------------------------- ### Example: Initialize ChatModel with OpenAI API Key Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/01-ChatModel-API-参考.md Shows how to initialize an OpenAI ChatModel, including setting the API URL, provider, model, and the API key. ```java ChatModel chatModel = ChatModel.of("https://api.openai.com/v1/chat/completions") .provider("openai") .model("gpt-4") .apiKey("sk-proj-...") .build(); ``` -------------------------------- ### Streaming Request Example Source: https://github.com/opensolon/solon-ai/blob/main/www/1429-harness-调用与流式请求.md Shows how to initiate a streaming request using the Harness engine. Use this when you need to process responses incrementally. ```java HarnessEngine engine = HarnessEngine.of(...) .sessionProvider(sessionProvider) .build(); engine.prompt("hello").stream(); ``` -------------------------------- ### Solon AI SDK Part Class Usage Source: https://github.com/opensolon/solon-ai/blob/main/solon-ai-ui/solon-ai-ui-aisdk/README.md Demonstrates how to manually construct and serialize Part objects for custom stream processing. Includes examples for text deltas, reasoning starts, and custom data parts. ```java import org.noear.solon.ai.ui.aisdk.part.text.*; import org.noear.solon.ai.ui.aisdk.part.reasoning.*; import org.noear.solon.ai.ui.aisdk.part.*; // 构建 Part 并序列化 String json = new TextDeltaPart("txt_001", "Hello").toJson(); // → {"type":"text-delta","id":"txt_001","delta":"Hello"} String json2 = new ReasoningStartPart("rsn_001").toJson(); // → {"type":"reasoning-start","id":"rsn_001"} // 使用 ID 生成器创建带前缀的 ID AiSdkIdGenerator gen = AiSdkIdGenerator.DEFAULT; String json3 = new TextStartPart(gen.ofText()).toJson(); // → {"type":"text-start","id":"txt_a1b2c3d4e5f6"} // 自定义数据 Part String json4 = DataPart.of("weather", Map.of("temp", 72)).toJson(); // → {"type":"data-weather","data":{"temp":72}} ``` -------------------------------- ### Initialize ReActAgent with Builder Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Example of initializing a ReActAgent with a name, role, description, and a default tool using the builder pattern. ```java ReActAgent agent = ReActAgent.of(chatModel) .name("weather_expert") .role("天气查询专家") .description("能够查询全球任何地点的天气信息") .defaultToolAdd(new WeatherTool()) .build(); ``` -------------------------------- ### Initialize ReActAgent with Multiple Tools Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Example of initializing a ReActAgent and adding multiple tools for order processing using the `defaultToolAdd` method. ```java ReActAgent agent = ReActAgent.of(chatModel) .name("order_assistant") .role("订单处理助手") .defaultToolAdd( new QueryOrderTool(), new UpdateOrderTool(), new SendNotificationTool() ) .build(); ``` -------------------------------- ### Initialize ReActAgent with Multi-line Role Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Example of initializing a ReActAgent, setting its name and a multi-line role description using the builder. ```java ReActAgent agent = ReActAgent.of(chatModel) .name("code_reviewer") .role("" 高级代码审查专家 - 熟悉多种编程语言和最佳实践 - 能够识别性能问题和安全漏洞 - 提供清晰的改进建议 """) .build(); ``` -------------------------------- ### Initialize ReActAgent with Name Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Example of initializing a ReActAgent, setting its name and role using the builder. ```java agent = ReActAgent.of(chatModel) .name("data_analyst") .role("数据分析师") .build(); ``` -------------------------------- ### Synchronous Call Example Source: https://github.com/opensolon/solon-ai/blob/main/www/1429-harness-调用与流式请求.md Demonstrates how to perform a synchronous 'call' request using the Harness engine. This is suitable for immediate responses. ```java HarnessEngine engine = HarnessEngine.of(...) .sessionProvider(sessionProvider) .build(); engine.prompt("hello").call(); ``` -------------------------------- ### SimpleAgent Usage Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Demonstrates how to instantiate and use a SimpleAgent to make a prompt call and print the response text. Requires a ChatModel instance. ```java SimpleAgent agent = SimpleAgent.of(chatModel) .name("chatbot") .role("友好的聊天机器人") .build(); SimpleResponse response = agent .prompt("你好,请告诉我关于 Java 的信息") .call(); System.out.println(response.getText()); ``` -------------------------------- ### Example: Configure OpenAI and Ollama Models Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md Shows how to configure both OpenAI and Ollama embedding models using the builder, including setting API keys for OpenAI. ```java // OpenAI 嵌入 EmbeddingModel openaiModel = EmbeddingModel.of("https://api.openai.com/v1/embeddings") .provider("openai") .apiKey("sk-...") .model("text-embedding-3-small") .build(); // Ollama 嵌入 EmbeddingModel ollamaModel = EmbeddingModel.of("http://localhost:11434/api/embed") .provider("ollama") .model("bge-m3") .build(); ``` -------------------------------- ### MCP Server Endpoint and Client Configuration Source: https://github.com/opensolon/solon-ai/blob/main/README_CN.md Provides examples for setting up an MCP server endpoint with tool mappings and configuring an MCP client provider to connect to the server. ```java //服务端 @McpServerEndpoint(channel = McpChannel.STREAMABLE, mcpEndpoint = "/mcp") public class MyMcpServer { @ToolMapping(description = "查询天气") public String getWeather(@Param(description = "城市") String location) { return "晴,25度"; } } //客户端 McpClientProvider clientProvider = McpClientProvider.builder() .channel(McpChannel.STREAMABLE) .url("http://localhost:8080/mcp") .build(); ``` -------------------------------- ### Custom OrderToolProvider Implementation Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/06-Tool-工具系统-API-参考.md An example implementation of ToolProvider that provides a specific set of order-related tools. ```java public class OrderToolProvider implements ToolProvider { @Override public List getTools() { return Arrays.asList( new CreateOrderTool(), new QueryOrderTool(), new UpdateOrderTool(), new CancelOrderTool() ); } } ``` -------------------------------- ### RerankingModel Usage Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/05-RAG-知识库-API-参考.md Demonstrates initializing RerankingModel with API details, performing an initial search, and then reranking the results. ```java RerankingModel rerankingModel = RerankingModel.of("https://api.cohere.com") .apiKey("api_key") .model("rerank-english-v3.0") .build(); // 初步搜索 String query = "什么是机器学习?"; List results = repository.search(query, 10); // 使用重排模型精确排序 List rerankedResults = rerankingModel.rerank(query, results); // 使用重排后的结果增强 prompt UserMessage augmented = ChatMessage.ofUserAugment(query, rerankedResults); ``` -------------------------------- ### TokenSizeTextSplitter Usage Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/05-RAG-知识库-API-参考.md Demonstrates how to use TokenSizeTextSplitter to split long text into chunks and insert them as documents. ```java TextSplitter splitter = new TokenSizeTextSplitter( 512, // 每个块 512 个 Token 50 // 块之间重叠 50 个 Token ); String longText = "...长文本内容..."; List chunks = splitter.split(longText); for (String chunk : chunks) { Document doc = new Document("分割文本", chunk, new HashMap<>()); repository.insert(doc); } ``` -------------------------------- ### Example: Create UserMessage with Metadata Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/02-ChatMessage-类型参考.md Demonstrates creating a `UserMessage` and chaining `addMetadata` calls to attach request-specific information like IDs, types, and timestamps. ```java UserMessage msg = ChatMessage.ofUser("分析数据") .addMetadata("request_id", UUID.randomUUID().toString()) .addMetadata("user_type", "premium") .addMetadata("timestamp", System.currentTimeMillis()); String requestId = msg.getMetadataAs("request_id"); ``` -------------------------------- ### Example: Build Ollama Embedding Model Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md Demonstrates how to use the builder to create an EmbeddingModel instance for Ollama, specifying the API URL, provider, and model. ```java EmbeddingModel model = EmbeddingModel.of("http://127.0.0.1:11434/api/embed") .provider("ollama") .model("bge-m3") .build(); ``` -------------------------------- ### Statically Register LSP Server During Build Source: https://github.com/opensolon/solon-ai/blob/main/www/1438-harness-LSP服务接入.md Register a specific LSP server (e.g., for Java) when building the HarnessEngine. This makes the LSP service available from the start. ```java HarnessEngine engine = HarnessEngine.of("work", ".soloncode/") .sessionProvider(sessionProvider) .toolsAdd(ToolPermission.TOOL_LSP) .lspServerAdd("java", lspServerParameters) .build(); ``` -------------------------------- ### Get Document v1 API Request Example Source: https://github.com/opensolon/solon-ai/blob/main/solon-ai-rag-repositorys/solon-ai-repo-chroma/Chroma-API-v1-v2-Difference.md Use this example to retrieve documents from a collection using the v1 API. It requires the collection ID and a list of document IDs. ```http POST http://localhost:8000/api/v1/collections/{collection_id}/get Content-Type: application/json { "ids": ["doc1", "doc2"], "include": ["documents", "metadatas"] } ``` -------------------------------- ### Get Document (v1 vs v2) Source: https://github.com/opensolon/solon-ai/blob/main/solon-ai-rag-repositorys/solon-ai-repo-chroma/Chroma-API-v1-v2-Difference.md This section details how to retrieve documents using both v1 and v2 of the Chroma API. It highlights the differences in the endpoint paths and provides example request bodies. ```APIDOC ## POST /api/v1/collections/{collection_id}/get ### Description Retrieves documents from a collection by their IDs using the v1 API. ### Method POST ### Endpoint /api/v1/collections/{collection_id}/get ### Parameters #### Request Body - **ids** (array[string]) - Required - A list of document IDs to retrieve. - **include** (array[string]) - Optional - Specifies which parts of the document to include in the response (e.g., "documents", "metadatas"). ### Request Example ```json { "ids": ["doc1", "doc2"], "include": ["documents", "metadatas"] } ``` ## POST /api/v2/tenants/{tenant}/databases/{database}/collections/{collection_id}/get ### Description Retrieves documents from a collection by their IDs using the v2 API, with support for tenant and database context. ### Method POST ### Endpoint /api/v2/tenants/{tenant}/databases/{database}/collections/{collection_id}/get ### Parameters #### Path Parameters - **tenant** (string) - Required - The tenant identifier. - **database** (string) - Required - The database identifier. - **collection_id** (string) - Required - The ID of the collection. #### Request Body - **ids** (array[string]) - Required - A list of document IDs to retrieve. - **include** (array[string]) - Optional - Specifies which parts of the document to include in the response (e.g., "documents", "metadatas"). ### Request Example ```json { "ids": ["doc1", "doc2"], "include": ["documents", "metadatas"] } ``` ``` -------------------------------- ### Configure ChatModel via Java Builder Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/08-配置参考-Configuration.md Example of configuring a ChatModel using the Java builder pattern. This method allows programmatic setup of API endpoints, keys, model details, and performance parameters. ```java ChatModel chatModel = ChatModel.of("https://api.openai.com/v1/chat/completions") .apiKey("sk-...") .provider("openai") .model("gpt-4-turbo") .contextLength(128000) .timeout(Duration.ofSeconds(60)) .userAgent("MyApp/1.0") .headerSet("X-Custom-Header", "value") .build(); ``` -------------------------------- ### Setting Environment Variables and Launching Application Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/08-配置参考-Configuration.md Demonstrates how to set specific environment variables for API keys and batch sizes, and then launch the Solon application. This is a common pattern for runtime configuration. ```bash # 设置环境变量 export SOLON_AI_CHAT_APIKEY="sk-..." export SOLON_AI_EMBEDDING_BATCHSIZE="100" # 启动应用 java -jar solon-app.jar ``` -------------------------------- ### AgentSessionProvider and Agent Initialization Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Demonstrates how to configure an Agent with a session provider and initialize it for conversational use. ```java AgentSessionProvider sessionProvider = () -> new InMemoryAgentSession(); ReActAgent agent = ReActAgent.of(chatModel) .name("assistant") .role("个人助手") .sessionProvider(sessionProvider) .build(); ``` -------------------------------- ### Full EmbeddingModel Usage Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md A comprehensive example showcasing single and batch embeddings, fine-grained control with the builder, and RAG integration. ```java import org.noear.solon.ai.embedding.*; import org.noear.solon.ai.rag.*; import java.io.IOException; import java.util.*; public class EmbeddingModelExample { public static void main(String[] args) throws IOException { // 1. 创建嵌入模型 EmbeddingModel model = EmbeddingModel.of("http://127.0.0.1:11434/api/embed") .provider("ollama") .model("bge-m3") .batchSize(10) .build(); // 2. 单个文本嵌入 float[] embedding = model.embed("机器学习是人工智能的重要分支"); System.out.println("向量维度: " + embedding.length); // 3. 批量嵌入 List texts = Arrays.asList( "深度学习改变了计算机视觉", "自然语言处理在文本分析中很重要", "强化学习用于游戏 AI" ); List embeddings = model.embed(texts); System.out.println("嵌入数量: " + embeddings.size()); // 4. 使用构建器进行更精细的控制 EmbeddingResponse response = model .input(texts) .options(op -> op.batchSize(5)) .call(); List data = response.getData(); System.out.println("返回数据数量: " + data.size()); // 5. 与知识库集成 InMemoryRepository repository = new InMemoryRepository(model); // 添加文档到知识库 Document doc1 = new Document("标题1", "这是文档1的内容...", new HashMap<>()); Document doc2 = new Document("标题2", "这是文档2的内容...", new HashMap<>()); repository.insert(Arrays.asList(doc1, doc2)); // 搜索相似文档 String query = "关键词搜索"; List searchResults = repository.search(query); System.out.println("搜索结果数量: " + searchResults.size()); } } ``` -------------------------------- ### Example: Configure OpenAI Model with API Key Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md Demonstrates setting up an OpenAI embedding model by providing the API endpoint, provider, model name, and the necessary API key. ```java EmbeddingModel model = EmbeddingModel.of("https://api.openai.com/v1/embeddings") .provider("openai") .model("text-embedding-3-small") .apiKey("sk-proj-...") .build(); ``` -------------------------------- ### Agent Initialization with Interceptor Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/03-Agent-API-参考.md Shows how to build a ReActAgent and add a custom interceptor, such as a logging interceptor, to customize its behavior. ```java ReActAgent agent = ReActAgent.of(chatModel) .name("smart_agent") .role("智能助手") .interceptorAdd(loggingInterceptor) .build(); ``` -------------------------------- ### Example: Reduce Embedding Dimension Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md This example shows how to configure an OpenAI embedding model to output vectors with a reduced dimension of 256, saving storage space. ```java // 使用降维嵌入节省存储空间 EmbeddingModel model = EmbeddingModel.of("https://api.openai.com/v1/embeddings") .provider("openai") .apiKey("sk-...") .model("text-embedding-3-large") .dimension(256) // 从 3072 维降低到 256 维 .build(); ``` -------------------------------- ### Delete Document v1 API Request Example Source: https://github.com/opensolon/solon-ai/blob/main/solon-ai-rag-repositorys/solon-ai-repo-chroma/Chroma-API-v1-v2-Difference.md Example for deleting documents from a collection using the v1 API. Provide the collection ID and the IDs of the documents to be removed. ```http POST http://localhost:8000/api/v1/collections/{collection_id}/delete Content-Type: application/json { "ids": ["doc1", "doc2"] } ``` -------------------------------- ### Create and Use STDIO Channel Client Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/07-MCP-集成-API-参考.md Demonstrates how to build an McpClientProvider using the STDIO channel for connecting to a local MCP server process. Shows how to retrieve remote tools and integrate them with a ChatModel. ```java McpClientProvider clientProvider = McpClientProvider.builder() .channel(McpChannel.STDIO) .stdio("java -jar mcp-server.jar") .build(); // 获取远程工具 List tools = clientProvider.getTools(); // 在聊天模型中使用 ChatModel chatModel = ChatModel.of("http://localhost:11434/api/chat") .provider("ollama") .model("qwen2.5") .defaultToolAdd(tools) .build(); ChatResponse response = chatModel.prompt("请执行远程工具").call(); ``` -------------------------------- ### Initialize HarnessEngine with MountDirs Source: https://github.com/opensolon/solon-ai/blob/main/www/1430-harness-目录结构与挂载机制.md Initializes the HarnessEngine with specified workspace and harness home, and adds custom mount directories for agents and skills. The mount directories are defined with aliases, types, physical paths, and write permissions. ```java HarnessEngine engine = HarnessEngine.of("work", ".soloncode/") .sessionProvider(sessionProvider) .mountAdd(MountDir.builder() .alias("@global-agents") // 虚拟别名,须以 @ 开头 .type(MountType.AGENTS) // 挂载类型 .path("~/.soloncode/agents/") // 物理路径 .primary(true) // 原始挂载(不可删除) .writeable(false) // 是否可写(默认只读) .build()) .mountAdd(MountDir.builder() .alias("@global-skills") .type(MountType.SKILLS) .path("~/.soloncode/skills/") .build()) .build(); ``` -------------------------------- ### Example: Batch Processing with Large Batch Size Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md This example demonstrates setting a batch size of 50 for an Ollama embedding model and illustrates how it would process a large list of texts in multiple batches. ```java EmbeddingModel model = EmbeddingModel.of("http://localhost:11434/api/embed") .provider("ollama") .model("bge-m3") .batchSize(50) // 每批处理 50 个文本 .build(); List texts = new ArrayList<>(); // 添加 1000 个文本... List embeddings = model.embed(texts); // 分 20 批处理 ``` -------------------------------- ### Switching Application Environments Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/08-配置参考-Configuration.md Use command-line arguments to activate specific Solon profiles for development or production environments. ```bash # 开发环境 java -jar app.jar --solon.profiles.active=dev # 生产环境 java -jar app.jar --solon.profiles.active=prod ``` -------------------------------- ### Delete Document v2 API Request Example Source: https://github.com/opensolon/solon-ai/blob/main/solon-ai-rag-repositorys/solon-ai-repo-chroma/Chroma-API-v1-v2-Difference.md This example shows how to delete documents with the v2 API. The URL includes tenant and database identifiers. Specify the collection ID and the document IDs to delete. ```http POST http://localhost:8000/api/v2/tenants/default_tenant/databases/default_database/collections/{collection_id}/delete Content-Type: application/json { "ids": ["doc1", "doc2"] } ``` -------------------------------- ### Create and Use HTTP Channel Client Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/07-MCP-集成-API-参考.md Illustrates setting up an McpClientProvider for an HTTP channel to connect to an MCP endpoint. Shows how to fetch a specific remote tool and use it within a ChatModel prompt. ```java McpClientProvider httpClient = McpClientProvider.builder() .channel(McpChannel.HTTP) .url("http://mcp-service:8080/mcp") .build(); // 访问远程工具 FunctionTool tool = httpClient.getTool("weather_tool"); // 在请求中使用 ChatResponse response = chatModel .prompt("查询天气") .options(op -> op.toolAdd(tool)) .call(); ``` -------------------------------- ### Using ToolProvider with ChatModel Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/06-Tool-工具系统-API-参考.md Demonstrates how to configure a ChatModel with a custom tool provider and make a prompt call. ```java ChatModel chatModel = ChatModel.of("http://localhost:11434/api/chat") .provider("ollama") .model("qwen2.5") .defaultToolAdd(new OrderToolProvider()) .build(); ChatResponse response = chatModel .prompt("帮我创建一个订单") .call(); ``` -------------------------------- ### get(String docId) Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/05-RAG-知识库-API-参考.md Retrieves a specific document from the knowledge base by its unique document ID. ```APIDOC ## get(String docId) ### Description Retrieves a specific document from the knowledge base by its unique document ID. ### Method ```java Document get(String docId) throws IOException ``` ### Parameters #### Path Parameters - **docId** (String) - Required - The unique identifier of the document to retrieve. ### Response #### Success Response - **Document** - The document object corresponding to the provided ID. #### Error Response - **IOException**: Thrown if the get operation fails or the document is not found. ``` -------------------------------- ### RAG Integration Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md Demonstrates how to integrate the EmbeddingModel with a Retrieval-Augmented Generation (RAG) system using a repository. ```APIDOC ## RAG Integration Example ### Description This example illustrates how to use the `EmbeddingModel` to create and interact with a RAG knowledge base. It covers loading documents, inserting them into a repository, searching for relevant documents, and augmenting user queries. ### Steps 1. **Create Embedding Model**: Instantiate `EmbeddingModel` with provider and model details. 2. **Create Repository**: Initialize a `InMemoryRepository` with the `EmbeddingModel`. 3. **Load and Insert Documents**: Use a loader (e.g., `PdfLoader`) to load documents and insert them into the repository. 4. **Search Documents**: Perform a search query against the repository to find similar documents. 5. **Augment User Message**: Create an augmented user message by combining the original query with the retrieved documents. 6. **Pass to LLM**: Send the augmented message to a chat model for generation. ### Request Example ```java // Create embedding model EmbeddingModel embeddingModel = EmbeddingModel.of("http://localhost:11434/api/embed") .provider("ollama") .model("bge-m3") .batchSize(10) .build(); // Create repository InMemoryRepository repository = new InMemoryRepository(embeddingModel); // Load and process documents repository.insert(new PdfLoader("documents.pdf").load()); // Search for similar documents String query = "如何优化数据库性能?"; List results = repository.search(query); // Augment user message with search results UserMessage augmented = ChatMessage.ofUserAugment(query, results); // Pass to LLM chatModel.prompt(augmented).call(); ``` ``` -------------------------------- ### RAG Integration Example Source: https://github.com/opensolon/solon-ai/blob/main/_autodocs/04-EmbeddingModel-API-参考.md Demonstrates integrating EmbeddingModel with a RAG knowledge base for document loading and searching. ```java // 创建嵌入模型 EmbeddingModel embeddingModel = EmbeddingModel.of("http://localhost:11434/api/embed") .provider("ollama") .model("bge-m3") .batchSize(10) .build(); // 创建知识库 InMemoryRepository repository = new InMemoryRepository(embeddingModel); // 加载和处理文档 repository.insert(new PdfLoader("documents.pdf").load()); // 搜索相似文档 String query = "如何优化数据库性能?"; List results = repository.search(query); // 使用搜索结果增强用户消息 UserMessage augmented = ChatMessage.ofUserAugment(query, results); // 传给 LLM chatModel.prompt(augmented).call(); ``` -------------------------------- ### Dynamically Manage Mounts in HarnessEngine Source: https://github.com/opensolon/solon-ai/blob/main/www/1430-harness-目录结构与挂载机制.md Demonstrates how to dynamically add, check, refresh, and remove mount directories from the Harness engine at runtime. It also shows how to retrieve all mounts, skills, and agents, including those specific to a mount. ```java engine.addMount(MountDir.builder() .alias("@team-skills") .type(MountType.SKILLS) .path("~/team/skills/") .build()); // 添加挂载 ``` ```java engine.hasMount("@team-skills"); // 是否存在 ``` ```java engine.refreshMount("@team-skills"); // 刷新(重新扫描该挂载) ``` ```java engine.refreshMount(null); // 刷新全部自定义代理 ``` ```java engine.removeMount("@team-skills"); // 移除(primary 的不可移除) ``` ```java engine.getMounts(); // 全部挂载 ``` ```java engine.getSkills(); // 全部技能 ``` ```java engine.getSkillsByMount("@global-skills"); ``` ```java engine.getAgents(); // 全部子代理 ``` ```java engine.getAgentsByMount("@global-agents"); ```