通过ChatOptions可以在每次请求中控制模型行为:
chatModel.prompt("写一首关于 Java 的诗") .options(o -> o .temperature(0.8) .max_tokens(500) .top_p(0.9) .systemPrompt("你是一位富有创造力的诗人。")) .call();部分常用参数:
| 方法 | 说明 |
|---|---|
temperature(val) | 采样温度(0.0–2.0) |
max_tokens(val) | 最大输出 Token 数 |
top_p(val) | 核采样参数 |
top_k(val) | Top-K 采样 |
frequency_penalty(val) | 降低重复 |
presence_penalty(val) | 鼓励新话题 |
tool_choice(val) | 强制工具调用:none、auto、required或工具名 |
role(val) | Agent 角色(role + instruction 可自动生成 systemPrompt) |
instruction(val) | Agent 指令(role + instruction 可自动生成 systemPrompt) |
systemPrompt(val) | 本次请求的系统提示词(完全定制) |
8. 多消息 Prompt
有时候你需要的不只是一条消息。可以用Prompt和ChatMessage构建更复杂的上下文:
import org.noear.solon.ai.chat.Prompt; import org.noear.solon.ai.chat.message.ChatMessage; Prompt prompt = Prompt.of( ChatMessage.ofUser("Hello, how are you?"), ChatMessage.ofAssistant("Bonjour, comment allez-vous?"), ChatMessage.ofUser("What is your name?") ); ChatResponse resp = chatModel.prompt(prompt).options(o -> o.systemPrompt("你是一名中英翻译专家。")).call();9. 完整实战:知识感知聊天机器人
下面是一个轻量级的 RAG 模式示例——用ChatMessage.ofUserAugment()把上下文注入到 Prompt 中:
import org.noear.solon.ai.chat.ChatModel; import org.noear.solon.ai.chat.ChatResponse; import org.noear.solon.ai.chat.message.ChatMessage; import org.noear.solon.annotation.Component; import org.noear.solon.annotation.Inject; @Component public class KnowledgeChatbot { @Inject ChatModel chatModel; public String answer(String question, String referenceContext) throws Exception { // 将参考上下文与用户问题合并 ChatMessage augmented = ChatMessage.ofUserAugment(question, referenceContext); ChatResponse resp = chatModel.prompt(augmented) .options(o -> o .temperature(0.3) .systemPrompt("你是一个知识渊博的助手。请基于提供的参考资料回答。")) .call(); return resp.getMessage().getContent(); } }这种模式——用上下文增强用户输入,再调用模型——正是 Solon AI 中 RAG(检索增强生成)的基础。
10. 下一步
ChatModel只是入口点。Solon AI 还提供: