๐Ÿ“ฆ agentscope-ai / agentscope-java

๐Ÿ“„ README.md ยท 406 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406# AgentScope Java Examples

This directory contains examples demonstrating core features of AgentScope Java framework.

## ๐Ÿš€ Quick Start

### Prerequisites

- **JDK 17** or higher
- **Maven 3.6+**
- **DashScope API Key** - Get one at https://dashscope.console.aliyun.com/apiKey

### Build Examples

```bash
# From project root, build and install the main library
cd agentscope-core-java
mvn clean install

# Build examples
cd examples
mvn compile
```

### Environment Setup

Set your API key (optional - examples will prompt for it if not set):

```bash
export DASHSCOPE_API_KEY=your_api_key_here
```

## ๐Ÿ“š Examples Overview

| 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"` |

## ๐Ÿ“– Detailed Examples

### 1. BasicChatExample

The simplest way to create and chat with an agent.

```bash
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?"

---

### 2. ToolCallingExample

Learn how to give agents access to tools.

```bash
mvn exec:java -Dexec.mainClass="io.agentscope.examples.ToolCallingExample"
```

**What you'll learn:**
- Defining tools with `@Tool` annotation
- Registering tools to Toolkit
- Agent automatically calling tools

**Try asking:**
- "What time is it in Tokyo?"
- "Calculate 123 * 456"
- "Search for 'artificial intelligence'"

---

### 3. StructuredOutputExample

Generate structured, typed output from natural language queries.

```bash
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:

1. **Product Requirements Extraction**
   - Input: Natural language product description
   - Output: Structured `ProductRequirements` object with type, brand, specs, budget, features

2. **Contact Information Extraction**
   - Input: Text containing contact details
   - Output: Structured `ContactInfo` object with name, email, phone, company

3. **Sentiment Analysis**
   - Input: Customer review text
   - Output: Structured `SentimentAnalysis` object 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

---

### 4. ToolGroupExample

Agent autonomously managing tool groups using meta-tool.

```bash
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_tools` meta-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_tools` meta-tool
- When you give the agent a task, it will:
  1. Determine which tool groups are needed
  2. Call `reset_equipped_tools` to activate those groups
  3. Use the tools from the activated groups

**Example prompts to try:**

1. **Single tool group activation:**
   ```
   You> Calculate the factorial of 5
   ```
   Watch: Agent activates `math_ops`, then uses `factorial` tool

2. **Different tool group:**
   ```
   You> Ping google.com
   ```
   Watch: Agent activates `network_ops`, then uses `ping` tool

3. **Another tool group:**
   ```
   You> List files in /tmp
   ```
   Watch: Agent activates `file_ops`, then uses `list_files` tool

4. **Multiple tool groups in one task:**
   ```
   You> Calculate factorial of 7 and then ping github.com
   ```
   Watch: Agent activates both `math_ops` and `network_ops`

5. **Complex multi-group task:**
   ```
   You> Check if 17 is prime, then list files in /tmp
   ```
   Watch: Agent activates `math_ops` and `file_ops`

This example demonstrates **autonomous tool management** - the agent intelligently decides which tools to enable based on your request!

---

### 4. McpToolExample

Connect to external tool servers using Model Context Protocol (MCP).

```bash
mvn exec:java -Dexec.mainClass="io.agentscope.examples.McpToolExample"
```

**Prerequisites:**
Install an MCP server:
```bash
npm install -g @modelcontextprotocol/server-filesystem
```

**What 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"

---

### 5. HookExample

Monitor and intercept agent execution in real-time.

```bash
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

---

### 6. StreamingWebExample

Spring Boot web application with Server-Sent Events (SSE) streaming.

```bash
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:

```bash
# 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=Hello
```

You'll see the agent's response streaming in real-time, character by character.

---

### 7. SessionExample

Maintain persistent conversation history across runs.

```bash
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!
```

---

### 8. InterruptionExample

Gracefully interrupt long-running agent tasks.

```bash
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.

---

## ๐Ÿ› ๏ธ Common Operations

### Running a Specific Example

```bash
mvn exec:java -Dexec.mainClass="io.agentscope.examples.BasicChatExample"
```

### Debugging Examples

Add debug logging:
```bash
mvn exec:java -Dexec.mainClass="io.agentscope.examples.BasicChatExample" \
  -Dorg.slf4j.simpleLogger.defaultLogLevel=debug
```

### Code Formatting

```bash
mvn spotless:apply
```

## ๐Ÿ“ API Key Configuration

Examples support two ways to provide API keys:

1. **Environment Variable** (recommended):
   ```bash
   export DASHSCOPE_API_KEY=your_key_here
   mvn exec:java -Dexec.mainClass="..."
   ```

2. **Interactive Input**:
   If environment variable is not set, examples will prompt you to enter the API key.

## ๐Ÿค” Troubleshooting

### "DASHSCOPE_API_KEY not found"

Set the environment variable:
```bash
export DASHSCOPE_API_KEY=sk-xxx
```

Or the example will prompt you to enter it interactively.

### MCP Server Connection Failed

For McpToolExample, ensure the MCP server is installed:
```bash
# For filesystem server
npm install -g @modelcontextprotocol/server-filesystem

# For git server
npm install -g @modelcontextprotocol/server-git
```

### Compilation Errors

Make sure you've built the main library first:
```bash
cd /path/to/agentscope-core-java
mvn clean install
```

## ๐Ÿ“š Additional Resources

- [AgentScope Documentation](https://github.com/modelscope/agentscope)
- [API Reference](../docs/)
- [CLAUDE.md](../CLAUDE.md) - Development guidelines

## ๐Ÿ’ก Contributing

When adding new examples:

1. Keep each example focused on a single feature
2. Add clear documentation and comments
3. Include interactive prompts for configuration
4. Follow the existing code style
5. Run `mvn spotless:apply` before committing

## ๐Ÿ“„ License

Apache License 2.0 - See [LICENSE](../LICENSE) for details.