AI创想
标题:
agentcope智能体
[打印本页]
作者:
米落枫
时间:
3 小时前
标题:
agentcope智能体
作者:CSDN博客
# 安装
pip install agentscope
# 或从源码(获取最新特性)git clone https://github.com/agentscope-ai/agentscope.git
cd agentscope && pip install-e.
运行实时语音Agent示例:
cd examples/agent/realtime_voice_agent
python app.py
# 访问 http://localhost:8080 进行语音对话
学习文档
https://java.agentscope.io/en/multi-agent/multiagent-debate.html
复制代码
python测试
安装
pip install deepagents
# 或者用 uv(推荐)
uv add deepagents
案例使用
testDeepAgent1.py
from deepagents import create_deep_agent
agent = create_deep_agent()
result = agent.invoke({"messages":[{"role":"user", "content":"调研LangGraph并写一份摘要"}]})
testDeepAgent2.py
# pip install -qU deepagents langchain-openai
from deepagents import create_deep_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_deep_agent(model="openai:gpt-5.4",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)# Run the agent
agent.invoke({"messages":[{"role":"user", "content":"what is the weather in sf"}]})
复制代码
java测试
案例一
<dependency><groupId>io.agentscope</groupId><artifactId>agentscope</artifactId><version>1.0.11</version></dependency>
ReActAgent agent = ReActAgent.builder()
.name("Assistant")
.sysPrompt("You are a helpful AI assistant.")
.model(DashScopeChatModel.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.modelName("qwen-max")
.build())
.build();
Msg response = agent.call(Msg.builder()
.textContent("Hello!")
.build()).block();
System.out.println(response.getTextContent());
案例二
<dependencies><dependency><groupId>io.agentscope</groupId><artifactId>agentscope</artifactId><version>1.0.9</version></dependency></dependencies>import io.agentscope.core.model.DashScopeChatModel;
public class ModelFactory {
public static DashScopeChatModel createQwenModel(){
String apiKey = System.getenv("DASHSCOPE_API_KEY");if(apiKey == null || apiKey.isBlank()){
throw new IllegalStateException("DASHSCOPE_API_KEY is required");}return DashScopeChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-plus")
//.modelName("gpt-4o")
//.generateOptions(GenerateOptions.builder().temperature(0.2).build())
.build();}}
简单输出
import io.agentscope.core.ReActAgent;import io.agentscope.core.message.Msg;import io.agentscope.core.model.DashScopeChatModel;
public class SimpleAgentDemo {
public static void main(String[] args){
DashScopeChatModel model = ModelFactory.createQwenModel();
ReActAgent agent = ReActAgent.builder()
.name("Nexus")
.sysPrompt("You are a helpful enterprise assistant.")
.model(model)
.build();
Msg response = agent.call(
Msg.builder()
.textContent("你好,请介绍一下 AgentScope 是什么")
.build()).block();if(response != null){
System.out.println(response.getTextContent());}}}
stream流输出
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;
public class StreamDemo {
public Flux<String> stream(String prompt){
DashScopeChatModel model = ModelFactory.createQwenModel();
GenerateOptions options = GenerateOptions.builder()
.stream(Boolean.TRUE)
.build();return model.stream(
List.of(Msg.builder().textContent(prompt).build()),
List.of(),
options)
.map(chatResponse -> chatResponse.getContent().stream()
.filter(TextBlock.class::isInstance)
.map(TextBlock.class::cast)
.map(TextBlock::getText)
.reduce("", String::concat))
.filter(text -> text != null &&!text.isBlank());}}
@GetMapping(value ="/test", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> test(@RequestParam String message){return qwenResponseComposer.composeTypewriter(message);}
其他例子
千问例子
DashScopeChatModel model = DashScopeChatModel.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.modelName("qwen3-max")
.enableThinking(true) // Automatically enables streaming
.defaultOptions(GenerateOptions.builder()
.thinkingBudget(5000) // Token budget for thinking
.build())
.build();
ollama例子
OllamaChatModel model =
OllamaChatModel.builder()
.modelName("qwen3-max")
.baseUrl("http://localhost:11434")
.defaultOptions(OllamaOptions.builder()
.thinkOption(ThinkOption.ThinkBoolean.ENABLED)
.temperature(0.8)
.build())
.build();
openai例子
OpenAIChatModel model = OpenAIChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o")
.build();
deepseek例子
OpenAIChatModel model = OpenAIChatModel.builder()
.apiKey("your-api-key")
.modelName("deepseek-chat")
.baseUrl("https://api.deepseek.com")
.build();
claude例子
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-sonnet-4-5-20250929") // Default
.build();
Gemini例子
GeminiChatModel model = GeminiChatModel.builder()
.apiKey(System.getenv("GEMINI_API_KEY"))
.modelName("gemini-2.5-flash") // Default
.baseUrl("https://your-gateway.example") // Optional
.build();
Vertex例子
GeminiChatModel model = GeminiChatModel.builder()
.modelName("gemini-2.0-flash")
.project("your-gcp-project")
.location("us-central1")
.vertexAI(true)
.credentials(GoogleCredentials.getApplicationDefault())
.build();
多智能体写作// 创建模型
DashScopeChatModel model = DashScopeChatModel.builder
.apiKey(apiKey)
.modelName("qwen-plus")
.build;
// 创建多个不同角色的智能体
ReActAgent planner = ReActAgent.builder
.name("规划师")
.sysPrompt("你是一个项目规划专家,擅长制定计划和分解任务。")
.model(model)
.build;
ReActAgent executor = ReActAgent.builder
.name("执行者")
.sysPrompt("你是一个执行专家,擅长将计划转化为具体的执行步骤。")
.model(model)
.build;
ReActAgent reviewer = ReActAgent.builder
.name("审查者")
.sysPrompt("你是一个审查专家,擅长评估和优化方案。")
.model(model)
.build;
System.out.println("\n[多智能体协作]");
String task ="设计一个简单的待办事项管理系统";
// 第一步: 规划师制定计划
System.out.println("任务: "+ task);
System.out.println("\n--- 规划师制定计划 ---");
Msg planRequest = Msg.builder
.textContent("请为以下任务制定一个详细的计划: "+ task)
.build;
Msg plan = planner.call(planRequest).block;
logger.info("规划师: {}", plan.getTextContent);
System.out.println(plan.getTextContent);
// 第二步: 执行者细化执行步骤
Msg executionRequest = Msg.builder
.textContent("基于以下计划,请提供具体的执行步骤:\n"+ plan.getTextContent)
.build;
Msg execution = executor.call(executionRequest).block;
logger.info("执行者: {}", execution.getTextContent);
System.out.println(execution.getTextContent);
// 第三步: 审查者评估方案
Msg reviewRequest = Msg.builder
.textContent("请评估以下执行方案,并提出改进建议:\n"+ execution.getTextContent)
.build;
Msg review = reviewer.call(reviewRequest).block;
logger.info("审查者: {}", review.getTextContent);
System.out.println(review.getTextContent);
多智能体模型案例
// DashScope multi-agent
DashScopeChatModel model = DashScopeChatModel.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.modelName("qwen3-max")
.formatter(new DashScopeMultiAgentFormatter())
.build();
// OpenAI multi-agent
OpenAIChatModel model = OpenAIChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o")
.formatter(new OpenAIMultiAgentFormatter())
.build();
// Anthropic multi-agent
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.formatter(new AnthropicMultiAgentFormatter())
.build();
// Gemini multi-agent
GeminiChatModel model = GeminiChatModel.builder()
.apiKey(System.getenv("GEMINI_API_KEY"))
.formatter(new GeminiMultiAgentFormatter())
.build();
// Ollama multi-agent
OllamaChatModel model = OllamaChatModel.builder()
.modelName("qwen3-max")
.formatter(new OllamaMultiAgentFormatter())
.build();
调用工具
import io.agentscope.core.ReActAgent;import io.agentscope.core.tool.Toolkit;import io.agentscope.core.model.DashScopeChatModel;
// Create model
DashScopeChatModel model = DashScopeChatModel.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.modelName("qwen-plus")
.build();
Toolkit toolkit = new Toolkit();
toolkit.registration()
.subAgent(()-> ReActAgent.builder()
.name("Expert")
.sysPrompt("You are a domain expert responsible for answering professional questions.")
.model(model)
.build())
.apply();
// Create main agent with toolkit
ReActAgent mainAgent = ReActAgent.builder()
.name("Coordinator")
.sysPrompt("You are a coordinator. When facing professional questions, call the call_expert tool to consult the expert.")
.model(model)
.toolkit(toolkit)
.build();
// Main agent will automatically call expert agent when needed
Msg response = mainAgent.call(userMsg).block();
// 1. Create knowledge base
EmbeddingModel embeddingModel = DashScopeTextEmbedding.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.modelName("text-embedding-v3")
.dimensions(1024)
.build();
Knowledge knowledge = SimpleKnowledge.builder()
.embeddingModel(embeddingModel)
.embeddingStore(InMemoryStore.builder().dimensions(1024).build())
.build();
// 2. Add documents
TextReader reader = new TextReader(512, SplitStrategy.PARAGRAPH, 50);
List<Document> docs = reader.read(ReaderInput.fromString("Text content...")).block();
knowledge.addDocuments(docs).block();
// 3. Retrieve
List<Document> results = knowledge.retrieve("query",
RetrieveConfig.builder().limit(3).scoreThreshold(0.5).build()).block();
复制代码
原文地址:https://blog.csdn.net/qq_35911118/article/details/160597964
欢迎光临 AI创想 (http://llms-ai.com/)
Powered by Discuz! X3.4