AgentScope Java Documentation

repository·main·Indexed 26 days ago

https://github.com/agentscope-ai/agentscope-java

An agent-oriented programming framework for building distributed, enterprise-grade LLM applications with JDK 17+. Version 0.3.0b1 / 2.0 provides robust abstractions for long-running tasks, secure tool execution via sandboxing, and real-time observability. Key features include @Tool annotations for tool calling, structured output generation, MCP tool server integration, and scheduling via XXL-Job or Quartz. Supports multiple model providers including DashScope, OpenAI, Anthropic, Gemini, and Ollama.

Tokens
220.6K
Snippets
535
Records
865
Agent score
89%

What's inside AgentScope Java

  1. Overview of Agent Middleware hooks

    main

    Agent middleware allows you to inject custom logic (logging, tracing, input rewriting, etc.) at key lifecycle points without modifying agent or model code. There are two types of hooks:

    • Onion hooks (onAgent, onReasoning, onActing, onModelCall): These wrap the next handler. You can execute logic before or after next.apply(input) and observe the intermediate event stream.
    • Transformer hooks (onSystemPrompt): These form a pipeline where the output of one middleware is the input to the next. There is no "inner layer."

    Hook Positions

    PositionTypeDescription
    onAgentOnionWraps the full reply flow (all ReAct rounds, tool execution, and final output)
    onReasoningOnionWraps one reasoning step (input assembly → model call → streaming decode)
    onActingOnionWraps the execution of a single tool call (only for tools executed inside the agent runtime)
    onModelCallOnionWraps a raw ChatModel API call
    onSystemPromptTransformerTriggers when the system prompt is assembled; middlewares run in sequence

    Execution Order

    • Onion hooks: The first middleware in the list is the outermost. For [mw1, mw2], the order is: mw1 pre → mw2 pre → inner → mw2 post → mw1 post.
    • Transformer hooks: Processed left-to-right. For [mw1, mw2], the order is: originalPrompt → mw1.onSystemPrompt() → mw2.onSystemPrompt() → final.
  2. Overview of AgentScope Scheduler extensions

    main

    The agentscope-extensions-scheduler module allows you to run Agents periodically (e.g., daily reports or health checks). It provides a unified AgentScheduler interface with two primary implementations:

    • Quartz mode (agentscope-extensions-scheduler-quartz): Suitable for standalone or clustered deployments using a shared Quartz DB.
    • XXL-Job mode (agentscope-extensions-scheduler-xxl-job): Designed for distributed scheduling that requires an external XXL-Job admin server for management and routing.

    To extend the system with a custom scheduler, you can implement the AgentScheduler SPI located in agentscope-extensions-scheduler-common.

  3. Overview of AgentScope Java 2.0 Architecture

    main

    AgentScope Java 2.0 is a platform designed for running agents in production, moving beyond simple agent construction to support long-running, complex tasks and enterprise-grade deployment. The architecture is built on three pillars:

    1. Harness Engineering: Provides scaffolding for reliability, including skill repositories, layered memory, sub-agent management, and auto-context compaction.
    2. Enterprise-grade Distributed Deployment: Supports stateless horizontal scaling, multi-tenant isolation, secure sandbox execution, and session recovery via AgentStateStore.
    3. Redesigned Foundation: A leaner core featuring built-in event streaming, a unified ContentBlock message model, and a structured middleware system.
  4. Overview of AgentScope Training Extension

    main

    The AgentScope Training Extension enables online training for Agents by creating a closed loop between production interaction data and model optimization. It allows developers to leverage real user interaction data and production toolchains (APIs, databases, etc.) to continuously improve Agent performance through methods like Supervised Fine-Tuning (SFT), knowledge distillation, and Reinforcement Learning (e.g., PPO).

    Key Characteristics

    • Reuse Production Toolchains: Agents use real tools instead of mocks, reducing the 'Reality Gap'.
    • Incremental Learning: Supports fast cold starts using small amounts of real interaction data.

    Safety and Modeling Constraints

    • Tool Safety: By default, the system supports read-only tools. Write operations (e.g., 'place order') require sandboxing, idempotency, or manual review to prevent repeated execution during training replays.
    • Multi-Turn Scenarios: Developers must explicitly model state management or trajectory sampling for complex, multi-turn dialogues.
  5. Use Chat Models in AgentScope Java

    main

    A Chat Model is the LLM that drives conversation and tool calling. AgentScope Java provides built-in support for several providers:

    ProviderClassNotes
    OpenAIOpenAIChatModelWorks with vLLM and OpenAI-compatible endpoints (DeepSeek, Kimi, etc.)
    AnthropicAnthropicChatModelClaude models; supports prompt caching and thinking
    DashScopeDashScopeChatModelQwen models; multi-modal (vision/audio/video) and reasoning
    GeminiGemGeminiChatModelGoogle Gemini; multi-modal
    OllamaOllamaChatModelLocally hosted LLMs; credentials are optional

    Provider-specific credential classes (e.g., OpenAICredential, AnthropicCredential) are included in their respective extension modules. OpenAI-compatible credentials like DeepSeekCredential and KimiCredential are available in the core package.

  6. Understand ReMe memory write and retrieval logic

    main

    Write (record) process

    Filtered messages are joined into a single ReMeTrajectory and sent to ReMe's add endpoint. The server performs LLM extraction on the trajectory to create searchable memory snippets.

    Filtering Rules:

    • Only USER and ASSISTANT messages are included.
    • Assistant messages containing ToolUseBlock (tool-call requests) are skipped.
    • Messages containing the <compressed_history> marker are skipped.

    Retrieval process

    The current message is used as a query against ReMe's search endpoint. The system returns the server-aggregated answer field if present; otherwise, it returns multiple joined memory snippets.

  7. Understand the HarnessAgent Workspace structure

    main

    The workspace is a directory-based foundation for a HarnessAgent. It stores persona, long-term memory, domain knowledge, subagent declarations, and session history as a directory structure of Markdown files. This allows agent state to be managed as files rather than being hardcoded.

    Directory Layout

    workspace/                           ← default: .agentscope/workspace
    ├── AGENTS.md                        ← persona / behavior guidelines (injected each turn)
    ├── MEMORY.md                        ← curated long-term memory (injected each turn, token-budgeted)
    ├── knowledge/
    │   ├── KNOWLEDGE.md                 ← domain knowledge entry point
    │   └── *                            ← other reference files
    ├── memory/
    │   ├── YYYY-MM-DD.md                ← daily fact log
    │   └── .consolidation_state         ← MemoryConsolidator internal state
    ├── skills/<skill-name>/SKILL.md     ← custom skills
    ├── subagents/<id>.md                ← subagent declarations
    └── agents/<agentId>/
        ├── workspace/                   ← runtime root for isolated subagents
        └── sessions/
            ├── sessions.json            ← session index (id / summary / updatedAt)
            ├── <sessionId>.jsonl        ← LLM-visible compacted context
            └── <sessionId>.log.jsonl    ← full conversation log (append-only)
  8. Understand the HarnessAgent filesystem abstraction

    main

    The HarnessAgent provides a uniform interface for workspace access, abstracting the underlying storage from the agent. This allows file operations and shell commands to remain consistent regardless of the deployment mode.

    Supported file tools that use this abstraction include:

    • read_file
    • write_file
    • edit_file
    • grep_files
    • glob_files
    • list_files
    • execute (optional shell command execution)
  9. Deploy agents as stable services with Agent Service

    main

    In AgentScope 2.0, the Agent Service capability is integrated into the main library, allowing agents to be built as service-ready components from the start. This enables agents to be called reliably from front-ends, external applications, and workflow systems rather than being limited to local terminal or single-process execution.

    Key features of the integrated Agent Service include:

    • Standardized Service Interface: Allows agents to stream execution progress to external front-ends for live displays.
    • Session Log Recovery: Enables tasks to resume execution after an interruption.
    • Background Tool Execution: Provides more reliable completion for long-running tools.
    • Deployment Readiness: Facilitates the transition from local scripts to deployable, stable services that act as a runtime support layer.
  10. Use AgentScope Core Libraries

    main

    The project relies on the following key libraries for its core functionality:

    • Reactor Core: Provides Mono and Flux for reactive programming.
    • Jackson: Used for JSON serialization and deserialization.
    • SLF4J: The standard for logging. Use parameterized logging (e.g., log.info("Message: {}", value)).
    • OkHttp: The underlying HTTP client for model API calls.
    • MCP SDK: Integration for the Model Context Protocol.
    • JUnit 5 & Mockito: Standard tools for testing and mocking.
  11. Understand HarnessAgent Architecture

    main

    HarnessAgent is a wrapper around ReActAgent designed for long-running, complex tasks. Unlike a standard ReActAgent which follows a simple "one request → reason → tool → reply" loop, HarnessAgent adds engineering capabilities like workspace-driven personas, long-term memory, subagent orchestration, and sandbox isolation.

    Key architectural principles:

    1. Capabilities layer onto the reasoning loop: Capabilities (like Plan Mode or Workspace injection) hook into the ReAct loop without modifying the core algorithm.
    2. Shared objects: Capabilities cooperate via three shared objects:
      • RuntimeContext: Contains sessionId, userId, and arbitrary extras (not persisted).
      • The workspace: The location for file reads/writes (local disk, sandbox, or KV store).
      • AgentStateStore: Manages how runtime state is restored across calls.
    3. Middleware execution order: Built-in Harness middleware runs in a fixed order, but any custom middleware added via .middleware(...) runs before the built-ins.