### Quickstart: create GitHubChannel and start Gateway Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/channel/github.md Creates a GitHubChannel from properties, builds a GatewayBootstrap with the channel, and starts it. The start method resolves bot identity via GET /user and begins accepting webhooks. ```java GitHubChannel channel = GitHubChannel.fromProperties( "my-github", ChannelConfig.of("my-github", "main"), Map.of( "token", "ghp_xxxxxxxxxxxx", "webhookSecret", "your-webhook-secret" )); GatewayBootstrap gw = GatewayBootstrap.builder() .agent("main", agent) .channel(channel) .build(); gw.start(); // resolves bot identity via GET /user, starts accepting webhooks ``` -------------------------------- ### Build and compile examples with Maven Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/README.md Run from the repository root to build and install all modules, then compile the documentation example module. The second command assumes you are in the agentscope-examples/documentation directory. ```bash # From the repository root, build and install every module (core, harness, extensions...) mvn clean install -DskipTests # Then cd into this example module — every command below assumes you're here cd agentscope-examples/documentation mvn compile ``` -------------------------------- ### Quickstart: configure OSS state store for AgentScope Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/session/oss.md Quickstart example showing how to create an OSS client, build an OssAgentStateStore, and attach it to a ReActAgent. Requires an OSS endpoint, access key ID, and access key secret. ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import io.agentscope.core.state.AgentStateStore; import io.agentscope.extensions.oss.OssAgentStateStore; OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); AgentStateStore stateStore = OssAgentStateStore.builder() .ossClient(ossClient) .bucketName("my-agentscope-bucket") .keyPrefix("agentscope/state/") .build(); ReActAgent agent = ReActAgent.builder() .name("assistant") .model(model) .stateStore(stateStore) .build(); ``` -------------------------------- ### Start Local Development Server Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/README.md Commands to install dependencies and start the local development server for the documentation site. ```bash npm ci npm run dev ``` -------------------------------- ### Quickstart: create GitLab channel and start gateway Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/channel/gitlab.md Create a GitLabChannel with a token and start a GatewayBootstrap that routes comments to the agent. Requires a Personal Access Token with api scope and a configured webhook. ```java GitLabChannel channel = GitLabChannel.fromProperties( "my-gitlab", ChannelConfig.of("my-gitlab", "main"), Map.of( "token", "glpat-xxxxxxxxxxxx" )); GatewayBootstrap gw = GatewayBootstrap.builder() .agent("main", agent) .channel(channel) .build(); gw.start(); ``` -------------------------------- ### Confirm source DSH boots Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/aistio/sdk/dsh/README.md First-time setup from a source checkout: install dependencies, build, and start the web UI. The default UI is at http://127.0.0.1:3080. ```bash cd "$DSH_ROOT" pnpm install pnpm run build pnpm dsh web ``` -------------------------------- ### Quickstart: create client, register toolkit, and use in agent Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/infrastructure/higress.md Shows the full setup: create a HigressMcpClientWrapper against an MCP endpoint, register it with HigressToolkit, and use it in a ReActAgent. ```java import io.agentscope.extensions.higress.HigressMcpClientBuilder; import io.agentscope.extensions.higress.HigressMcpClientWrapper; import io.agentscope.extensions.higress.HigressToolkit; // 1) Create a client against an MCP endpoint published by Higress HigressMcpClientWrapper client = HigressMcpClientBuilder .create("higress") .streamableHttpEndpoint("http://gateway/mcp-servers/union-tools-search") .build(); // 2) Register with HigressToolkit (a Toolkit subclass that caches the Higress client) HigressToolkit toolkit = new HigressToolkit(); toolkit.registerMcpClient(client).block(); // 3) Use it from an Agent ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .toolkit(toolkit) .build(); ``` -------------------------------- ### Quickstart with Lettuce standalone Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/session/redis.md Create a RedisClient and build a RedisAgentStateStore using the lettuceClient builder method. This is the minimal setup for a standalone Redis instance. ```java import io.lettuce.core.RedisClient; import io.agentscope.core.state.AgentStateStore; import io.agentscope.extensions.redis.state.RedisAgentStateStore; RedisClient redisClient = RedisClient.create("redis://localhost:6379"); AgentStateStore stateStore = RedisAgentStateStore.builder() .lettuceClient(redisClient) .build(); ``` -------------------------------- ### Quick Start with JdbcDistributedStore Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-extensions/agentscope-extensions-jdbc/README.md Quick start example for using the full JdbcDistributedStore facade. The dialect is auto-detected from the DataSource via JDK SPI, so no manual dialect selection is required. ```java import io.agentscope.extensions.jdbc.JdbcDistributedStore; import io.agentscope.harness.agent.HarnessAgent; import io.agentscope.harness.agent.sandbox.impl.docker.DockerFilesystemSpec; import javax.sql.DataSource; DataSource dataSource = ...; // HikariCP, Druid, etc. HarnessAgent agent = HarnessAgent.builder() .name("my-agent") .model("dashscope:qwen-plus") .distributedStore(JdbcDistributedStore.create(dataSource)) .filesystem(new DockerFilesystemSpec().image("ubuntu:24.04")) .build(); ``` -------------------------------- ### Docker alternative build and start Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/managed_agents/guide/13-operations.md Builds the agentscope-service module and starts the Docker Compose stack. Use this as an alternative to the local script-based setup. ```bash mvn -pl agentscope-service -am install -DskipTests docker compose -f agentscope-service/docker-compose.yml up --build ``` -------------------------------- ### Install MCP servers Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/README.md Install the necessary MCP servers for the McpStdioExample. ```bash # For filesystem server npm install -g @modelcontextprotocol/server-filesystem # For git server npm install -g @modelcontextprotocol/server-git ``` -------------------------------- ### Build or run the console Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/README.md Install dependencies and build static assets, or start the Vite development server with HMR. ```bash cd agentscope-service/frontend npm install npm run build # emits static assets into ../aistio/ui npm run dev # Vite HMR; /api proxies to the gateway ``` -------------------------------- ### Quickstart: Stream mode (default) Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/channel/dingtalk.md Creates a DingTalk channel in Stream mode and starts the gateway. Opens a persistent WebSocket to receive bot messages. ```java DingTalkChannel channel = DingTalkChannel.fromProperties( "my-dingtalk", ChannelConfig.of("my-dingtalk", "main"), Map.of( "appKey", "your-app-key", "appSecret", "your-app-secret", "robotCode", "your-robot-code" )); GatewayBootstrap gw = GatewayBootstrap.builder() .agent("main", agent) .channel(channel) .build(); gw.start(); // opens the Stream WebSocket and begins dispatching ``` -------------------------------- ### Install Runtime CLI Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/controlplane/runtime-host-cli.md Install the runtime CLI from source to the specified prefix. ```bash cd agentscope-service/aistio make install-runtime-cli PREFIX="$HOME/.local" ``` -------------------------------- ### Set DashScope API key environment variable Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/README.md Optional environment setup. If not set, examples will prompt for the API key. ```bash export DASHSCOPE_API_KEY=your_api_key_here ``` -------------------------------- ### Local development setup and smoke test Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/managed_agents/guide/13-operations.md Sets the DASHSCOPE_API_KEY, rebuilds the local schema, starts all four planes, and runs API-level smoke tests. Use this for the fastest local development path. The console is available at http://localhost:18080 with default admin/admin credentials. ```bash export DASHSCOPE_API_KEY=sk-xxx # 全量编译、重建可丢弃的本地 schema、启动全部四个平面 cd agentscope-service scripts/dev-down.sh && BUILDER_REBUILD=1 scripts/dev-up.sh # API 级验收:Managed Agent + v4 Issue/Run/ExecutionAttempt + Artifact/Approval/Automation scripts/smoke.sh ``` -------------------------------- ### Example Instructions for a Managed Agent Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/service/managed-agent.md Example instructions to provide when creating a Managed Agent. These instructions guide the agent to organize technical material, check input sufficiency, cite evidence, read only specified files, ask for missing material, and deliver conclusions with supporting evidence and open questions. ```text You organize technical material. Check whether the input is sufficient and cite evidence. Read only the files specified by the task. Ask for missing material. Deliver conclusions, supporting evidence and open questions. ``` -------------------------------- ### Environment setup and run commands Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/agents/agentscope-codingagent/README.md Required environment variables include GITHUB_WEBHOOK_SECRET, GITHUB_TOKEN, ANTHROPIC_API_KEY, and MODEL_ID. Optional variables enable web search (TAVILY_API_KEY) and Docker sandboxing (SANDBOX_TYPE=docker). Build and run with 'mvn spring-boot:run -pl agentscope-examples/agents/agentscope-codingagent'. The service starts on port 8080, overridable with PORT. ```bash # Required env vars export GITHUB_WEBHOOK_SECRET=your-webhook-secret export GITHUB_TOKEN=your-github-token export ANTHROPIC_API_KEY=sk-ant-... export MODEL_ID=claude-... # Optional export TAVILY_API_KEY=tvly-... # enables web search export SANDBOX_TYPE=docker # run each session in a Docker sandbox (default: none) # Build and run mvn spring-boot:run -pl agentscope-examples/agents/agentscope-codingagent ``` -------------------------------- ### Run AGUI Example via Maven Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/protocol/agui.md Set the DASHSCOPE_API_KEY environment variable and run the Spring Boot application from the example directory. ```bash export DASHSCOPE_API_KEY=your-key cd agentscope-examples/agui mvn spring-boot:run ``` -------------------------------- ### Start AgentScope Service with Docker Compose Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/service/quickstart.md Extract the release archive, run init-env.sh with VERSION and REGISTRY/NAMESPACE, then pull and start the service. Initialization creates a mode-600 .env with secrets; rerunning preserves the file. ```bash tar -xzf agentscope-service-VERSION-compose.tar.gz cd agentscope-service ./init-env.sh VERSION REGISTRY/NAMESPACE docker compose pull docker compose up -d --wait --wait-timeout 600 ``` -------------------------------- ### Install SDK and DSH packages Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/service/integrations.md Use these commands to install the required Python and npm packages. Ensure you use the versions specified in the release-manifest.json file. ```bash python -m pip install "aistio-sdk==$AISTIO_SDK_VERSION" npm install "@agentscope/dsh-aistio@$DSH_AISTIO_VERSION" ``` -------------------------------- ### Install aistio-sdk from wheel Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/aistio/sdk/python/README.md Install the SDK using a downloaded wheel file. Replace VERSION with the specific version from the release manifest. ```bash python -m pip install ./aistio_sdk-VERSION-py3-none-any.whl ``` -------------------------------- ### Debug Examples Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/README.md Command to run an example with debug logging enabled via SLF4J. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.documentation2.quickstart.BasicChatExample" \ -Dorg.slf4j.simpleLogger.defaultLogLevel=debug ``` -------------------------------- ### Run CustomizedMiddlewareExample Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/README.md Executes the middleware example to monitor agent execution. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.documentation2.middleware.CustomizedMiddlewareExample" ``` -------------------------------- ### Run MCP Examples Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/README.md Executes different MCP transport examples for local and remote tool servers. ```bash # Local subprocess over stdin/stdout mvn exec:java -Dexec.mainClass="io.agentscope.examples.documentation2.mcp.McpStdioExample" # Remote server over Server-Sent Events mvn exec:java -Dexec.mainClass="io.agentscope.examples.documentation2.mcp.McpSseExample" # Remote server over Streamable HTTP mvn exec:java -Dexec.mainClass="io.agentscope.examples.documentation2.mcp.McpStreamableHttpExample" ``` -------------------------------- ### Clone and start the local stack with dev-up.sh Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/README.md Clones the repository, sets the DashScope API key, and starts PostgreSQL, aistiod, the data plane, scheduler, and gateway. BUILDER_REBUILD=1 recreates the disposable cp, rt, and dp development schemas; use BUILDER_RESET_DB=0 to preserve an existing v4 database. ```bash git clone https://github.com/agentscope-ai/agentscope-java.git cd agentscope-java export DASHSCOPE_API_KEY=sk-xxx cd agentscope-service scripts/dev-down.sh && BUILDER_REBUILD=1 scripts/dev-up.sh ``` -------------------------------- ### Example prompts for the Coding Agent Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/agents/agentscope-codingagent/README.md Example prompts to use in the interactive REPL. The agent works in its own workspace, so clone or fetch repos there. ```text You> write hello.txt with a haiku about Java You> fetch https://github.com/anthropics/anthropic-sdk-python/blob/main/README.md and summarize it You> clone https://github.com/owner/repo into the workspace and tell me what it does You> /exit ``` -------------------------------- ### Quick start: TrainingRunner with shadow rollouts Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-extensions/agentscope-extensions-training/README.md Sets up a TrainingRunner to sample 10% of agent calls for shadow rollouts against a Trinity endpoint, using a constant reward of 1.0 and a commit interval of 300 seconds. The runner is started and stopped, and the agent is called normally. ```java import io.agentscope.core.ReActAgent; import io.agentscope.core.message.Msg; import io.agentscope.core.message.MsgRole; import io.agentscope.core.training.reward.RewardCalculator; import io.agentscope.core.training.runner.TrainingRunner; import io.agentscope.core.training.strategy.SamplingRateStrategy; import java.util.List; ReActAgent agent = ReActAgent.builder() .name("assistant") .model("dashscope:qwen-plus") .sysPrompt("You are a helpful assistant.") .build(); // Scores a shadow rollout after it completes; typically inspects the shadow // agent's final state/output rather than the production agent's. RewardCalculator rewardCalculator = shadowAgent -> 1.0; TrainingRunner runner = TrainingRunner.builder() .trinityEndpoint("http://localhost:8010") .modelName("/home/ecs-user/models/Qwen2.5-0.5B-Instruct") .selectionStrategy(SamplingRateStrategy.of(0.1)) // sample 10% of calls .rewardCalculator(rewardCalculator) .commitIntervalSeconds(300) // trigger a Trinity commit every 5 minutes .build(); runner.start(); // Used completely normally — 100% of calls still go through the agent's own // model. TrainingRouter decides in the background, per call, whether to also // run a shadow rollout against Trinity. Msg reply = agent.call( List.of( Msg.builder() .role(MsgRole.USER) .textContent("What's the weather today?") .build())) .block(); runner.stop(); // flushes a final commit and unregisters the hook ``` -------------------------------- ### Start the coding agent service for DingTalk Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/agents/agentscope-codingagent/README.md Run this Maven command to start the service with the DingTalk channel. On boot, expect logs: 'DingTalk channel 'dingtalk' started: appKey=…, robotCode=…' and 'DingTalk Stream connected: '. ```bash mvn spring-boot:run -pl agentscope-examples/agents/agentscope-codingagent ``` -------------------------------- ### Run Issue collaboration example Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/aistio/examples/collaboration/README.md Sets the required environment variables and runs the collaboration example script. The script prints IDs only; Agents receive the actual obligation through the configured Managed, External, or Hosted binding. ```bash export AISTIO_URL=http://localhost:8080 export AGENTSCOPE_API_TOKEN=... ./run.sh ``` -------------------------------- ### Install MCP Filesystem Server Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/README.md Installs the MCP filesystem server prerequisite via npm. ```bash npm install -g @modelcontextprotocol/server-filesystem ``` -------------------------------- ### Initialize and start TrainingRunner Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/ecosystem/training.md Configure the TrainingRunner with a Trinity endpoint, sampling strategy, and reward calculator, then start the pipeline to intercept agent calls. ```java import io.agentscope.core.training.runner.TrainingRunner; import io.agentscope.core.training.strategy.SamplingRateStrategy; TrainingRunner runner = TrainingRunner.builder() .trinityEndpoint("http://localhost:8080") .modelName("/path/to/model") .selectionStrategy(SamplingRateStrategy.of(0.1)) // 10% sampling .rewardCalculator(agent -> 0.0) // custom reward .commitIntervalSeconds(300) // commit every 5 minutes .build(); runner.start(); // intercept Agent calls and start sampling // Business code keeps using the Agent unmodified agent.call(msg).block(); runner.stop(); // stop the training pipeline ``` -------------------------------- ### Create and start a DingTalk channel with GatewayBootstrap (Java) Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-extensions/agentscope-extensions-channel/README.md Shows how to create a DingTalkChannel using the fromProperties factory, configure it with app credentials, and start a GatewayBootstrap to open the Stream WebSocket and begin dispatching. Requires a HarnessAgent and ChannelConfig. The channel internally wires up shared IdempotencyStore and BotLoopGuard utilities. ```java import io.agentscope.extensions.channel.dingtalk.DingTalkChannel; import io.agentscope.harness.agent.gateway.GatewayBootstrap; import io.agentscope.harness.agent.gateway.channel.ChannelConfig; import io.agentscope.harness.agent.HarnessAgent; import java.util.Map; HarnessAgent agent = HarnessAgent.builder() .name("main") .model("dashscope:qwen-plus") .build(); DingTalkChannel channel = DingTalkChannel.fromProperties( "my-dingtalk", ChannelConfig.of("my-dingtalk", "main"), Map.of( "appKey", "your-app-key", "appSecret", "your-app-secret", "robotCode", "your-robot-code" )); GatewayBootstrap gw = GatewayBootstrap.builder() .agent("main", agent) .channel(channel) .build(); gw.start(); // opens the Stream WebSocket and begins dispatching ``` -------------------------------- ### Start PAW with Aistio Integration Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/agents/agentscope-paw/README.md Environment variables and command to start the PAW agent with Aistio transcript support enabled. ```bash # Terminal 1 — control plane export AISTIO_TRANSCRIPT_FS_ROOT="$HOME/.agentscope/claw/transcripts" # start aistiod (:8081) # Terminal 2 — paw export DASHSCOPE_API_KEY=sk-... export CLAW_AISTIO_ENABLED=true export AISTIO_CONTROL_HTTP=http://localhost:8081 export BUILDER_INTERNAL_TOKEN=local-dev-internal-token-at-least-32chars export CLAW_AISTIO_AGENT_NAME=default export CLAW_AISTIO_NAMESPACE=default export CLAW_PORT=8090 java -jar agentscope-examples/agents/agentscope-paw/target/agentscope-paw-*.jar ``` -------------------------------- ### Quickstart: instantiate PostgresSkillRepository and register skills Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/skill/postgresql-repository.md Create a PostgresSkillRepository with a DataSource (e.g., HikariCP, PgBouncer). The boolean parameters enable auto-creation of schema/tables and allow writes. Then register all skills into a Toolkit. ```java import javax.sql.DataSource; import io.agentscope.core.skill.repository.postgresql.PostgresSkillRepository; DataSource ds = ...; // HikariCP, PgBouncer, etc. // createIfNotExist=true: auto-create schema and tables; writeable=true: allow writes PostgresSkillRepository repo = new PostgresSkillRepository(ds, true, true); Toolkit toolkit = new Toolkit(); repo.getAllSkills().forEach(toolkit::registerSkill); ``` -------------------------------- ### Quickstart: create MySQL state store with auto-create Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/session/mysql.md Creates a HikariCP data source and a MysqlAgentStateStore with createIfNotExist=true, which auto-creates the database and table. The store is then attached to a ReActAgent. ```java import com.zaxxer.hikari.HikariDataSource; import io.agentscope.core.state.AgentStateStore; import io.agentscope.extensions.mysql.state.MysqlAgentStateStore; HikariDataSource ds = new HikariDataSource(); ds.setJdbcUrl("jdbc:mysql://localhost:3306/agentscope?serverTimezone=UTC"); ds.setUsername("root"); ds.setPassword("***"); // Second arg createIfNotExist=true: auto-create database and table AgentStateStore stateStore = new MysqlAgentStateStore(ds, true); ReActAgent agent = ReActAgent.builder() .name("assistant") .model(model) .stateStore(stateStore) .build(); ``` -------------------------------- ### Quickstart: Build a SimpleKnowledge with DashScope embeddings and InMemoryStore Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/rag/simple.md Shows the full workflow: create an embedding model (DashScope), an in-memory vector store, assemble a SimpleKnowledge, ingest documents via TikaReader, and retrieve with a RetrieveConfig. Requires DASHSCOPE_API_KEY environment variable. ```java import io.agentscope.core.embedding.dashscope.DashScopeTextEmbedding; import io.agentscope.core.rag.knowledge.SimpleKnowledge; import io.agentscope.core.rag.store.InMemoryStore; import io.agentscope.core.rag.model.RetrieveConfig; // 1) Embedding model EmbeddingModel embeddings = DashScopeTextEmbedding.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("text-embedding-v3") .dimensions(1024) .build(); // 2) Vector store (in-process here) VDBStoreBase store = InMemoryStore.builder().dimensions(1024).build(); // 3) Assemble Knowledge SimpleKnowledge knowledge = SimpleKnowledge.builder() .embeddingModel(embeddings) .embeddingStore(store) .build(); // 4) Ingest documents List docs = new TikaReader().read(input).block(); knowledge.addDocuments(docs).block(); // 5) Retrieve List hits = knowledge.retrieve( "What is AgentScope?", RetrieveConfig.builder().limit(5).scoreThreshold(0.5).build() ).block(); ``` -------------------------------- ### Multi-replica customer-service agent configuration Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/docs/harness/filesystem.md Example of a multi-replica setup where three pods share a single Redis instance for state management. ```java DistributedStore store = RedisDistributedStore.fromJedis( new JedisPooled("redis://shared-redis:6379")); HarnessAgent agent = HarnessAgent.builder() .name("customer-service") .model(model) .workspace(Paths.get("/opt/agent/workspace")) .distributedStore(store) // stateStore + baseStore in one call .filesystem(new RemoteFilesystemSpec() .isolationScope(IsolationScope.USER) // one namespace per user .anonymousUserId("anonymous")) // fallback for unauthenticated callers .build(); ``` -------------------------------- ### Complete AgentScope Java Example Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/SKILL.md A full example showing how to create a DashScope model, register tools, define a streaming hook, build a ReActAgent, and call it with a user message. Note that .block() is only allowed in main() methods for demo purposes and should never be used in agent logic or service code. ```java package com.example.agentscope; import io.agentscope.core.ReActAgent; import io.agentscope.core.hook.Hook; import io.agentscope.core.hook.HookEvent; import io.agentscope.core.hook.ReasoningChunkEvent; import io.agentscope.core.memory.InMemoryMemory; import io.agentscope.core.message.Msg; import io.agentscope.core.message.MsgRole; import io.agentscope.core.message.TextBlock; import io.agentscope.core.model.Model; import io.agentscope.core.tool.Tool; import io.agentscope.core.tool.ToolParam; import io.agentscope.core.tool.Toolkit; import io.agentscope.extensions.model.dashscope.DashScopeChatModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * Complete example demonstrating AgentScope best practices. */ public class CompleteExample { private static final Logger log = LoggerFactory.getLogger(CompleteExample.class); public static void main(String[] args) { // 1. Create model (no .temperature() method, use defaultOptions) Model model = DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen-plus") .stream(true) .build(); // 2. Create toolkit with tools Toolkit toolkit = new Toolkit(); toolkit.registerTool(new WeatherTools()); toolkit.registerTool(new TimeTools()); // 3. Create hook for streaming output Hook streamingHook = new Hook() { @Override public Mono onEvent(T event) { if (event instanceof ReasoningChunkEvent e) { String text = e.getIncrementalChunk().getTextContent(); if (text != null) { System.out.print(text); } } return Mono.just(event); } @Override public int priority() { return 500; // Low priority } }; // 4. Build agent ReActAgent agent = ReActAgent.builder() .name("Assistant") .sysPrompt("You are a helpful assistant. Use tools when appropriate.") .model(model) .toolkit(toolkit) .memory(new InMemoryMemory()) .hook(streamingHook) .maxIters(10) .build(); // 5. Use agent Msg userMsg = Msg.builder() .role(MsgRole.USER) .content(TextBlock.builder() .text("What's the weather in San Francisco and what time is it?") .build()) .build(); try { System.out.println("User: " + userMsg.getTextContent()); System.out.print("Assistant: "); // ⚠️ IMPORTANT: .block() is ONLY allowed in main() methods for demo purposes // NEVER use .block() in agent logic, service methods, or library code Msg response = agent.call(userMsg).block(); System.out.println("\n\n--- Response Details ---"); System.out.println("Role: " + response.getRole()); System.out.println("Content: " + response.getTextContent()); } catch (Exception e) { log.error("Error during agent execution", e); System.err.println("Error: " + e.getMessage()); } } /** * Example tool class for weather information. */ public static class WeatherTools { @Tool(description = "Get current weather for a city. Returns temperature and conditions.") public String getWeather( @ToolParam(name = "city", description = "City name, e.g., 'San Francisco'") String city) { log.info("Getting weather for city: {}", city); // Simulate API call return String.format("Weather in %s: Sunny, 22°C, Light breeze", city); } } /** * Example tool class for time information. */ public static class TimeTools { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Tool(description = "Get current date and time") public String getCurrentTime() { LocalDateTime now = LocalDateTime.now(); String formatted = now.format(FORMATTER); log.info("Returning current time: {}", formatted); return "Current time: " + formatted; } } } ``` -------------------------------- ### Registering Tools with Toolkit Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/SKILL.md Demonstrates how to instantiate a Toolkit and register tool classes. ```java Toolkit toolkit = new Toolkit(); toolkit.registerTool(new WeatherTools()); toolkit.registerTool(new AsyncTools()); ``` -------------------------------- ### Initialize and run a HarnessAgent Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/docs/quickstart.md This example configures a HarnessAgent with a workspace path and compaction settings, then executes two turns within the same session to demonstrate state persistence. ```java import io.agentscope.core.agent.RuntimeContext; import io.agentscope.core.message.UserMessage; import io.agentscope.harness.agent.HarnessAgent; import io.agentscope.harness.agent.memory.compaction.CompactionConfig; import java.nio.file.Paths; public class FirstAgent { public static void main(String[] args) { HarnessAgent agent = HarnessAgent.builder() .name("note-taker") .sysPrompt("You are a note-taking assistant.") // String form resolved via ModelRegistry — picks up DASHSCOPE_API_KEY // from the environment. Use "openai:gpt-5.5", "anthropic:claude-sonnet-4-5", // "gemini:gemini-2.0-flash", or "ollama:llama3" to switch providers. .model("dashscope:qwen-plus") .workspace(Paths.get(".agentscope/workspace")) .compaction(CompactionConfig.builder() .triggerMessages(30) .keepMessages(10) .build()) .build(); RuntimeContext ctx = RuntimeContext.builder() .sessionId("demo-session") .userId("alice") .build(); // Turn 1: introduce yourself + state today's task agent.call(new UserMessage("My name is Alice, and I'm preparing a tech talk on ReAct today."), ctx).block(); // Turn 2: same sessionId — state from turn 1 is restored automatically agent.call(new UserMessage("What is my name? What am I doing today?"), ctx).block(); } } ``` -------------------------------- ### Handle leftover core.hooksPath failure Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/aistio/sdk/dsh/README.md If pnpm install/build fails with 'refusing to replace user-owned core.hooksPath', packages are already installed. Use DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE=1 to let leftover succeed once, then build and start. ```bash DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE=1 pnpm install pnpm run build pnpm dsh web ``` -------------------------------- ### Initialize GitSkillRepository Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/skill/git-repository.md Basic setup using a public repository, registering skills into a Toolkit, and ensuring cleanup on shutdown. ```java import io.agentscope.core.skill.repository.GitSkillRepository; import io.agentscope.core.skill.AgentSkill; // Public repo + default branch, temporary local directory GitSkillRepository repo = new GitSkillRepository( "https://github.com/agentscope/skills.git" ); // Register all skills into a Toolkit Toolkit toolkit = new Toolkit(); repo.getAllSkills().forEach(toolkit::registerSkill); // Clean up the temp directory on shutdown Runtime.getRuntime().addShutdownHook(new Thread(repo::close)); ``` -------------------------------- ### Quickstart Dify integration Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/rag/dify.md Initialize the Dify configuration and retrieve documents using the DifyKnowledge client. ```java import io.agentscope.core.rag.integration.dify.DifyKnowledge; import io.agentscope.core.rag.integration.dify.DifyRAGConfig; import io.agentscope.core.rag.integration.dify.RetrievalMode; import io.agentscope.core.rag.model.RetrieveConfig; DifyRAGConfig config = DifyRAGConfig.builder() .apiKey(System.getenv("DIFY_RAG_API_KEY")) .datasetId("your-dataset-id") .retrievalMode(RetrievalMode.HYBRID_SEARCH) .enableRerank(true) .build(); DifyKnowledge knowledge = DifyKnowledge.builder() .config(config) .build(); List hits = knowledge.retrieve( "How do I renew my membership?", RetrieveConfig.builder().limit(5).scoreThreshold(0.5).build() ).block(); ``` -------------------------------- ### Configure Agent Protocol properties in YAML Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/protocol/agent-protocol.md Example configuration for enabling the Agent Protocol integration. Set agentscope.agent-protocol.enabled to true to register the /tasks REST endpoints; streaming-enabled exposes SSE GET /tasks/{id}/events, hitl-enabled pauses tasks for tool confirmation and accepts /resume, and the sse-replay-buffer-size and sse-timeout-ms control SSE behavior. ```yaml agentscope: agent-protocol: enabled: true streaming-enabled: true hitl-enabled: true sse-replay-buffer-size: 256 sse-timeout-ms: 10800000 ``` -------------------------------- ### GET /invoke/v1/jobs/{invocationId} Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/controlplane/service-v5-api-contract.md Get the status of a job. ```APIDOC ## [GET] /invoke/v1/jobs/{invocationId} ### Description Get the status of a job. ### Method GET ### Endpoint /invoke/v1/jobs/{invocationId} ### Parameters #### Path Parameters - **invocationId** (string) - Required - The public invocation identifier. ### Response #### Success Response (200) - **job status** (object) - The status of the job. ``` -------------------------------- ### Deploy Sample Agent Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/aistio/helm/aistio/templates/NOTES.txt Apply a sample agent configuration and verify the resource creation. ```bash kubectl apply -f https://raw.githubusercontent.com/spring-ai-alibaba/aistio/main/config/samples/agent_declarative.yaml kubectl get agents ``` -------------------------------- ### GET /invoke/v1/conversations/{conversationId} Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/controlplane/service-v5-api-contract.md Get the details of a conversation. ```APIDOC ## [GET] /invoke/v1/conversations/{conversationId} ### Description Get the details of a conversation. ### Method GET ### Endpoint /invoke/v1/conversations/{conversationId} ### Parameters #### Path Parameters - **conversationId** (string) - Required - The unique identifier of the conversation. ### Response #### Success Response (200) - **conversation** (object) - The conversation details. ``` -------------------------------- ### GET /api/v1/agents/{agentId}/definition Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/controlplane/service-v5-api-contract.md Get the definition of a specific agent. ```APIDOC ## [GET] /api/v1/agents/{agentId}/definition ### Description Get the definition of a specific agent. ### Method GET ### Endpoint /api/v1/agents/{agentId}/definition ### Parameters #### Path Parameters - **agentId** (UUID) - Required - The unique identifier of the agent. ``` -------------------------------- ### Initialize MongoBaseStore Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/distributed/mongodb.md Set up filesystem KV storage for RemoteFilesystemSpec using MongoBaseStore. ```java import io.agentscope.extensions.mongodb.store.MongoBaseStore; BaseStore store = new MongoBaseStore(mongoClient.getDatabase("agentscope"), "agentscope_base"); ``` -------------------------------- ### Configure DistributedStore and RemoteFilesystemSpec Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/docs/others/going-to-production.md Demonstrates initializing a Redis-backed DistributedStore and injecting it into a HarnessAgent, with an alternative example for MySQL. ```java // Recommended: one-line configuration via DistributedStore DistributedStore store = RedisDistributedStore.fromJedis( new JedisPooled("redis://prod-redis:6379")); HarnessAgent agent = HarnessAgent.builder() .name("multi-tenant-agent") .model(model) .workspace(workspace) .distributedStore(store) // auto-wires stateStore + baseStore .filesystem(new RemoteFilesystemSpec() // baseStore injected from store .isolationScope(IsolationScope.USER) .workspaceIndex(WorkspaceIndex.open(workspace))) // speeds up ls/glob .build(); // Or with MySQL: DistributedStore mysqlStore = MysqlDistributedStore.create(dataSource); ``` -------------------------------- ### GET /invoke/v1/jobs/{invocationId}/artifacts/{artifactId} Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/controlplane/service-v5-api-contract.md Get a specific artifact produced by a job. ```APIDOC ## [GET] /invoke/v1/jobs/{invocationId}/artifacts/{artifactId} ### Description Get a specific artifact produced by a job. ### Method GET ### Endpoint /invoke/v1/jobs/{invocationId}/artifacts/{artifactId} ### Parameters #### Path Parameters - **invocationId** (string) - Required - The public invocation identifier. - **artifactId** (string) - Required - The unique identifier of the artifact. ### Response #### Success Response (200) - **artifact** (object) - The artifact content. ``` -------------------------------- ### Initialize NacosSkillRepository Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/integration/infrastructure/nacos.md Configure the skill repository to download skills. Version takes precedence over labels if both are resolved. ```java import io.agentscope.core.nacos.skill.NacosSkillRepository; Properties props = new Properties(); props.setProperty(NacosSkillRepository.SKILL_VERSION_PATH, "1.2.0"); // or SKILL_LABEL_PATH = "stable" NacosSkillRepository repo = new NacosSkillRepository(aiService, "default-namespace", props); AgentSkill skill = repo.getSkill("calculator"); ``` -------------------------------- ### Install Aistio SDK Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/service/external-agent.md Install the specific version of the Aistio SDK required for your release. ```bash python -m pip install "aistio-sdk==$AISTIO_SDK_VERSION" ``` -------------------------------- ### Verify CRD Installation Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/aistio/helm/aistio/templates/NOTES.txt List installed CRDs and filter for those belonging to the agentscope.io group. ```bash kubectl get crds | grep agentscope.io ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/CONTRIBUTING.md Examples of commit messages using the specified types and scopes. ```bash feat(models): add support for Claude-3 model fix(agent): resolve memory leak in ReActAgent docs(readme): update installation instructions refactor(formatter): simplify message formatting logic ci(models): add unit tests for OpenAI integration ``` -------------------------------- ### Launch agentscope-paw application Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/agents/agentscope-paw/README.md Set the API key, build the project, and execute the JAR file to start the application. ```bash export DASHSCOPE_API_KEY=sk-... mvn -pl agentscope-examples/agents/agentscope-paw -am clean package -DskipTests java -jar agentscope-examples/agents/agentscope-paw/target/agentscope-paw-*.jar ``` -------------------------------- ### GET /invoke/v1/jobs/{invocationId}/events Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/controlplane/service-v5-api-contract.md Get the event stream for a job. The stream is resumable using Last-Event-ID. ```APIDOC ## [GET] /invoke/v1/jobs/{invocationId}/events ### Description Get the event stream for a job. The stream is resumable using Last-Event-ID. ### Method GET ### Endpoint /invoke/v1/jobs/{invocationId}/events ### Parameters #### Path Parameters - **invocationId** (string) - Required - The public invocation identifier. ### Response #### Success Response (200) - **event stream** (SSE) - A resumable SSE stream of events. ``` -------------------------------- ### GET /invoke/v1/conversations/{conversationId}/events Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/controlplane/service-v5-api-contract.md Get the event stream for a conversation. The stream is resumable using Last-Event-ID. ```APIDOC ## [GET] /invoke/v1/conversations/{conversationId}/events ### Description Get the event stream for a conversation. The stream is resumable using Last-Event-ID. ### Method GET ### Endpoint /invoke/v1/conversations/{conversationId}/events ### Parameters #### Path Parameters - **conversationId** (string) - Required - The unique identifier of the conversation. ### Response #### Success Response (200) - **event stream** (SSE) - A resumable SSE stream of events. ``` -------------------------------- ### Start the AgentScope Service components Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/blogs/agentscope-service-release.md Set the API key and execute the development startup script to launch the control plane and dataplane. ```bash export DASHSCOPE_API_KEY=sk-xxx cd agentscope-service scripts/dev-down.sh && BUILDER_REBUILD=1 scripts/dev-up.sh ``` -------------------------------- ### GET /api/environments/{id}/work/stats Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/managed_agents/events/worker.md Get counts and oldest queued age. Requires X-Builder-Environment-Key header. ```APIDOC ## GET /api/environments/{id}/work/stats ### Description Get counts and oldest queued age. ### Method GET ### Endpoint /api/environments/{id}/work/stats ### Parameters #### Path Parameters - **id** (string) - Required - Environment ID ### Response #### Success Response (200) - **counts** (object) - Counts by state - **oldestQueuedAge** (integer) - Age of oldest queued item in seconds #### Response Example { "counts": { "queued": 1, "active": 0 }, "oldestQueuedAge": 30 } ``` -------------------------------- ### Set up environment and verify release Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/release/README.md Commands to create a Python virtual environment, install release dependencies, and run the release verifier. Requires Java 21, Maven, Go, Node.js 22, Python 3.10+, Docker Buildx, and Helm 3.17+. ```bash python3 -m venv .venv . .venv/bin/activate pip install -r agentscope-service/release/requirements.txt -e 'agentscope-service/aistio/sdk/python[dev]' python agentscope-service/release/release.py verify ``` -------------------------------- ### GET /api/environments/{id}/work/{workId} Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/managed_agents/events/worker.md Get a single work item by ID. Requires X-Builder-Environment-Key header. ```APIDOC ## GET /api/environments/{id}/work/{workId} ### Description Get a single work item by ID. ### Method GET ### Endpoint /api/environments/{id}/work/{workId} ### Parameters #### Path Parameters - **id** (string) - Required - Environment ID - **workId** (string) - Required - Work item ID ### Response #### Success Response (200) - **work** (object) - The work item #### Response Example { "work": { "id": "work-123" } } ``` -------------------------------- ### GET /api/environments/{id}/sessions/{sessionId}/skills Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-service/docs/managed_agents/events/worker.md Get skills bundle for staging under /workspace/skills. Requires X-Builder-Environment-Key header. ```APIDOC ## GET /api/environments/{id}/sessions/{sessionId}/skills ### Description Get skills bundle for staging under /workspace/skills. ### Method GET ### Endpoint /api/environments/{id}/sessions/{sessionId}/skills ### Parameters #### Path Parameters - **id** (string) - Required - Environment ID - **sessionId** (string) - Required - Session ID ### Response #### Success Response (200) - **skills** (object) - Skills bundle #### Response Example { "skills": {} } ``` -------------------------------- ### ToolGroupExample Prompts Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/README.md Example prompts to test autonomous tool group activation. ```text You> Calculate the factorial of 5 ``` ```text You> Ping google.com ``` ```text You> List files in /tmp ``` ```text You> Calculate factorial of 7 and then ping github.com ``` ```text You> Check if 17 is prime, then list files in /tmp ``` -------------------------------- ### Example response fields Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/service/first-session.md Example JSON response fields returned by the API. Use the actual IDs and status returned. ```json { "invocationId": "INVOCATION_ID", "conversationId": "CONVERSATION_ID", "status": "running", "statusUrl": "/invoke/v1/conversations/CONVERSATION_ID", "eventsUrl": "/invoke/v1/conversations/CONVERSATION_ID/events?invocationId=INVOCATION_ID" } ``` -------------------------------- ### Set up and launch the Coding Agent CLI Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/agentscope-examples/agents/agentscope-codingagent/README.md Set the DashScope API key, build dependencies, and launch the interactive CLI. The agent operates in its own workspace at ~/.agentscope/codingagent/workspace/. ```bash # 1. Set your model key (default model is DashScope; OpenAI / Anthropic also supported, see ENV_VARS.md) export DASHSCOPE_API_KEY=sk-... # 2. From the repo root, build dependencies once (skip on subsequent runs) cd agentscope-java mvn install -pl agentscope-examples/agents/agentscope-codingagent -am -DskipTests -q # 3. Launch the CLI (re-run this anytime to chat again) mvn exec:java -pl agentscope-examples/agents/agentscope-codingagent ``` -------------------------------- ### Initialize HarnessAgent and ChatUiChannel Source: https://github.com/agentscope-ai-java/agentscope-java/blob/master/docs/v2/en/docs/harness/channel.md Demonstrates creating a HarnessAgent and binding a ChatUiChannel to send messages with automatic session management based on userId. ```java HarnessAgent agent = HarnessAgent.builder() .name("assistant") .sysPrompt("You are a helpful assistant.") .model("dashscope:qwen-plus") .build(); // Bind a ChatUI channel. ChatUiChannel chat = agent.channel(ChatUiChannel.create()); // Send messages. Each userId gets its own session automatically. Msg reply = chat.send(SendOptions.userId("user-1"), "Hello!").block(); // Same user, same session — conversation continues. Msg followUp = chat.send(SendOptions.userId("user-1"), "Tell me more.").block(); // Different user, different session. Msg otherUser = chat.send(SendOptions.userId("user-2"), "Hi there").block(); ```