### Install Dependencies Source: https://doc.agentscope.io/tutorial/task_eval_openjudge.html Install the necessary libraries for AgentScope and OpenJudge. This is a prerequisite for running the evaluation examples. ```bash pip install agentscope py-openjudge ``` -------------------------------- ### Start AgentScope Studio Source: https://doc.agentscope.io/_sources/tutorial/task_studio.rst.txt Starts the AgentScope Studio application from the command line. This command should be run after the Studio has been installed. ```bash as_studio ``` -------------------------------- ### Install and Start AgentScope Studio Source: https://doc.agentscope.io/_downloads/a29fb4d5a2f8a541ea7628de96d494f5/task_studio.ipynb Commands to install the AgentScope Studio package globally via npm and launch the studio application from the command line. ```bash npm install -g @agentscope/studio as_studio ``` -------------------------------- ### Verify AgentScope Installation Source: https://doc.agentscope.io/_downloads/ff098ddfc7896640c06c203d7c96131a/quickstart_installation.ipynb A simple Python script to import the library and print the installed version to confirm successful setup. ```python import agentscope print(agentscope.__version__) ``` -------------------------------- ### Initializing a Realtime Agent in Python Source: https://doc.agentscope.io/tutorial/task_realtime.html Demonstrates how to create and initialize a `RealtimeAgent` with a specified model and system prompt. It sets up an asynchronous queue to handle messages from the agent and starts the agent's communication loop. This example requires the `dashscope` and `asyncio` libraries. ```python import os import asyncio from agentscope.agents import RealtimeAgent from agentscope.models import DashScopeRealtimeModel async def example_realtime_agent() -> None: """Example of creating and using a realtime agent.""" agent = RealtimeAgent( name="Friday", sys_prompt="You are a helpful assistant named Friday.", model=DashScopeRealtimeModel( model_name="qwen3-omni-flash-realtime", api_key=os.getenv("DASHSCOPE_API_KEY"), ), ) # Create a queue to receive messages from the agent outgoing_queue = asyncio.Queue() # The agent is now ready to handle inputs # Handle outgoing messages in a separate task async def handle_agent_messages(): while True: event = await outgoing_queue.get() # Process the event (e.g., send to frontend via WebSocket) print(f"Agent event: {event.type}") # Start the message handling task asyncio.create_task(handle_agent_messages()) # Start the agent (establishes connection) await agent.start(outgoing_queue) # Stop the agent when done await agent.stop() ``` -------------------------------- ### QA Benchmark Setup with OpenJudge Graders Source: https://doc.agentscope.io/_sources/tutorial/task_eval_openjudge.rst.txt This example demonstrates setting up a QA benchmark using AgentScope's BenchmarkBase and integrating OpenJudge's RelevanceGrader and CorrectnessGrader. Ensure your DASHSCOPE_API_KEY is set. ```Python import os from typing import Generator from openjudge.graders.common.relevance import RelevanceGrader from openjudge.graders.common.correctness import CorrectnessGrader from agentscope.evaluate import ( Task, BenchmarkBase, ) class QABenchmark(BenchmarkBase): """A benchmark for QA tasks using OpenJudge metrics.""" def __init__(self): super().__init__( name="QA Quality Benchmark", description="Benchmark to evaluate QA systems using OpenJudge grader classes", ) self.dataset = self._load_data() def _load_data(self): tasks = [] # Configuration for LLM-based graders # Ensure OPENAI_API_KEY is set in your environment variables model_config = { "model": "qwen3-32b", "api_key": os.environ.get("DASHSCOPE_API_KEY"), ``` -------------------------------- ### Example Reasoning with DashScopeChatModel Source: https://doc.agentscope.io/tutorial/task_model.html Demonstrates how to use the DashScopeChatModel with reasoning enabled to get a thinking process before the final response. Ensure the DASHSCOPE_API_KEY environment variable is set. ```python async def example_reasoning() -> None: """An example of using the reasoning model.""" model = DashScopeChatModel( model_name="qwen-turbo", api_key=os.environ["DASHSCOPE_API_KEY"], enable_thinking=True, ) res = await model( messages=[ {"role": "user", "content": "Who am I?"}, ], ) last_chunk = None async for chunk in res: last_chunk = chunk print("The final response:") print(last_chunk) asyncio.run(example_reasoning()) ``` -------------------------------- ### Agent State Management Example Source: https://doc.agentscope.io/_sources/tutorial/task_state.rst.txt Demonstrates how to interact with an agent, print its state, and then load an initial state. ```Python async def example_agent_state() -> None: """Example of agent state management""" await agent(Msg("user", "Hello, agent!", "user")) print("State of the agent after generating a reply:") print(json.dumps(agent.state_dict(), indent=4)) asyncio.run(example_agent_state()) ``` ```Python agent.load_state_dict(initial_state) print("State after loading the initial state:") print(json.dumps(agent.state_dict(), indent=4)) ``` ```Python # change the agent state by generating a reply message asyncio.run(example_agent_state()) print("\nState of agent:") print(json.dumps(agent.state_dict(), indent=4)) ``` -------------------------------- ### Initializing a Realtime Agent Source: https://doc.agentscope.io/_downloads/b9ea2d5f1a0b19c3900464ff9de7596e/task_realtime.ipynb Example of how to initialize and use a Realtime Agent. ```APIDOC ## Initializing a Realtime Agent Here's how to create and use a realtime agent: ```python # Example usage (conceptual) from agentscope.agents import RealtimeAgent # Assuming you have a realtime model client initialized # realtime_model = ... # Initialize the RealtimeAgent agent = RealtimeAgent(model=realtime_model) # Example of sending a client event (e.g., text input) # agent.receive(ClientEvents.ClientTextAppendEvent(content='Hello agent!')) # Example of processing server events (e.g., agent response) # for event in agent.stream(): # if isinstance(event, ServerEvents.AgentResponseAudioDeltaEvent): # # Process audio chunk # pass # elif isinstance(event, ServerEvents.AgentResponseDoneEvent): # # Agent finished response # break ``` ``` -------------------------------- ### Using ChatRoom for Multi-Agent Realtime Conversation Source: https://doc.agentscope.io/_downloads/b9ea2d5f1a0b19c3900464ff9de7596e/task_realtime.ipynb Demonstrates how to create and use the ChatRoom class to manage multiple realtime agents. It initializes agents, sets up a chat room, starts the room to handle messages, simulates frontend input, and stops the room. This example requires the 'agentscope' library and an environment variable 'DASHSCOPE_API_KEY'. ```python async def example_chat_room() -> None: """Example of using ChatRoom with multiple realtime agents.""" from agentscope.pipeline import ChatRoom from agentscope.agent import RealtimeAgent from agentscope.realtime import DashScopeRealtimeModel # Create multiple agents agent1 = RealtimeAgent( name="Agent1", sys_prompt="You are Agent1, a helpful assistant.", model=DashScopeRealtimeModel( model_name="qwen3-omni-flash-realtime", api_key=os.getenv("DASHSCOPE_API_KEY"), ), ) agent2 = RealtimeAgent( name="Agent2", sys_prompt="You are Agent2, a helpful assistant.", model=DashScopeRealtimeModel( model_name="qwen3-omni-flash-realtime", api_key=os.getenv("DASHSCOPE_API_KEY"), ), ) # Create a chat room with multiple agents chat_room = ChatRoom(agents=[agent1, agent2]) # Create queue to receive messages from all agents outgoing_queue = asyncio.Queue() # Start the chat room await chat_room.start(outgoing_queue) # Handle input from frontend # The chat room will broadcast to all agents from agentscope.realtime import ClientEvents client_event = ClientEvents.ClientTextAppendEvent( session_id="session1", text="Hello everyone!", ) await chat_room.handle_input(client_event) # Stop the chat room when done await chat_room.stop() ``` -------------------------------- ### Run Example Pipeline Source: https://doc.agentscope.io/_downloads/a841049f564cf5f9c0fea523e59490f5/task_pipeline.ipynb This snippet demonstrates how to run an example pipeline that streams and prints messages from an agent. It shows agent creation, disabling console output for cleaner logs, and iterating through streaming messages. ```APIDOC ## Run Example Pipeline ### Description This example demonstrates running a pipeline that streams and prints messages from an agent. It includes agent creation, disabling console output for cleaner logs, and iterating through streaming messages. ### Method N/A (Python function execution) ### Endpoint N/A ### Parameters N/A ### Request Example ```python async def run_example_pipeline() -> None: """Run an example of streaming printing messages.""" agent = create_agent("Alice", 20, "student") # We disable the terminal printing to avoid messy outputs agent.set_console_output_enabled(False) async for msg, last in stream_printing_messages( agents=[agent], coroutine_task=agent( Msg("user", "Hello, who are you?", "user"), ), ): print(msg, last) if last: print() asyncio.run(run_example_pipeline()) ``` ### Response N/A (Prints output to console) ``` -------------------------------- ### Example Output for Token Counting Source: https://doc.agentscope.io/tutorial/task_token.html This is the expected output when running the token counting example. ```text Number of tokens: 21 ``` -------------------------------- ### Install AgentScope from Source Source: https://doc.agentscope.io/_downloads/ff098ddfc7896640c06c203d7c96131a/quickstart_installation.ipynb Clones the repository from GitHub and installs the package in editable mode for development purposes. ```bash git clone -b main https://github.com/agentscope-ai/agentscope cd agentscope pip install -e . ``` -------------------------------- ### Tool Use Example Source: https://doc.agentscope.io/tutorial/workflow_multiagent_debate.html An example of a tool use action, specifying the tool name and its input parameters. ```json { "type": "tool_use", "name": "generate_response", "input": { "correct_answer": "4", "finished": true }, "id": "call_4f4db0d567a24252a8f8ba" } ``` -------------------------------- ### Agent Output Example Source: https://doc.agentscope.io/tutorial/quickstart_agent.html Shows the expected output from the 'MyAgent' when it responds to a user query. ```text Friday: I'm Friday, your helpful assistant! How can I assist you today? ``` -------------------------------- ### Setup for Multi-Agent Debate Source: https://doc.agentscope.io/_sources/tutorial/workflow_multiagent_debate.rst.txt Imports necessary libraries and defines the debate topic. This sets up the environment for the multi-agent discussion. ```Python import asyncio import os from pydantic import Field, BaseModel from agentscope.agent import ReActAgent from agentscope.formatter import ( DashScopeMultiAgentFormatter, DashScopeChatFormatter, ) from agentscope.message import Msg from agentscope.model import DashScopeChatModel from agentscope.pipeline import MsgHub # Prepare a topic topic = ( "The two circles are externally tangent and there is no relative sliding. " "The radius of circle A is 1/3 the radius of circle B. Circle A rolls " "around circle B one trip back to its starting point. How many times will " "circle A revolve in total?" ) ``` -------------------------------- ### Initialize and Use Realtime Agent (Python) Source: https://doc.agentscope.io/_sources/tutorial/task_realtime.rst.txt Demonstrates how to create and initialize a RealtimeAgent with a specified model and system prompt. It also sets up a queue to handle outgoing events from the agent and starts a task to process these events. ```Python async def example_realtime_agent() -> None: """Example of creating and using a realtime agent.""" agent = RealtimeAgent( name="Friday", sys_prompt="You are a helpful assistant named Friday.", model=DashScopeRealtimeModel( model_name="qwen3-omni-flash-realtime", api_key=os.getenv("DASHSCOPE_API_KEY"), ), ) # Create a queue to receive messages from the agent outgoing_queue = asyncio.Queue() # The agent is now ready to handle inputs # Handle outgoing messages in a separate task async def handle_agent_messages(): while True: event = await outgoing_queue.get() # Process the event (e.g., send to frontend via WebSocket) print(f"Agent event: {event.type}") # Start the message handling task asyncio.create_task(handle_agent_messages()) ``` -------------------------------- ### Registering and Using Agent Skills Source: https://doc.agentscope.io/tutorial/task_agent_skill.html Demonstrates how to initialize a Toolkit, register a skill directory, and generate the corresponding system prompt for an agent. ```python from agentscope.tool import Toolkit # Initialize toolkit and register skill toolkit = Toolkit() toolkit.register_agent_skill("sample_skill") # Generate prompt for the agent agent_skill_prompt = toolkit.get_agent_skill_prompt() print("Agent Skill Prompt:") print(agent_skill_prompt) ``` -------------------------------- ### Create and Run ReAct Agent Example Source: https://doc.agentscope.io/_downloads/aa553c3d61de8335d21a5136b32f5098/quickstart_agent.ipynb Demonstrates how to instantiate a ReActAgent with specified tools, model, formatter, and memory, then uses it to process a user message. ```python async def creating_react_agent() -> None: """Create a ReAct agent and run a simple task.""" # Prepare tools toolkit = Toolkit() toolkit.register_tool_function(execute_python_code) jarvis = ReActAgent( name="Jarvis", sys_prompt="You're a helpful assistant named Jarvis", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], stream=True, enable_thinking=False, ), formatter=DashScopeChatFormatter(), toolkit=toolkit, memory=InMemoryMemory(), ) msg = Msg( name="user", content="Hi! Jarvis, run Hello World in Python.", role="user", ) await jarvis(msg) asyncio.run(creating_react_agent()) ``` -------------------------------- ### Initializing MCP Clients Source: https://doc.agentscope.io/_downloads/da545788627514321d5d0429de9a0028/task_mcp.ipynb Demonstrates how to instantiate both stateful and stateless HTTP clients for an MCP server. ```python stateful_client = HttpStatefulClient( name="mcp_services_stateful", transport="streamable_http", url=f"https://mcp.amap.com/mcp?key={os.environ['GAODE_API_KEY']}", ) stateless_client = HttpStatelessClient( name="mcp_services_stateless", transport="streamable_http", url=f"https://mcp.amap.com/mcp?key={os.environ['GAODE_API_KEY']}", ) ``` -------------------------------- ### GET /plan_notebook/get_current_hint Source: https://doc.agentscope.io/_downloads/a776edd4ceeb1e1c060eeaa2e2a79b11/task_plan.ipynb Retrieves the current hint message that guides the agent's next reasoning step. ```APIDOC ## GET /plan_notebook/get_current_hint ### Description Fetches the current hint message injected into the agent's reasoning process based on the active plan. ### Method GET ### Endpoint /plan_notebook/get_current_hint ### Response #### Success Response (200) - **name** (string) - The name of the current hint. - **content** (string) - The detailed hint content. #### Response Example { "name": "Current Step", "content": "Search for survey papers on Google Scholar." } ``` -------------------------------- ### Tablestore Memory in FastAPI Source: https://doc.agentscope.io/_downloads/614c62124a3a81f471b56e3377ea63d0/task_memory.ipynb Illustrates integrating TablestoreMemory into a FastAPI application for persistent chat memory. This example is a starting point and requires further implementation for full functionality. ```python import os from fastapi import FastAPI from agentscope.memory import TablestoreMemory from agentscope.message import Msg app = FastAPI() @app.post("/chat_endpoint") async def chat_endpoint(user_id: str ``` -------------------------------- ### Initialize and Manage a RealtimeAgent Source: https://doc.agentscope.io/_downloads/b9ea2d5f1a0b19c3900464ff9de7596e/task_realtime.ipynb Demonstrates how to instantiate a RealtimeAgent with a DashScope model, set up an asynchronous message queue, and manage the agent's lifecycle using start and stop methods. ```python async def example_realtime_agent() -> None: agent = RealtimeAgent( name="Friday", sys_prompt="You are a helpful assistant named Friday.", model=DashScopeRealtimeModel( model_name="qwen3-omni-flash-realtime", api_key=os.getenv("DASHSCOPE_API_KEY"), ), ) outgoing_queue = asyncio.Queue() async def handle_agent_messages(): while True: event = await outgoing_queue.get() print(f"Agent event: {event.type}") asyncio.create_task(handle_agent_messages()) await agent.start(outgoing_queue) await agent.stop() ``` -------------------------------- ### Configure and Preview Task Dataset Source: https://doc.agentscope.io/_downloads/243e482519a51e80a9f627d3dbd503d2/task_tuner.ipynb Demonstrates how to initialize a DatasetConfig using a local directory path and preview the loaded data samples to ensure correct formatting. ```python from agentscope.tuner import DatasetConfig dataset = DatasetConfig(path="my_dataset", split="train") dataset.preview(n=2) ``` -------------------------------- ### Import necessary modules for AgentScope memory Source: https://doc.agentscope.io/_sources/tutorial/task_memory.rst.txt Imports required classes for different memory implementations and message handling. This setup is common for examples involving memory operations. ```Python import asyncio import json import fakeredis from sqlalchemy.ext.asyncio import create_async_engine from agentscope.memory import ( InMemoryMemory, AsyncSQLAlchemyMemory, RedisMemory, ) from agentscope.message import Msg ``` -------------------------------- ### Initialize Toolkit and Register Agent Skills Source: https://doc.agentscope.io/_downloads/49581b9ec49c0c26280f5d25c406d988/task_agent_skill.ipynb Demonstrates how to instantiate the Toolkit class and register a skill directory. The directory must contain a SKILL.md file with YAML frontmatter. ```python import os from agentscope.tool import Toolkit # Prepare directory os.makedirs("sample_skill", exist_ok=True) with open("sample_skill/SKILL.md", "w", encoding="utf-8") as f: f.write("---\nname: sample_skill\ndescription: A sample agent skill for demonstration.\n---\n\n# Sample Skill\n...\n") # Register skill toolkit = Toolkit() toolkit.register_agent_skill("sample_skill") ``` -------------------------------- ### Initialize Realtime Models (DashScope, OpenAI, Gemini) Source: https://doc.agentscope.io/_downloads/b9ea2d5f1a0b19c3900464ff9de7596e/task_realtime.ipynb Demonstrates how to initialize different realtime model providers including DashScope, OpenAI, and Gemini. It shows setting model names, API keys, voice options, and enabling audio transcription. ```python # DashScope realtime model dashscope_model = DashScopeRealtimeModel( model_name="qwen3-omni-flash-realtime", api_key=os.getenv("DASHSCOPE_API_KEY"), voice="Cherry", # Options: "Cherry", "Serena", "Ethan", "Chelsie" enable_input_audio_transcription=True, ) # OpenAI realtime model openai_model = OpenAIRealtimeModel( model_name="gpt-4o-realtime-preview", api_key=os.getenv("OPENAI_API_KEY"), voice="alloy", # Options: "alloy", "echo", "marin", "cedar" enable_input_audio_transcription=True, ) # Gemini realtime model gemini_model = GeminiRealtimeModel( model_name="gemini-2.5-flash-native-audio-preview-09-2025", api_key=os.getenv("GEMINI_API_KEY"), voice="Puck", # Options: "Puck", "Charon", "Kore", "Fenrir" enable_input_audio_transcription=True, ) ``` -------------------------------- ### Run Concurrent Agents using asyncio.gather in Python Source: https://doc.agentscope.io/_downloads/f527c4754f6b5d0f59f17934af084403/workflow_concurrent_agents.ipynb This Python code defines an example agent that simulates a long-running task and then executes two instances of this agent concurrently using asyncio.gather. It measures and prints the start and end times for each agent to demonstrate parallel execution. ```python import asyncio from datetime import datetime from typing import Any from agentscope.agent import AgentBase class ExampleAgent(AgentBase): """The example agent for concurrent execution.""" def __init__(self, name: str) -> None: """Initialize the agent with its name.""" super().__init__() self.name = name async def reply(self, *args: Any, **kwargs: Any) -> None: """Reply to the message.""" start_time = datetime.now().strftime("%H:%M:%S.%f")[:-3] print(f"{self.name} started at {start_time}") await asyncio.sleep(3) # Simulate a long-running task end_time = datetime.now().strftime("%H:%M:%S.%f")[:-3] print(f"{self.name} finished at {end_time}") async def run_concurrent_agents() -> None: """Run the concurrent agents.""" agent1 = ExampleAgent("Agent 1") agent2 = ExampleAgent("Agent 2") await asyncio.gather(agent1(), agent2()) asyncio.run(run_concurrent_agents()) ``` -------------------------------- ### Count Tokens with OpenAI Token Counter Source: https://doc.agentscope.io/_downloads/88e9480ef84c8c1b502a18c720aefa2a/task_token.ipynb This example demonstrates how to use the OpenAITokenCounter to calculate the number of tokens in a list of messages. It initializes the counter with a specific model name and then calls the count method to get the token estimate. This is useful for managing API costs and prompt length. ```python import asyncio from agentscope.token import OpenAITokenCounter async def example_token_counting(): # Example messages messages = [ {"role": "user", "content": "Hello!"}, {"role": "assistant", "content": "Hi, how can I help you?"}, ] # OpenAI token counting openai_counter = OpenAITokenCounter(model_name="gpt-4.1") n_tokens = await openai_counter.count(messages) print(f"Number of tokens: {n_tokens}") asyncio.run(example_token_counting()) ``` -------------------------------- ### Initialize Routing Agent with Structured Output Source: https://doc.agentscope.io/tutorial/workflow_routing.html Initializes a ReActAgent configured as a router. It uses DashScopeChatModel and DashScopeChatFormatter. The agent's system prompt guides it to route user queries to appropriate follow-up tasks. This setup is suitable for direct routing based on agent's understanding. ```python import asyncio import json import os from typing import Literal from pydantic import BaseModel, Field from agentscope.agent import ReActAgent from agentscope.formatter import DashScopeChatFormatter from agentscope.memory import InMemoryMemory from agentscope.message import Msg from agentscope.model import DashScopeChatModel from agentscope.tool import Toolkit, ToolResponse router = ReActAgent( name="Router", sys_prompt="You're a routing agent. Your target is to route the user query to the right follow-up task.", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], stream=False, ), formatter=DashScopeChatFormatter(), ) # Use structured output to specify the routing task class RoutingChoice(BaseModel): your_choice: Literal[ "Content Generation", "Programming", "Information Retrieval", None, ] = Field( description="Choose the right follow-up task, and choose ``None`` if the task is too simple or no suitable task", ) task_description: str | None = Field( description="The task description", default=None, ) async def example_router_explicit() -> None: """Example of explicit routing with structured output.""" msg_user = Msg( "user", "Help me to write a poem", "user", ) # Route the query msg_res = await router( msg_user, structured_model=RoutingChoice, ) # The structured output is stored in the metadata field print("The structured output:") print(json.dumps(msg_res.metadata, indent=4, ensure_ascii=False)) asyncio.run(example_router_explicit()) ``` -------------------------------- ### Install Tablestore Memory Packages Source: https://doc.agentscope.io/_sources/tutorial/task_memory.rst.txt Command to install the necessary packages for Tablestore memory. ```bash pip install tablestore tablestore-for-agent-memory ``` -------------------------------- ### Tool Result Example Source: https://doc.agentscope.io/tutorial/workflow_multiagent_debate.html An example of a tool result, indicating the outcome of a previously called tool. ```json { "type": "tool_result", "id": "call_4f4db0d567a24252a8f8ba", "name": "generate_response", "output": [ { "type": "text", "text": "Successfully generated response." } ] } ``` -------------------------------- ### Initialize ReActAgent with Plan Notebook Source: https://doc.agentscope.io/_downloads/a776edd4ceeb1e1c060eeaa2e2a79b11/task_plan.ipynb Demonstrates how to initialize the ReActAgent, specifying a system prompt, a language model, a formatter, and a PlanNotebook for agent-managed plan execution. ```APIDOC ## Initialize ReActAgent with Plan Notebook ### Description Initialize the `ReActAgent` with a system prompt, a language model (e.g., `DashScopeChatModel`), a formatter, and a `PlanNotebook` instance. This setup allows the agent to create and manage its own execution plans. ### Method Initialization (Constructor) ### Endpoint N/A (Code Initialization) ### Parameters - **name** (string) - Required - The name of the agent. - **sys_prompt** (string) - Required - The system prompt that guides the agent's behavior. - **model** (object) - Required - The language model to be used by the agent (e.g., `DashScopeChatModel`). - **formatter** (object) - Required - The formatter for the language model's input/output. - **plan_notebook** (object) - Required - An instance of `PlanNotebook` to enable agent-managed plan execution. ### Request Example ```python agent = ReActAgent( name="Friday", sys_prompt="You are a helpful assistant.", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], ), formatter=DashScopeChatFormatter(), plan_notebook=PlanNotebook(), ) ``` ### Response N/A (Initialization does not return a response in this context) ``` -------------------------------- ### Install Tablestore Dependencies Source: https://doc.agentscope.io/_downloads/614c62124a3a81f471b56e3377ea63d0/task_memory.ipynb Installs the necessary Python packages for using Tablestore with AgentScope memory. ```bash pip install tablestore tablestore-for-agent-memory ``` -------------------------------- ### List PlanNotebook Tools Source: https://doc.agentscope.io/_downloads/a776edd4ceeb1e1c060eeaa2e2a79b11/task_plan.ipynb This snippet demonstrates how to instantiate a PlanNotebook and list all available tool functions provided by the notebook. ```python plan_notebook = PlanNotebook() async def list_tools() -> None: """List the tool functions provided by PlanNotebook.""" print("The tools provided by PlanNotebook:") for tool in plan_notebook.list_tools(): print(tool.__name__) asyncio.run(list_tools()) ``` -------------------------------- ### Setting up Agents and MsgHub for Conversation Source: https://doc.agentscope.io/_sources/tutorial/workflow_conversation.rst.txt This code initializes multiple ReActAgents with a shared model and formatter, then sets up an asynchronous MsgHub to facilitate their conversation with an initial announcement. ```python model = DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], ) formatter = DashScopeMultiAgentFormatter() alice = ReActAgent( name="Alice", sys_prompt="You're a student named Alice.", model=model, formatter=formatter, toolkit=Toolkit(), memory=InMemoryMemory(), ) bob = ReActAgent( name="Bob", sys_prompt="You're a student named Bob.", model=model, formatter=formatter, toolkit=Toolkit(), memory=InMemoryMemory(), ) charlie = ReActAgent( name="Charlie", sys_prompt="You're a student named Charlie.", model=model, formatter=formatter, toolkit=Toolkit(), memory=InMemoryMemory(), ) async def example_msghub() -> None: """Example of using MsgHub for multi-agent conversation.""" async with MsgHub( [alice, bob, charlie], announcement=Msg( "system", "Now you meet each other with a brief self-introduction.", "system", ), ): await alice() await bob() await charlie() asyncio.run(example_msghub()) ``` -------------------------------- ### Record User Preferences with Agent Source: https://doc.agentscope.io/tutorial/task_long_term_memory.html This example demonstrates how to record user preferences by having a conversation with the agent. The agent's response is shown. ```python async def record_preferences(): """ReAct agent integration example""" # Conversation example msg = Msg( "user", "When I travel to Hangzhou, I like staying in homestays", "user", ) await agent(msg) asyncio.run(record_preferences()) ``` -------------------------------- ### Install AgentScope and OpenJudge Dependencies Source: https://doc.agentscope.io/_downloads/111fb4ecba0dae3d1df2a707ee3f76d6/task_eval_openjudge.ipynb Command to install the necessary Python packages for integrating OpenJudge with AgentScope. ```bash pip install agentscope py-openjudge ``` -------------------------------- ### Build and Query Knowledge Base Source: https://doc.agentscope.io/tutorial/task_rag.html Demonstrates how to build a knowledge base using `SimpleKnowledge`, an embedding model (`DashScopeTextEmbedding`), and an embedding store (`QdrantStore`). It includes adding documents and retrieving relevant ones based on a query with score thresholding. Requires `DASHSCOPE_API_KEY` environment variable. ```python async def build_knowledge_base() -> SimpleKnowledge: """Build a knowledge base with sample documents.""" # Read documents using the text reader documents = await example_text_reader(print_docs=False) # Create an in-memory knowledge base instance knowledge = SimpleKnowledge( # Choose an embedding model to convert text to embedding vectors embedding_model=DashScopeTextEmbedding( api_key=os.environ["DASHSCOPE_API_KEY"], model_name="text-embedding-v4", dimensions=1024, ), # Choose Qdrant as the embedding store embedding_store=QdrantStore( location=":memory:", # Use in-memory storage for demonstration collection_name="test_collection", dimensions=1024, # The dimension of the embedding vectors ), ) # Insert documents into the knowledge base await knowledge.add_documents(documents) # Retrieve relevant documents based on a given query docs = await knowledge.retrieve( query="Who is John Doe's father?", limit=3, score_threshold=0.5, ) print("Retrieved Documents:") for doc in docs: print(doc, "\n") return knowledge knowledge = asyncio.run(build_knowledge_base()) ``` -------------------------------- ### Example DashScopeChatModel Call Source: https://doc.agentscope.io/tutorial/task_model.html An example of creating and calling `DashScopeChatModel` with messages and tools. The response can be converted to a `Msg` object. ```python async def example_model_call() -> None: """An example of using the DashScopeChatModel.""" model = DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_API_KEY"], stream=False, ) res = await model( messages=[ {"role": "user", "content": "Hi!"}, ], ) # You can directly create a ``Msg`` object with the response content msg_res = Msg("Friday", res.content, "assistant") print("The response:", res) print("The response as Msg:", msg_res) asyncio.run(example_model_call()) ``` -------------------------------- ### Install AgentScope via PyPI Source: https://doc.agentscope.io/_downloads/ff098ddfc7896640c06c203d7c96131a/quickstart_installation.ipynb Standard installation command for the AgentScope package using the Python package manager. ```bash pip install agentscope ``` -------------------------------- ### Agent State Initialization Source: https://doc.agentscope.io/_sources/tutorial/task_state.rst.txt Shows how to create a ReActAgent and inspect its initial state, including memory and toolkit configurations. ```Python # Creating an agent agent = ReActAgent( name="Friday", sys_prompt="You're a assistant named Friday.", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], ), formatter=DashScopeChatFormatter(), memory=InMemoryMemory(), toolkit=Toolkit(), ) initial_state = agent.state_dict() print("Initial state of the agent:") print(json.dumps(initial_state, indent=4)) ``` -------------------------------- ### Serialized Message Example Output Source: https://doc.agentscope.io/tutorial/quickstart_message.html An example of a serialized message, including multimodal content like images, audio, and video encoded in base64. ```json { "id": "E6TotD4eqLarzHYHUtJCtw", "name": "Jarvis", "role": "assistant", "content": [ { "type": "text", "text": "This is a multimodal message with base64 encoded data." }, { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "/9j/4AAQSkZ..." } }, { "type": "audio", "source": { "type": "base64", "media_type": "audio/mpeg", "data": "SUQzBAAAAA..." } }, { "type": "video", "source": { "type": "base64", "media_type": "video/mp4", "data": "AAAAIGZ0eX..." } } ], "metadata": {}, "timestamp": "2026-05-25 08:41:13.020" } ``` -------------------------------- ### Initialize ReActAgent with Agent Skills (Python) Source: https://doc.agentscope.io/_sources/tutorial/task_agent_skill.rst.txt This snippet shows how to create a ReActAgent instance and configure it with a system prompt, a language model, memory, a formatter, and a toolkit that includes agent skills. It highlights that the agent's system prompt is automatically augmented with skill information. ```Python from agentscope.agents import ReActAgent from agentscope.models import DashScopeChatModel from agentscope.memory import InMemoryMemory from agentscope.prompt import DashScopeChatFormatter import os # Assuming 'toolkit' is defined elsewhere and includes agent skills toolkit = ... # Placeholder for actual toolkit initialization agent = ReActAgent( name="Friday", sys_prompt="You are a helpful assistant named Friday.", model=DashScopeChatModel( model_name="qwen3-max", api_key=os.environ["DASHSCOPE_API_KEY"], ), memory=InMemoryMemory(), formatter=DashScopeChatFormatter(), toolkit=toolkit, ) print("Agent's System Prompt with Agent Skills:") print(agent.sys_prompt) ``` -------------------------------- ### Streaming Model Example Source: https://doc.agentscope.io/_sources/tutorial/task_model.rst.txt Shows how to use a chat model in streaming mode by setting `stream=True`. This example iterates over an async generator, printing each received chunk. ```Python async def example_streaming() -> None: """An example of using the streaming model.""" model = DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], stream=True, ) generator = await model( messages=[ { "role": "user", "content": "Count from 1 to 20, and just report the number without any other information.", }, ], ) print("The type of the response:", type(generator)) i = 0 async for chunk in generator: print(f"Chunk {i}") print(f"\ttype: {type(chunk.content)}") print(f"\t{chunk}\n") i += 1 asyncio.run(example_streaming()) ``` -------------------------------- ### Install AgentScope with Full Dependencies (Windows) Source: https://doc.agentscope.io/_sources/tutorial/quickstart_installation.rst.txt For Windows users, install AgentScope with all extra dependencies, including model APIs and tool functions, using this command. ```bash pip install agentscope[full] ``` -------------------------------- ### Initializing Realtime Models Source: https://doc.agentscope.io/_sources/tutorial/task_realtime.rst.txt Examples of how to initialize different realtime models supported by AgentScope, including DashScope, OpenAI, and Gemini. ```APIDOC ## Initializing Realtime Models ### Description AgentScope supports several realtime model providers. Below are examples of how to initialize models from DashScope, OpenAI, and Gemini, specifying model names, API keys, voice options, and audio transcription settings. ### Providers and Classes | Provider | Class | Supported Models | |-------------|-------------------------|---------------------------------------------------| | DashScope | `DashScopeRealtimeModel`| `qwen3-omni-flash-realtime` | | OpenAI | `OpenAIRealtimeModel` | `gpt-4o-realtime-preview` | | Gemini | `GeminiRealtimeModel` | `gemini-2.5-flash-native-audio-preview-09-2025` | ### Request Example ```python import os from agentscope.realtime import ( DashScopeRealtimeModel, OpenAIRealtimeModel, GeminiRealtimeModel, ) # DashScope realtime model dashscope_model = DashScopeRealtimeModel( model_name="qwen3-omni-flash-realtime", api_key=os.getenv("DASHSCOPE_API_KEY"), voice="Cherry", # Options: "Cherry", "Serena", "Ethan", "Chelsie" enable_input_audio_transcription=True, ) # OpenAI realtime model openai_model = OpenAIRealtimeModel( model_name="gpt-4o-realtime-preview", api_key=os.getenv("OPENAI_API_KEY"), voice="alloy", # Options: "alloy", "echo", "marin", "cedar" enable_input_audio_transcription=True, ) # Gemini realtime model gemini_model = GeminiRealtimeModel( model_name="gemini-2.5-flash-native-audio-preview-09-2025", api_key=os.getenv("GEMINI_API_KEY"), voice="Puck", # Options: "Puck", "Charon", "Kore", "Fenrir" enable_input_audio_transcription=True, ) ``` ``` -------------------------------- ### Install AgentScope with Extra Dependencies Source: https://doc.agentscope.io/_downloads/ff098ddfc7896640c06c203d7c96131a/quickstart_installation.ipynb Installs AgentScope with additional features such as model API support and tool functions. Syntax varies slightly by operating system. ```bash # Windows pip install agentscope[full] # Mac and Linux pip install agentscope\[full\] ``` -------------------------------- ### Running the Tuning Script with Ray Source: https://doc.agentscope.io/_sources/tutorial/task_tuner.rst.txt Instructions on how to run the tuning script using Ray. This involves starting the Ray cluster and then executing the Python script. ```Bash ray start --head python main.py ```