开启左侧

agentcope智能体

[复制链接]
米落枫 发表于 2 小时前 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
作者:CSDN博客
  1. # 安装
  2. pip install agentscope
  3. # 或从源码(获取最新特性)git clone https://github.com/agentscope-ai/agentscope.git
  4. cd agentscope && pip install-e.
  5. 运行实时语音Agent示例:
  6. cd examples/agent/realtime_voice_agent
  7. python app.py
  8. # 访问 http://localhost:8080 进行语音对话
  9. 学习文档
  10. https://java.agentscope.io/en/multi-agent/multiagent-debate.html
复制代码
python测试
  1. 安装
  2. pip install deepagents
  3. # 或者用 uv(推荐)
  4. uv add deepagents
  5. 案例使用
  6. testDeepAgent1.py
  7. from deepagents import create_deep_agent
  8. agent = create_deep_agent()
  9. result = agent.invoke({"messages":[{"role":"user", "content":"调研LangGraph并写一份摘要"}]})
  10. testDeepAgent2.py
  11. # pip install -qU deepagents langchain-openai
  12. from deepagents import create_deep_agent
  13. def get_weather(city: str) -> str:
  14.     """Get weather for a given city."""
  15.     return f"It's always sunny in {city}!"
  16. agent = create_deep_agent(model="openai:gpt-5.4",
  17.     tools=[get_weather],
  18.     system_prompt="You are a helpful assistant",
  19. )# Run the agent
  20. agent.invoke({"messages":[{"role":"user", "content":"what is the weather in sf"}]})
复制代码
java测试
  1. 案例一
  2. <dependency><groupId>io.agentscope</groupId><artifactId>agentscope</artifactId><version>1.0.11</version></dependency>
  3. ReActAgent agent = ReActAgent.builder()
  4.     .name("Assistant")
  5.     .sysPrompt("You are a helpful AI assistant.")
  6.     .model(DashScopeChatModel.builder()
  7.         .apiKey(System.getenv("DASHSCOPE_API_KEY"))
  8.         .modelName("qwen-max")
  9.         .build())
  10.     .build();
  11. Msg response = agent.call(Msg.builder()
  12.         .textContent("Hello!")
  13.         .build()).block();
  14. System.out.println(response.getTextContent());
  15. 案例二
  16. <dependencies><dependency><groupId>io.agentscope</groupId><artifactId>agentscope</artifactId><version>1.0.9</version></dependency></dependencies>import io.agentscope.core.model.DashScopeChatModel;
  17. public class ModelFactory {
  18.     public static DashScopeChatModel createQwenModel(){
  19.         String apiKey = System.getenv("DASHSCOPE_API_KEY");if(apiKey == null || apiKey.isBlank()){
  20.             throw new IllegalStateException("DASHSCOPE_API_KEY is required");}return DashScopeChatModel.builder()
  21.                 .apiKey(apiKey)
  22.                 .modelName("qwen-plus")
  23.                 //.modelName("gpt-4o")
  24.                 //.generateOptions(GenerateOptions.builder().temperature(0.2).build())
  25.                 .build();}}
  26. 简单输出
  27. import io.agentscope.core.ReActAgent;import io.agentscope.core.message.Msg;import io.agentscope.core.model.DashScopeChatModel;
  28. public class SimpleAgentDemo {
  29.     public static void main(String[] args){
  30.         DashScopeChatModel model = ModelFactory.createQwenModel();
  31.         ReActAgent agent = ReActAgent.builder()
  32.                 .name("Nexus")
  33.                 .sysPrompt("You are a helpful enterprise assistant.")
  34.                 .model(model)
  35.                 .build();
  36.         Msg response = agent.call(
  37.                 Msg.builder()
  38.                         .textContent("你好,请介绍一下 AgentScope 是什么")
  39.                         .build()).block();if(response != null){
  40.             System.out.println(response.getTextContent());}}}
  41. stream流输出
  42. import io.agentscope.core.message.Msg;import io.agentscope.core.message.TextBlock;import io.agentscope.core.model.DashScopeChatModel;import io.agentscope.core.model.GenerateOptions;import reactor.core.publisher.Flux;import java.util.List;
  43. public class StreamDemo {
  44.     public Flux<String> stream(String prompt){
  45.         DashScopeChatModel model = ModelFactory.createQwenModel();
  46.         GenerateOptions options = GenerateOptions.builder()
  47.                 .stream(Boolean.TRUE)
  48.                 .build();return model.stream(
  49.                         List.of(Msg.builder().textContent(prompt).build()),
  50.                         List.of(),
  51.                         options)
  52.                 .map(chatResponse -> chatResponse.getContent().stream()
  53.                         .filter(TextBlock.class::isInstance)
  54.                         .map(TextBlock.class::cast)
  55.                         .map(TextBlock::getText)
  56.                         .reduce("", String::concat))
  57.                 .filter(text -> text != null &&!text.isBlank());}}
  58. @GetMapping(value ="/test", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  59. public Flux<String> test(@RequestParam String message){return qwenResponseComposer.composeTypewriter(message);}
  60. 其他例子
  61. 千问例子
  62. DashScopeChatModel model = DashScopeChatModel.builder()
  63.         .apiKey(System.getenv("DASHSCOPE_API_KEY"))
  64.         .modelName("qwen3-max")
  65.         .enableThinking(true)  // Automatically enables streaming
  66.         .defaultOptions(GenerateOptions.builder()
  67.                 .thinkingBudget(5000)  // Token budget for thinking
  68.                 .build())
  69.         .build();
  70. ollama例子
  71. OllamaChatModel model =
  72.         OllamaChatModel.builder()
  73.                 .modelName("qwen3-max")
  74.                 .baseUrl("http://localhost:11434")
  75.                 .defaultOptions(OllamaOptions.builder()
  76.                         .thinkOption(ThinkOption.ThinkBoolean.ENABLED)
  77.                         .temperature(0.8)
  78.                         .build())
  79.                 .build();
  80. openai例子
  81. OpenAIChatModel model = OpenAIChatModel.builder()
  82.         .apiKey(System.getenv("OPENAI_API_KEY"))
  83.         .modelName("gpt-4o")
  84.         .build();
  85. deepseek例子
  86. OpenAIChatModel model = OpenAIChatModel.builder()
  87.         .apiKey("your-api-key")
  88.         .modelName("deepseek-chat")
  89.         .baseUrl("https://api.deepseek.com")
  90.         .build();
  91. claude例子
  92. AnthropicChatModel model = AnthropicChatModel.builder()
  93.         .apiKey(System.getenv("ANTHROPIC_API_KEY"))
  94.         .modelName("claude-sonnet-4-5-20250929")  // Default
  95.         .build();
  96. Gemini例子
  97. GeminiChatModel model = GeminiChatModel.builder()
  98.         .apiKey(System.getenv("GEMINI_API_KEY"))
  99.         .modelName("gemini-2.5-flash")  // Default
  100.         .baseUrl("https://your-gateway.example")  // Optional
  101.         .build();
  102. Vertex例子
  103. GeminiChatModel model = GeminiChatModel.builder()
  104.         .modelName("gemini-2.0-flash")
  105.         .project("your-gcp-project")
  106.         .location("us-central1")
  107.         .vertexAI(true)
  108.         .credentials(GoogleCredentials.getApplicationDefault())
  109.         .build();
  110. 多智能体写作// 创建模型
  111. DashScopeChatModel model = DashScopeChatModel.builder
  112. .apiKey(apiKey)
  113. .modelName("qwen-plus")
  114. .build;
  115. // 创建多个不同角色的智能体
  116. ReActAgent planner = ReActAgent.builder
  117. .name("规划师")
  118. .sysPrompt("你是一个项目规划专家,擅长制定计划和分解任务。")
  119. .model(model)
  120. .build;
  121. ReActAgent executor = ReActAgent.builder
  122. .name("执行者")
  123. .sysPrompt("你是一个执行专家,擅长将计划转化为具体的执行步骤。")
  124. .model(model)
  125. .build;
  126. ReActAgent reviewer = ReActAgent.builder
  127. .name("审查者")
  128. .sysPrompt("你是一个审查专家,擅长评估和优化方案。")
  129. .model(model)
  130. .build;
  131. System.out.println("\n[多智能体协作]");
  132. String task ="设计一个简单的待办事项管理系统";
  133. // 第一步: 规划师制定计划
  134. System.out.println("任务: "+ task);
  135. System.out.println("\n--- 规划师制定计划 ---");
  136. Msg planRequest = Msg.builder
  137. .textContent("请为以下任务制定一个详细的计划: "+ task)
  138. .build;
  139. Msg plan = planner.call(planRequest).block;
  140. logger.info("规划师: {}", plan.getTextContent);
  141. System.out.println(plan.getTextContent);
  142. // 第二步: 执行者细化执行步骤
  143. Msg executionRequest = Msg.builder
  144. .textContent("基于以下计划,请提供具体的执行步骤:\n"+ plan.getTextContent)
  145. .build;
  146. Msg execution = executor.call(executionRequest).block;
  147. logger.info("执行者: {}", execution.getTextContent);
  148. System.out.println(execution.getTextContent);
  149. // 第三步: 审查者评估方案
  150. Msg reviewRequest = Msg.builder
  151. .textContent("请评估以下执行方案,并提出改进建议:\n"+ execution.getTextContent)
  152. .build;
  153. Msg review = reviewer.call(reviewRequest).block;
  154. logger.info("审查者: {}", review.getTextContent);
  155. System.out.println(review.getTextContent);
  156. 多智能体模型案例
  157. // DashScope multi-agent
  158. DashScopeChatModel model = DashScopeChatModel.builder()
  159.         .apiKey(System.getenv("DASHSCOPE_API_KEY"))
  160.         .modelName("qwen3-max")
  161.         .formatter(new DashScopeMultiAgentFormatter())
  162.         .build();
  163. // OpenAI multi-agent
  164. OpenAIChatModel model = OpenAIChatModel.builder()
  165.         .apiKey(System.getenv("OPENAI_API_KEY"))
  166.         .modelName("gpt-4o")
  167.         .formatter(new OpenAIMultiAgentFormatter())
  168.         .build();
  169. // Anthropic multi-agent
  170. AnthropicChatModel model = AnthropicChatModel.builder()
  171.         .apiKey(System.getenv("ANTHROPIC_API_KEY"))
  172.         .formatter(new AnthropicMultiAgentFormatter())
  173.         .build();
  174. // Gemini multi-agent
  175. GeminiChatModel model = GeminiChatModel.builder()
  176.         .apiKey(System.getenv("GEMINI_API_KEY"))
  177.         .formatter(new GeminiMultiAgentFormatter())
  178.         .build();
  179. // Ollama multi-agent
  180. OllamaChatModel model = OllamaChatModel.builder()
  181.         .modelName("qwen3-max")
  182.         .formatter(new OllamaMultiAgentFormatter())
  183.         .build();
  184. 调用工具
  185. import io.agentscope.core.ReActAgent;import io.agentscope.core.tool.Toolkit;import io.agentscope.core.model.DashScopeChatModel;
  186. // Create model
  187. DashScopeChatModel model = DashScopeChatModel.builder()
  188.         .apiKey(System.getenv("DASHSCOPE_API_KEY"))
  189.         .modelName("qwen-plus")
  190.         .build();
  191. Toolkit toolkit = new Toolkit();
  192. toolkit.registration()
  193.         .subAgent(()-> ReActAgent.builder()
  194.                 .name("Expert")
  195.                 .sysPrompt("You are a domain expert responsible for answering professional questions.")
  196.                 .model(model)
  197.                 .build())
  198.         .apply();
  199. // Create main agent with toolkit
  200. ReActAgent mainAgent = ReActAgent.builder()
  201.         .name("Coordinator")
  202.         .sysPrompt("You are a coordinator. When facing professional questions, call the call_expert tool to consult the expert.")
  203.         .model(model)
  204.         .toolkit(toolkit)
  205.         .build();
  206. // Main agent will automatically call expert agent when needed
  207. Msg response = mainAgent.call(userMsg).block();
  208. // 1. Create knowledge base
  209. EmbeddingModel embeddingModel = DashScopeTextEmbedding.builder()
  210.     .apiKey(System.getenv("DASHSCOPE_API_KEY"))
  211.     .modelName("text-embedding-v3")
  212.     .dimensions(1024)
  213.     .build();
  214. Knowledge knowledge = SimpleKnowledge.builder()
  215.     .embeddingModel(embeddingModel)
  216.     .embeddingStore(InMemoryStore.builder().dimensions(1024).build())
  217.     .build();
  218. // 2. Add documents
  219. TextReader reader = new TextReader(512, SplitStrategy.PARAGRAPH, 50);
  220. List<Document> docs = reader.read(ReaderInput.fromString("Text content...")).block();
  221. knowledge.addDocuments(docs).block();
  222. // 3. Retrieve
  223. List<Document> results = knowledge.retrieve("query",
  224.     RetrieveConfig.builder().limit(3).scoreThreshold(0.5).build()).block();
复制代码
原文地址:https://blog.csdn.net/qq_35911118/article/details/160597964
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

发布主题
阅读排行更多+

Powered by Discuz! X3.4© 2001-2013 Discuz Team.( 京ICP备17022993号-3 )