Master AgentScope Java’s 5 Core Blocks: Message, Agent, Model, Memory, Tool

This article breaks down AgentScope Java's five fundamental components—Message, Agent, Model, Memory, and Tool—explaining their roles, structures, code examples, provider switching, tool definition, and state management, while highlighting concurrency pitfalls and persistence options.

Tech Ocean
Tech Ocean
Tech Ocean
Master AgentScope Java’s 5 Core Blocks: Message, Agent, Model, Memory, Tool

Overview of the Five Building Blocks

AgentScope Java structures an agent around five collaborating components: Message , Agent , Model , Tool , and Memory/State . The data flow is:

┌────────────────────── ReActAgent ──────────────────────┐
        │                                                      │
UserMessage ─►   Model(推理)  ◄──►   Toolkit(行动)          │
(你的输入)      qwen-plus          @Tool 方法               │
        │          │                │                        │
        │          ▼                ▼                        │
        │   Memory / AgentState(记住每一轮对话)               │
        │                                                      │
        └───────────────────►  AssistantMessage(回复)───────┘

The Message component carries all data exchanged between user, model, and tools. The Agent receives a Message, processes it, and returns a Message. The Model wraps calls to large language models. The Tool extends the model’s capabilities beyond text generation. Memory/State automatically stores each round’s inputs, tool calls, tool results, and model replies.

Message: Unified Data Structure

Every piece of information is a Message with three main fields: role: one of USER, ASSISTANT, SYSTEM, TOOL. content: a list of blocks. Supported block types are TextBlock (plain text), ImageBlock (image data), ToolUseBlock (model requests a tool), and ToolResultBlock (tool response). name / id / metadata: optional auxiliary information.

Common subclasses are UserMessage (user input) and AssistantMessage (model output). Example constructions:

// Simple user message
Msg userMsg = new UserMessage("帮我查下上海天气");

// Builder style with explicit role
Msg msg = Msg.builder()
    .role(MsgRole.USER)
    .textContent("帮我查下上海天气")
    .build();

String text = msg.getTextContent(); // extracts plain text

The block‑based design enables multimodal content and tool interactions within a single message.

Agent: Stateful Receive‑Process‑Reply Loop

The Agent contract is a single method: receive a Message, process it, and return a Message. The default implementation ReActAgent follows a “receive → think → act → observe” cycle (detailed in the next article). A single Agent instance holds internal state and is **not thread‑safe**; concurrent requests must create separate instances or use session‑isolated agents.

Model: Provider‑Agnostic LLM Invocation

The Model component abstracts calls to large language models. Two configuration styles are shown:

// Style 1: short string – ModelRegistry resolves provider and reads API key from env
.model("dashscope:qwen-plus")

// Style 2: explicit builder for fine‑tuned parameters
.model(DashScopeChatModel.builder()
    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
    .modelName("qwen-max")
    .stream(true)
    .build())

Internally a Formatter translates the unified Message format into each provider’s API request. Built‑in providers include DashScope, OpenAI, Anthropic, Gemini, Ollama, DeepSeek, and GLM. Switching providers only requires changing the provider:model prefix, leaving business code untouched. Example prefixes and required environment variables:

DashScope – dashscope:qwen-plusDASHSCOPE_API_KEY OpenAI – openai:gpt-5.5OPENAI_API_KEY Anthropic – anthropic:claude-sonnet-4-5ANTHROPIC_API_KEY Google Gemini – gemini:gemini-2.0-flashGEMINI_API_KEY Local Ollama – ollama:llama3 – (no API key required)

Tool: Extending the Model with External Capabilities

Tools let the model perform actions beyond text generation. Defining a tool requires a single annotation on a public method:

public class WeatherTools {
    @Tool(name = "get_weather", description = "查询指定城市的天气")
    public String getWeather(@ToolParam(name = "city", description = "城市名") String city) {
        return city + ":晴,22°C";
    }
}

Because Java discards parameter names after compilation, the @ToolParam(name = "…") annotation is mandatory; otherwise the model cannot map arguments to parameters. Register the class with a Toolkit to make the tool callable (details in Day 4).

Memory / State: Persistent Conversation Context

Each Agent automatically records the user input, any tool calls, tool results, and model replies into its conversation context, preventing “forgetting”. The context is exposed via AgentState:

List<Msg> history = agent.getAgentState().getContext();

By default the history lives in process memory and is lost when the process exits. For durability across restarts or requests, implement an AgentStateStore to persist the state.

Day 2 Summary

Message : unified structure role + content blocks. Key classes: UserMessage, AssistantMessage, Msg.builder.

Agent : receives, processes, and replies; holds state and is not thread‑safe. Key class: ReActAgent.

Model : invokes LLMs; provider switched by changing the provider:model string. Key classes: Formatter, provider‑specific builders.

Tool : gives the model actionable capabilities. Key annotations/classes: @Tool, @ToolParam, Toolkit.

Memory/State : automatically stores conversation rounds; can be persisted with AgentStateStore. Key class: AgentState.

Related Links

AgentScope Java 官方文档:https://java.agentscope.io/v2/zh/intro.html
核心概念:https://java.agentscope.io/v1/zh/docs/quickstart/key-concepts.html
GitHub 仓库:https://github.com/agentscope-ai/agentscope-java
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaLLMAgentMemoryMessageModeltoolAgentScope
Tech Ocean
Written by

Tech Ocean

Focused on AI programming, sharing ready-to-use development efficiency solutions.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.