This directory contains examples demonstrating core features of AgentScope Java framework.
- JDK 17 or higher
- Maven 3.6+
- DashScope API Key - Get one at https://dashscope.console.aliyun.com/apiKey
# From project root, build and install the main library cd agentscope-core-java mvn clean install # Build examples cd examples mvn compileSet your API key (optional - examples will prompt for it if not set):
export DASHSCOPE_API_KEY=your_api_key_here| Example | Description | Core Concepts | Run Command |
|---|---|---|---|
| BasicChatExample | Simplest agent conversation | Agent, Model, Memory | mvn exec:java -Dexec.mainClass="io.agentscope.examples.BasicChatExample" |
| ToolCallingExample | Equipping agents with tools | @Tool, Toolkit, Tool calling | mvn exec:java -Dexec.mainClass="io.agentscope.examples.ToolCallingExample" |
| StructuredOutputExample | Generate typed structured output | Structured output, Schema validation | mvn exec:java -Dexec.mainClass="io.agentscope.examples.StructuredOutputExample" |
| ToolGroupExample | Autonomous tool group management | Meta-tool, Tool groups, Self-activation | mvn exec:java -Dexec.mainClass="io.agentscope.examples.ToolGroupExample" |
| McpToolExample | MCP tool server integration | MCP, External tools | mvn exec:java -Dexec.mainClass="io.agentscope.examples.McpToolExample" |
| HookExample | Monitoring agent execution | Hook, Lifecycle callbacks | mvn exec:java -Dexec.mainClass="io.agentscope.examples.HookExample" |
| StreamingWebExample | Spring Boot + SSE streaming | Web API, Real-time streaming | mvn exec:java -Dexec.mainClass="io.agentscope.examples.StreamingWebExample" |
| SessionExample | Persistent conversations | JsonSession, State management | mvn exec:java -Dexec.mainClass="io.agentscope.examples.SessionExample" |
| InterruptionExample | Agent interruption mechanism | User interruption, Recovery | mvn exec:java -Dexec.mainClass="io.agentscope.examples.InterruptionExample" |
The simplest way to create and chat with an agent.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.BasicChatExample"What you'll learn:
- Creating a ReActAgent
- Configuring Model, Memory, and Formatter
- Interactive conversation
Try asking:
- "Hello, introduce yourself"
- "What can you help me with?"
Learn how to give agents access to tools.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.ToolCallingExample"What you'll learn:
- Defining tools with
@Toolannotation - Registering tools to Toolkit
- Agent automatically calling tools
Try asking:
- "What time is it in Tokyo?"
- "Calculate 123 * 456"
- "Search for 'artificial intelligence'"
Generate structured, typed output from natural language queries.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.StructuredOutputExample"What you'll learn:
- Defining structured output schema using Java classes
- Requesting structured responses from agents
- Extracting and validating typed data
How it works: This example demonstrates three use cases:
-
Product Requirements Extraction
- Input: Natural language product description
- Output: Structured
ProductRequirementsobject with type, brand, specs, budget, features
-
Contact Information Extraction
- Input: Text containing contact details
- Output: Structured
ContactInfoobject with name, email, phone, company
-
Sentiment Analysis
- Input: Customer review text
- Output: Structured
SentimentAnalysisobject with sentiment, scores, topics, summary
Example output:
=== Example 1: Product Information === Query: I'm looking for a laptop. I need at least 16GB RAM, prefer Apple brand... Extracted structured data: Product Type: laptop Brand: Apple Min RAM: 16 GB Max Budget: $2000.0 Features: [lightweight, travel-friendly] Key features:
- ✅ Type-safe data extraction
- ✅ Automatic schema generation from Java classes
- ✅ Works with any model supporting tool calling
- ✅ No need for manual JSON parsing
Agent autonomously managing tool groups using meta-tool.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.ToolGroupExample"What you'll learn:
- Creating tool groups to organize tools
- Agent autonomously activating tool groups using
reset_equipped_toolsmeta-tool - Agent deciding which tools to activate based on task requirements
How it works:
- All tool groups start as INACTIVE
- The agent has access to the
reset_equipped_toolsmeta-tool - When you give the agent a task, it will:
- Determine which tool groups are needed
- Call
reset_equipped_toolsto activate those groups - Use the tools from the activated groups
Example prompts to try:
-
Single tool group activation:
You> Calculate the factorial of 5Watch: Agent activates
math_ops, then usesfactorialtool -
Different tool group:
You> Ping google.comWatch: Agent activates
network_ops, then usespingtool -
Another tool group:
You> List files in /tmpWatch: Agent activates
file_ops, then useslist_filestool -
Multiple tool groups in one task:
You> Calculate factorial of 7 and then ping github.comWatch: Agent activates both
math_opsandnetwork_ops -
Complex multi-group task:
You> Check if 17 is prime, then list files in /tmpWatch: Agent activates
math_opsandfile_ops
This example demonstrates autonomous tool management - the agent intelligently decides which tools to enable based on your request!
Connect to external tool servers using Model Context Protocol (MCP).
mvn exec:java -Dexec.mainClass="io.agentscope.examples.McpToolExample"Prerequisites: Install an MCP server:
npm install -g @modelcontextprotocol/server-filesystemWhat you'll learn:
- Connecting to MCP servers (StdIO, SSE, HTTP)
- Using external tools from MCP servers
- Interactive MCP configuration
Try asking:
- "List files in /tmp"
- "Read the content of /tmp/test.txt"
Monitor and intercept agent execution in real-time.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.HookExample"What you'll learn:
- Complete Hook lifecycle callbacks
- Streaming output monitoring
- Tool execution tracking
- ToolEmitter for progress updates
Try asking:
- "Process the customer dataset"
You'll see detailed logs of:
- Agent start
- Reasoning chunks (streaming)
- Tool calls and results
- Progress updates
- Completion
Spring Boot web application with Server-Sent Events (SSE) streaming.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.StreamingWebExample"What you'll learn:
- Building a Spring Boot REST API with reactive endpoints
- Real-time streaming with Server-Sent Events (SSE)
- Hook-based response collection for streaming
- Session persistence in web environment
How to use: After starting the server, open your browser or use curl:
# Simple query curl -N "http://localhost:8080/chat?message=Hello" # With session persistence curl -N "http://localhost:8080/chat?message=What%20is%20AI?&sessionId=my-session" # Or open in browser http://localhost:8080/chat?message=HelloYou'll see the agent's response streaming in real-time, character by character.
Maintain persistent conversation history across runs.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.SessionExample"What you'll learn:
- Using JsonSession for persistence
- Saving/loading conversation state
- Session management
Try this flow:
# First run Enter session ID: alice_session You> My name is Alice and I love pizza # Second run (same session ID) Enter session ID: alice_session You> What's my name and what do I like? Agent> Your name is Alice and you love pizza! Gracefully interrupt long-running agent tasks.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.InterruptionExample"What you'll learn:
- User-initiated interruption
- Cooperative interruption mechanism
- Fake tool results generation
- Graceful recovery
The example automatically demonstrates interruption by starting a long task and interrupting it after 2 seconds.
mvn exec:java -Dexec.mainClass="io.agentscope.examples.BasicChatExample"Add debug logging:
mvn exec:java -Dexec.mainClass="io.agentscope.examples.BasicChatExample" \ -Dorg.slf4j.simpleLogger.defaultLogLevel=debugmvn spotless:applyExamples support two ways to provide API keys:
-
Environment Variable (recommended):
export DASHSCOPE_API_KEY=your_key_here mvn exec:java -Dexec.mainClass="..."
-
Interactive Input: If environment variable is not set, examples will prompt you to enter the API key.
Set the environment variable:
export DASHSCOPE_API_KEY=sk-xxxOr the example will prompt you to enter it interactively.
For McpToolExample, ensure the MCP server is installed:
# For filesystem server npm install -g @modelcontextprotocol/server-filesystem # For git server npm install -g @modelcontextprotocol/server-gitMake sure you've built the main library first:
cd /path/to/agentscope-core-java mvn clean install- AgentScope Documentation
- API Reference
- CLAUDE.md - Development guidelines
When adding new examples:
- Keep each example focused on a single feature
- Add clear documentation and comments
- Include interactive prompts for configuration
- Follow the existing code style
- Run
mvn spotless:applybefore committing
Apache License 2.0 - See LICENSE for details.