Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
Add RAG module into AgentScope (#800)
DavdGaod933f3ab432f
diff --git a/README.md b/README.mdindex d089cf60b..6c82851ac 100644--- a/README.md+++ b/README.md@@ -99,10 +99,13 @@ Quick overview of important features in **AgentScope 1.0**:| formatter | Support multi-agent prompt formatting with tools API | [Prompt Formatter](https://doc.agentscope.io/tutorial/task_prompt.html) || | Support truncation-based formatter strategy | || plan | Support ReAct-based long-term planning | [Plan](https://doc.agentscope.io/tutorial/task_plan.html) |-| | Support manual plan specification | |+| | Support manual plan specification | |+| RAG | Support agentic RAG | [RAG](https://doc.agentscope.io/tutorial/task_rag.html) |+| | Support multimodal RAG | || ... | | |## 📢 News+- **[2025-09]** **RAG** module in AgentScope 1.0 is online now! Check our [tutorial](https://doc.agentscope.io/tutorial/task_rag.html) and [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/rag) for more details.- **[2025-09]** **Voice agent** is online! `ReActAgent` supports Qwen-Omni and GPT-Audio natively now, check our [new example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/voice_agent) and [roadmap](https://github.com/agentscope-ai/agentscope/issues/773).- **[2025-09]** A new powerful 📋**Plan** module is online now! Check out the [tutorial](https://doc.agentscope.io/tutorial/task_plan.html) for more details.- **[2025-09]** **AgentScope Runtime** is open-sourced now! Enabling effective agent deployment with sandboxed tool execution for production-ready AI applications. Check out the [GitHub repo](https://github.com/agentscope-ai/agentscope-runtime).@@ -361,6 +364,7 @@ as_studio- [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/mcp)- [Plan](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/plan)- [Structured Output](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)+ - [RAG](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/rag)- [Long-Term Memory](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory)- [Session with SQLite](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/session_with_sqlite)- [Voice Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/voice_agent)diff --git a/README_zh.md b/README_zh.mdindex 769d9b032..0c921d91c 100644--- a/README_zh.md+++ b/README_zh.md@@ -99,17 +99,20 @@ AgentScope v1.0 新功能概览:| evaluation | 提供分布式和并行评估 | [Evaluation](https://doc.agentscope.io/zh_CN/tutorial/task_eval.html) || formatter | 支持多Agent提示格式化与工具API | [Prompt Formatter](https://doc.agentscope.io/zh_CN/tutorial/task_prompt.html) || | 支持基于截断的格式化策略 | |-| plan | 支持任务分解和计划制定 | [Plan](https://doc.agentscope.io/zh_CN/tutorial/task_plan.html) |-| | 支持开发者手动设定计划 | |+| plan | 支持任务分解和计划制定 | [Plan](https://doc.agentscope.io/zh_CN/tutorial/task_plan.html) |+| | 支持开发者手动设定计划 | |+| RAG | 支持 agentic RAG | [RAG](https://doc.agentscope.io/tutorial/task_rag.html) |+| | 支持多模态 RAG | || ... | | |## 📢 新闻+- **[2025-09]** AgentScope 1.0 **RAG** 模块已上线!欢迎查看 [文档](https://doc.agentscope.io/zh_CN/tutorial/task_rag.html) 和 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/rag)。- **[2025-09]** **Voice agent** 已上线!`ReActAgent` 已原生支持 Qwen-Omni 和 GPT-Audio 系列模型,欢迎查看 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/voice_agent) 和 [roadmap](https://github.com/agentscope-ai/agentscope/issues/773)。- **[2025-09]** 一个全新功能强大的 📋**Plan** 模块已经上线 AgentScope!查看[文档](https://doc.agentscope.io/zh_CN/tutorial/task_plan.html)了解更多详情。- **[2025-09]** **AgentScope Runtime** 现已开源!支持沙盒化工具执行的高效智能体部署,助力打造生产级AI应用。查看 [GitHub 仓库](https://github.com/agentscope-ai/agentscope-runtime)。- **[2025-09]** **AgentScope Studio** 现已开源!查看 [GitHub 仓库](https://github.com/agentscope-ai/agentscope-studio)。-- **[2025-08]** v1 版本 Tutorial 已上线!查看[tutorial](https://doc.agentscope.io/zh_CN/)了解更多详情。-- **[2025-08]** 🎉🎉 AgentScope v1现已发布!在完全拥抱异步执行的基础上提供许多新功能和改进。查看[changelog](https://github.com/agentscope-ai/agentscope/blob/main/docs/changelog.md)了解详细变更。+- **[2025-08]** v1 版本 Tutorial 已上线!查看 [tutorial](https://doc.agentscope.io/zh_CN/) 了解更多详情。+- **[2025-08]** 🎉🎉 AgentScope v1现已发布!在完全拥抱异步执行的基础上提供许多新功能和改进。查看 [changelog](https://github.com/agentscope-ai/agentscope/blob/main/docs/changelog.md) 了解详细变更。## 💬 联系我们@@ -363,6 +366,7 @@ as_studio- [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/mcp)- [计划](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/plan)- [结构化输出](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)+ - [RAG](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/rag)- [长期记忆](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory)- [基于DB的会话管理](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/session_with_sqlite)- [语音智能体](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/voice_agent)diff --git a/docs/tutorial/en/index.rst b/docs/tutorial/en/index.rstindex 73b0fdf79..7fa644723 100644--- a/docs/tutorial/en/index.rst+++ b/docs/tutorial/en/index.rst@@ -43,6 +43,7 @@ Welcome to AgentScope's documentation!tutorial/task_agenttutorial/task_pipelinetutorial/task_plan+ tutorial/task_ragtutorial/task_statetutorial/task_hooktutorial/task_mcpdiff --git a/docs/tutorial/en/src/task_embedding.py b/docs/tutorial/en/src/task_embedding.pyindex 258e6d0d5..fce9363d1 100644--- a/docs/tutorial/en/src/task_embedding.py+++ b/docs/tutorial/en/src/task_embedding.py@@ -22,11 +22,12 @@ AgentScope has built-in embedding classes for the following API providers:* - Gemini- ``GeminiTextEmbedding``* - DashScope- - ``DashScopeTextEmbedding``+ - ``DashScopeTextEmbedding``, ``DashScopeMultiModalEmbedding``* - Ollama- ``OllamaTextEmbedding``All classes inherit from ``EmbeddingModelBase``, implementing the ``__call__`` method and generating ``EmbeddingResponse`` object with the embeddings and usage information.+The ``DashScopeMultiModalEmbedding`` supports multi-modal embeddings for text, images, and videos.Taking the DashScope embedding class as an example, you can use it as follows:"""diff --git a/docs/tutorial/en/src/task_rag.py b/docs/tutorial/en/src/task_rag.pynew file mode 100644index 000000000..9d32ecc39--- /dev/null+++ b/docs/tutorial/en/src/task_rag.py@@ -0,0 +1,418 @@+# -*- coding: utf-8 -*-+"""+.. _rag:++RAG+===========================++AgentScope provides built-in support for Retrieval-Augmented Generation (RAG)+tasks. This tutorial demonstrates++- how to use the RAG module in AgentScope,+- how to use **multimodal** RAG,+- how to integrate the RAG module with the ``ReActAgent`` in+ - **agentic manner** and+ - **generic manner**:++.. list-table:: RAG module integration methods+ :header-rows: 1++ * - Integration Manner+ - Description+ - Advantages+ - Disadvantages+ * - Agentic Manner+ - The RAG module is integrated with the agent as a tool, and the agent can decide when to retrieve knowledge and the queries to be retrieved.+ - - The query rewriting and knowledge retrieval are integrated into the ReAct process, which is more flexible,+ - the agent can rewrite the query based on all the available information,+ - only retrieve knowledge when necessary.+ - High requirements for the LLM's reasoning and tool-use capabilities.+ * - Generic Manner+ - Retrieve knowledge at the beginning of each reply, and attach the retrieved knowledge to the prompt in a user message.+ - - Simple, easy to implement,+ - does not require high reasoning and tool-use capabilities from the LLM.+ - - Still retrieve knowledge even when not necessary, and+ - if the retrieval is imperceptible to the user, the waiting time may be longer.++.. note:: As an open-source project, AgentScope doesn't insist that developers+ use the built-in RAG module. Our target is make the development easier and+ more enjoyable, so integrating other RAG implementations, frameworks, or+ services are welcome and encouraged!++"""+import asyncio+import json+import os++from matplotlib import pyplot as plt++import agentscope+from agentscope.agent import ReActAgent+from agentscope.embedding import (+ DashScopeTextEmbedding,+ DashScopeMultiModalEmbedding,+)+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.rag import (+ TextReader,+ SimpleKnowledge,+ QdrantStore,+ Document,+ ImageReader,+)+from agentscope.tool import Toolkit++# %%+# Using RAG Module+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# The RAG module in AgentScope is composed of two core components:+#+# - **Reader**: responsible for reading and chunking the input documents.+# - **Knowledge**: responsible for algorithm implementation of knowledge retrieval and updating.+#+# .. note:: We're integrating more vector databases and readers into AgentScope. Contributions are welcome!+#+# The currently built-in readers include:+#++for _ in agentscope.rag.__all__:+ if _.endswith("Reader"):+ print(f"- {_}")++# %%+# they are responsible for reading data and chunking them into ``Document`` objects.+# The ``Document`` class has the following fields:+#+# - ``metadata``: the metadata of the document, including the content, doc_id, chunk_id, and total_chunks.+# - ``embedding``: the embedding vector of the document, which will be filled when the document is added to or retrieved from the knowledge base.+# - ``score``: the relevance score of the document, which will be filled when the document is retrieved from the knowledge base.+#+# Taking the ``TextReader`` as an example, it can read and chunk documents from text strings.+#+++async def example_text_reader(print_docs: bool) -> list[Document]:+ """The example of using TextReader."""+ # Create a text reader with chunk size of 512 characters, split by characters+ reader = TextReader(chunk_size=512, split_by="paragraph")++ # Read documents from a text string+ documents = await reader(+ text=(+ # Fake personal profile for demonstration+ "I'm John Doe, 28 years old.\n"+ "I live in San Francisco. I work at OpenAI as a "+ "software engineer. I love hiking and photography.\n"+ "My father is Michael Doe, a doctor. I'm very proud of him. "+ "My mother is Sarah Doe, a teacher. She is very kind and "+ "always helps me with my studies.\n"+ "I'm now a PhD student at Stanford University, majoring in "+ "Computer Science. My advisor is Prof. Jane Williams, who is "+ "a leading expert in artificial intelligence. I have published "+ "several papers in top conferences, such as NeurIPS and ICML.\n"+ "My best friend is James Smith.\n"+ ),+ )++ if print_docs:+ print("The length of the documents:", len(documents))+ for idx, doc in enumerate(documents):+ print("Document #", idx)+ print("\tScore: ", doc.score)+ print("\tMetadata: ", json.dumps(doc.metadata, indent=2), "\n")++ return documents+++docs = asyncio.run(example_text_reader(print_docs=True))++# %%+# Note there doesn't exist a universally best chunk size and splitting method, especially for PDF files, we highly+# encourage developers to implement or contribute their own readers according to their specific scenarios.+# To create a custom reader, you only need to inherit the ``ReaderBase`` class and implement the ``__call__`` method.+#+# After chunking the documents, we can create a knowledge base to store the documents and perform retrieval.+# Such a knowledge base is initialized by providing **an embedding model** and **an embedding store** (also known as a vector database).+# Agentscope provides built-in support for `Qdrant <https://qdrant.tech/>`_ as the embedding store and a simple knowledge base implementation ``SimpleKnowledge``.+# They can be used as follows:+#+# .. note::+#+# - We're integrating more vector databases into AgentScope. Contributions are welcome!+# - The Qdrant store supports various storage backends by the ``location`` parameter, including in-memory, local file, and remote server. Refer to the `Qdrant documentation <https://qdrant.tech/>`_ for more details.+#+++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())++# %%+# The knowledge base class provides two main methods: ``add_documents`` and+# ``retrieve``, which are used to add documents to the knowledge base and+# retrieve relevant documents based on a given query, respectively.+#+# In addition, the knowledge base class also provides a convenient method+# ``retrieve_knowledge``, which wraps the ``retrieve`` method into a tool+# function that can be directly registered in the toolkit of an agent.+#+#+# Customizing RAG Components+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# AgentScope supports and encourages developers to customize their own RAG components, including readers, knowledge bases and embedding stores.+# Specifically, we provide the following base classes for customization:+#+# .. list-table:: RAG Base Classes+# :header-rows: 1+#+# * - Base Class+# - Description+# - Abstract Methods+# * - ``ReaderBase``+# - The base class for all readers.+# - ``__call__``+# * - ``VDBStoreBase``+# - The base class for embedding stores (vector databases).+# - | ``add``+# | ``search``+# | ``get_client`` (optional)+# | ``delete`` (optional)+# * - ``KnowledgeBase``+# - The base class for knowledge bases.+# - | ``retrieve``+# | ``add_documents``+#+#+# The `get_client` method in the ``VDBStoreBase`` allows developers to access the full functionality of the underlying vector database.+# So that they can implement more advanced features based on the vector database, e.g. index management, advanced search, etc.+#+# Integrating with ReActAgent+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# Next we demonstrate how to integrate the RAG module with the ``ReActAgent``+# class in AgentScope in agentic and generic manners.+#+# Agentic Manner+# --------------------------------+# In agentic manner, the ReAct agent is empowered with the ability to decide when to retrieve knowledge and the queries to be retrieved.+# It's very easy to integrate the RAG module with the ``ReActAgent`` class in AgentScope, just by registering the ``retrieve_knowledge`` method of the knowledge base as a tool,+# and providing a proper description for the tool.+++async def example_agentic_manner() -> None:+ """The example of integrating RAG module with ReActAgent in agentic manner."""+ # Create a ReAct agent+ toolkit = Toolkit()++ # Create the ReAct agent with DashScope as the model+ agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant named Friday.",+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen-max",+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ )++ print("The first response: ")+ # Ask some questions about Tony Stank+ await agent(+ Msg(+ "user",+ "John Doe is my best friend.",+ "user",+ ),+ )++ # Register the retrieve_knowledge method as a tool function in the toolkit+ toolkit.register_tool_function(+ knowledge.retrieve_knowledge,+ func_description=( # Provide a clear description for the tool+ "The tool used to retrieve documents relevant to the given query. "+ "Use this tool when you need to find some information about John Doe."+ ),+ )++ print("\n\nThe second response: ")+ # We hope the agent can rewrite the query to be more specific, e.g.+ # "Who is Tony Stank's father?" or "Tony Stank's father"+ await agent(+ Msg(+ "user",+ "Do you know who his father is?",+ "user",+ ),+ )+++asyncio.run(example_agentic_manner())++# %%+# In the above example, our question is "Do you know who his father is?".+# We hope the agent can rewrite the query with the historical information, and+# rewrite it to be more specific, e.g. "Who is John Doe's father?" or "John Doe's father".+#+#+# Generic Manner+# --------------------------------+# The ``ReActAgent`` also integrates the RAG module in a generic manner, which+# retrieves knowledge at the beginning of each reply, and attaches the+# retrieved knowledge to the prompt in a user message.+#+# Just set the ``knowledge`` parameter of the ``ReActAgent``, and the agent+# will automatically retrieve knowledge at the beginning of each reply.+#+++async def example_generic_manner() -> None:+ """The example of integrating RAG module with ReActAgent in generic manner."""+ # Create a ReAct agent+ agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant named Friday.",+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen-max",+ ),+ formatter=DashScopeChatFormatter(),+ #+ knowledge=knowledge,+ )++ await agent(+ Msg(+ "user",+ "Do you know who John Doe's father is?",+ "user",+ ),+ )+++asyncio.run(example_generic_manner())+++# %%+# Multimodal RAG+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# The RAG module in AgentScope supports multimodal RAG natively, as+#+# - AgentScope supports multimodal embedding API, e.g. ``DashScopeMultimodalEmbedding``.+# - The ``Document`` class supports text, image, and other modalities in its ``metadata`` field.+#+# Thus, we can directly use the multimodal reader and embedding model to build+# a multimodal knowledge base as follows.+#+# First we prepare an image with some text about my name.++# Prepare an image with the text "John Doe's father is Michael Doe."+path_image = "./example.jpg"+plt.figure(figsize=(8, 3))+plt.text(+ 0.5,+ 0.5,+ "My name is Tony Stank",+ ha="center",+ va="center",+ fontsize=30,+)+plt.axis("off")+plt.savefig(path_image, bbox_inches="tight", pad_inches=0.1)+plt.close()++# %%+# Then we can build a multimodal knowledge base with the image document.+# The example is the same as before, just using the ``ImageReader`` and+# ``DashScopeMultiModalEmbedding`` instead of the text counterparts.+#+++async def example_multimodal_rag() -> None:+ """The example of using multimodal RAG."""+ # Read the image using the ImageReader+ reader = ImageReader()+ docs = await reader(image_url=path_image)++ # Create a knowledge base with the new image document+ knowledge = SimpleKnowledge(+ embedding_model=DashScopeMultiModalEmbedding(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="multimodal-embedding-v1",+ dimensions=1024,+ ),+ embedding_store=QdrantStore(+ location=":memory:",+ collection_name="test_collection",+ dimensions=1024,+ ),+ )++ await knowledge.add_documents(docs)++ agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant named Friday.",+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen-vl-max",+ ),+ formatter=DashScopeChatFormatter(),+ knowledge=knowledge,+ )++ await agent(+ Msg(+ "user",+ "What's my name?",+ "user",+ ),+ )++ # Let's see the last message from the agent+ print("\nThe image is attached in the agent's memory:")+ print((await agent.memory.get_memory())[-4])+++asyncio.run(example_multimodal_rag())++# %%+# We can see that the agent can answer the question based on the retrieved+# image.diff --git a/docs/tutorial/zh_CN/index.rst b/docs/tutorial/zh_CN/index.rstindex 73b0fdf79..7fa644723 100644--- a/docs/tutorial/zh_CN/index.rst+++ b/docs/tutorial/zh_CN/index.rst@@ -43,6 +43,7 @@ Welcome to AgentScope's documentation!tutorial/task_agenttutorial/task_pipelinetutorial/task_plan+ tutorial/task_ragtutorial/task_statetutorial/task_hooktutorial/task_mcpdiff --git a/docs/tutorial/zh_CN/src/task_embedding.py b/docs/tutorial/zh_CN/src/task_embedding.pyindex d98bb114c..a6a791f13 100644--- a/docs/tutorial/zh_CN/src/task_embedding.py+++ b/docs/tutorial/zh_CN/src/task_embedding.py@@ -22,13 +22,14 @@ AgentScope 内置支持以下 API:* - Gemini- ``GeminiTextEmbedding``* - DashScope- - ``DashScopeTextEmbedding``+ - ``DashScopeTextEmbedding``, ``DashScopeMultiModalEmbedding``* - Ollama- ``OllamaTextEmbedding``所有类都继承自 ``EmbeddingModelBase``,实现了 ``__call__`` 方法并生成包含嵌入和使用信息的 ``EmbeddingResponse`` 对象。+其中 ``DashScopeMultiModalEmbedding`` 支持文本,图像和视频的多模态嵌入。-以 DashScope 嵌入类为例,您可以按如下方式使用:+以 DashScope 嵌入类为例,可以按如下方式使用:"""import asynciodiff --git a/docs/tutorial/zh_CN/src/task_rag.py b/docs/tutorial/zh_CN/src/task_rag.pynew file mode 100644index 000000000..6ab667b40--- /dev/null+++ b/docs/tutorial/zh_CN/src/task_rag.py@@ -0,0 +1,404 @@+# -*- coding: utf-8 -*-+"""+.. _rag:++RAG+==========================++AgentScope 提供了内置的 RAG(Retrieval-Augmented Generation) 实现。本节将详细介绍++- 如何使用 AgentScope 中的 RAG 模块,+- 如何实现 **多模态** RAG,+- 如何在 ``ReActAgent`` 中以两种不同的方式集成 RAG 模块:+ - 智能体自主控制(Agentic manner)+ - 通用方式(Generic manner)++我们在下列表格中总结了两种模式的优缺点:++.. list-table:: RAG 集成方式比较+ :header-rows: 1++ * - 集成方式+ - 描述+ - 优点+ - 缺点+ * - 智能体自主控制+ - 以工具调用方式让智能体自主决定何时进行查询,查询什么关键字+ - - 与 ReAct 算法契合,灵活性高+ - 智能体能够根据当前的上下文改写查询关键词+ - 避免在不必要时发生查询+ - 对 LLM 模型能力要求较高+ * - 通用方式+ - 每次在 ``reply`` 函数开始时固定进行查询,并将检索结果整合到提示(prompt)中+ - - 实现简单+ - 对 LLM 模型能力要求低+ - - 每次都会运行查询,因此会引入过多不必要的查询检索+ - 查询数据库较大时,回复延迟较高++.. note:: 作为开源框架,AgentScope 的目标是让开发过程更简单也更有趣。因此,AgentScope 的设计中并不强制要求使用内置的 RAG 实现,同时支持、鼓励开发者集成现有的 RAG 实现或第三方 RAG 框架。++"""+import asyncio+import json+import os++from matplotlib import pyplot as plt++import agentscope+from agentscope.agent import ReActAgent+from agentscope.embedding import (+ DashScopeTextEmbedding,+ DashScopeMultiModalEmbedding,+)+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.rag import (+ TextReader,+ SimpleKnowledge,+ QdrantStore,+ Document,+ ImageReader,+)+from agentscope.tool import Toolkit++# %%+# 使用 RAG 模块+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# AgentScope 中的 RAG 模块由以下三个核心组件构成:+#+# - **Reader**:负责从数据源读取数据,并进行分块(chunking)+# - **Knowledge**:负责知识库查询检索和数据存储逻辑的算法实现+# - **Store**:负责与向量数据库交互的逻辑实现+#+# .. note:: 我们将持续在 AgentScope 中集成新的向量数据库和数据读取模块。详情请查看我们的 `开发路线图 <https://github.com/orgs/agentscope-ai/projects/2>`_,同时也欢迎贡献代码!+#+# 当前 AgentScope 中内置支持的 reader 包括:+#++for _ in agentscope.rag.__all__:+ if _.endswith("Reader"):+ print(f"- {_}")++# %%+# 这些 reader 的作用是读取数据,将数据分块并包装成 ``agentscope.rag.Document`` 对象。 ``Document`` 对象包含以下字段:+#+# - ``metadata``:数据块的元信息,包含数据内容(``content``)、数据 ID(``doc_id``)、块 ID(``chunk_id``)和总块数(``total_chunks``)+# - ``embedding``: 数据块的向量表示,默认为 ``None``,在将数据块添加到知识库时会被填充+# - ``score``: 数据块的相关性分数,默认为 ``None``,在从知识库检索数据块时会被填充+#+# 以 ``TextReader`` 为例,通过如下代码读取文本字符串,并将文本分块为 ``Document`` 对象:+#+++async def example_text_reader(print_docs: bool) -> list[Document]:+ """使用 TextReader 读取文本字符串,并将文本分块为 Document 对象。"""+ # 创建 TextReader 对象+ reader = TextReader(chunk_size=512, split_by="paragraph")++ # 读取文本字符串+ documents = await reader(+ text=(+ # 我们准备一些文本数据用于演示 RAG 功能。+ "我的名字是李明,今年28岁。\n"+ "我居住在中国杭州,是一名算法工程师。我喜欢打篮球和玩游戏。\n"+ "我父亲的名字是李强,是一名医生,我的母亲是陈芳芳,是一名教师,她总是指导我学习。\n"+ "我现在在北京大学攻读博士学位,研究方向是人工智能。\n"+ "我最好的朋友是王伟,我们从小一起长大,现在他是一名律师。"+ ),+ )++ if print_docs:+ print(f"文本被分块为 {len(documents)} 个 Document 对象:")+ for idx, doc in enumerate(documents):+ print(f"Document {idx}:")+ print("\tScore: ", doc.score)+ print(+ "\tMetadata: ",+ json.dumps(doc.metadata, indent=2, ensure_ascii=False),+ "\n",+ )++ return documents+++docs = asyncio.run(example_text_reader(print_docs=True))++# %%+# 由于并不存在一个 “one-for-all” 的数据读取和分块方法,特别像是 PDF 和 Word 这类复杂格式的文档。+# 因此,AgentScope 鼓励开发者根据自己的数据格式实现自定义的 reader。+# 只需要继承 ``BaseReader`` 类,并实现 ``__call__`` 方法即可。+#+# 在数据分块后,接下来需要将数据块添加到知识库中。+# 在 AgentScope 中,知识库的初始化需要提供 **嵌入模型** 和 **向量存储** (即向量数据库) 的对象。+# AgentScope 目前内置支持基于 `Qdrant <https://qdrant.tech/>`_ 实现的向量存储,以及一个知识库的基础实现 ``SimpleKnowledge``。+# 具体使用方式如下:+#+# .. note::+#+# - 我们正在 AgentScope 中集成新的向量数据库,详情请查看我们的 `开发路线图 <https://github.com/orgs/agentscope-ai/projects/2>`_。欢迎贡献代码!+# - Qdrant 的实现通过 ``location`` 参数支持多种不同的部署方式,包括内存模式,本地模式和云端模式。详情请参考 `Qdrant 文档 <https://qdrant.tech/>`_。+#+++async def build_knowledge_base() -> SimpleKnowledge:+ """构建知识库。"""+ # 读取 documents 数据+ documents = await example_text_reader(print_docs=False)++ # 创建一个内存中的 Qdrant 向量存储,以及使用 DashScopeTextEmbedding 作为嵌入模型,初始化知识库+ knowledge = SimpleKnowledge(+ # 提供一个 embedding 模型用于将文本转换为向量+ embedding_model=DashScopeTextEmbedding(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="text-embedding-v4",+ dimensions=1024,+ ),+ # 选择 Qdrant 作为向量存储+ embedding_store=QdrantStore(+ location=":memory:", # 使用内存模式+ collection_name="test_collection",+ dimensions=1024, # 嵌入向量的维度必须与嵌入模型输出的维度一致+ ),+ )++ # 将 documents 添加到知识库中+ await knowledge.add_documents(documents)++ # 从知识库中检索数据+ docs = await knowledge.retrieve(+ query="李明的父亲是谁?",+ limit=3,+ score_threshold=0.5,+ )++ print("检索到的 Document 对象:")+ for doc in docs:+ print(doc, "\n")++ return knowledge+++knowledge = asyncio.run(build_knowledge_base())++# %%+# AgentScope 中的知识库类提供两个核心方法:``add_documents`` 和 ``retrieve``,分别用于添加数据块和搜索检索数据块。+#+# 此外,AgentScope 提供了 ``retrieve_knowledge`` 方法,它将 ``retrieve`` 方法封装成一个智能体能够直接调用的工具函数。开发者可以直接使用该工具函数装备智能体。+#+# 自定义 RAG 组件+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# AgentScope 支持并鼓励开发者自定义 RAG 组件,包括 reader、知识库和向量数据库。+# 具体来说,我们提供了以下基类用于自定义:+#+# .. list-table:: RAG 基类+# :header-rows: 1+#+# * - 基类+# - 描述+# - 抽象方法+# * - ``ReaderBase``+# - 所有 reader 的基类+# - ``__call__``+# * - ``VDBStoreBase``+# - 向量数据库的基类+# - | ``add``+# | ``search``+# | ``get_client`` (可选)+# | ``delete`` (可选)+# * - ``KnowledgeBase``+# - 知识库的基类+# - | ``retrieve``+# | ``add_documents``+#+# ``VDBStoreBase`` 中的 ``get_client`` 方法允许开发者访问底层向量数据库的完整功能。+# 这样,他们就可以基于向量数据库实现更高级的功能,例如建立索引、高级搜索等。+#+# 与 ReActAgent 集成+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# 接下来,我们将演示如何以智能体自主控制(agentic)和通用(generic)两种方式将 RAG 模块与 AgentScope 中的 ``ReActAgent`` 集成。+#+# 智能体自主控制+# --------------------------------+# 在智能体自主控制的方式中,ReAct 智能体可以自主决定何时检索知识以及检索的查询内容。+# 将 RAG 模块与 AgentScope 中的 ``ReActAgent`` 集成非常简单,只需将知识库的 ``retrieve_knowledge`` 方法注册为工具,并为该工具提供适当的描述即可。+++async def example_agentic_manner() -> None:+ """以智能体自主控制方式将 RAG 模块与 ReActAgent 集成的示例。"""+ # 创建一个 ReAct 智能体+ toolkit = Toolkit()++ # 使用 DashScope 作为模型创建 ReAct 智能体+ agent = ReActAgent(+ name="Friday",+ sys_prompt="You're a helpful assistant named Friday.",+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen-max",+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ )++ print("第一次回复: ")+ # 第一次我们进行一些交流,提供“李明”这个名字作为上下文内容+ await agent(+ Msg(+ "user",+ "李明是我最好的朋友。",+ "user",+ ),+ )++ # 将 retrieve_knowledge 方法注册为工具箱中的工具函数+ toolkit.register_tool_function(+ knowledge.retrieve_knowledge,+ func_description=( # 为工具提供清晰的描述+ "用于检索与给定查询相关的文档的工具。" "当你需要查找有关李明的信息时使用此工具。"+ ),+ )++ print("\n\n第二次回复: ")+ # 第二次回复中,我们希望智能体能够将查询中“他父亲”改写得更具体,例如+ # “李明的父亲是谁?”或“李明的父亲”+ await agent(+ Msg(+ "user",+ "你知道他父亲是谁吗?",+ "user",+ ),+ )+++asyncio.run(example_agentic_manner())++# %%+# 在上面的例子中,我们模拟了正常与智能体交流过程。第一次的交流我们提供了“李明”的名字作为上下文内容。+# 第二次提问时,我们的问题是“你知道他父亲是谁吗?”,+# 我们希望智能体能够利用上下文历史信息改写查询,使其更具体,更好的进行检索,例如改写为“李明的父亲是谁?”或“李明的父亲”。+#+# 更进一步,结合 :ref:`plan` 模块,我们可以让智能体实现更加复杂的查询改写和多轮检索。+#+# 通用方式+# --------------------------------+# ``ReActAgent`` 还以一种更加通用的方式集成了 RAG 模块,+# 它在每次 ``reply`` 函数开始执行时检索知识,并将检索到的知识附加到用户消息的提示中。+#+# 只需设置 ``ReActAgent`` 的 ``knowledge`` 参数,智能体就会在每次回复开始时自动检索知识。+#+++async def example_generic_manner() -> None:+ """以通用方式将 RAG 模块与 ReActAgent 集成的示例。"""+ # 创建一个 ReAct 智能体+ agent = ReActAgent(+ name="Friday",+ sys_prompt="You're a helpful assistant named Friday.",+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen-max",+ ),+ formatter=DashScopeChatFormatter(),+ # 将知识库传递给智能体+ knowledge=knowledge,+ )++ await agent(+ Msg(+ "user",+ "你知道李明的父亲是谁吗?",+ "user",+ ),+ )++ print("\n查看智能体记忆中检索信息如何插入:")+ content = (await agent.memory.get_memory())[-4].content+ print(json.dumps(content, indent=2, ensure_ascii=False))+++asyncio.run(example_generic_manner())+++# %%+# 多模态 RAG+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# AgentScope 中的 RAG 模块原生支持多模态,因为+#+# - AgentScope 支持多模态嵌入 API,例如 ``DashScopeMultimodalEmbedding``。+# - ``Document`` 类的 ``metadata`` 中,``content`` 字段的类型是 ``TextBlock | ImageBlock | VideoBlock``,因此可以存储文本、图片和视频等多模态数据。+#+# 因此,我们可以直接使用多模态 reader 和嵌入模型来构建多模态知识库,如下所示。+#+# 首先,我们准备一张本地的图片,这张图片上包含了文本“My name is Ming Li”。++# 准备一张包含文本“My name is Ming Li”的图片。+path_image = "./example.png"+plt.figure(figsize=(8, 3))+plt.text(0.5, 0.5, "My name is Ming Li", ha="center", va="center", fontsize=30)+plt.axis("off")+plt.savefig(path_image, bbox_inches="tight", pad_inches=0.1)+plt.close()++# %%+# 然后我们可以构建一个多模态知识库,构建过程与纯文本知识库类似。只是将 reader 和嵌入模型替换为多模态版本即可。+# 在下面的例子中,我们使用了 ``ImageReader`` 和 ``DashScopeMultiModalEmbedding``。+# 同时,这里我们使用多模态模型 ``qwen3-vl-plus`` 作为智能体的语言模型。+#+++async def example_multimodal_rag() -> None:+ """使用多模态 RAG 的示例。"""+ # 使用 ImageReader 读取图片+ reader = ImageReader()+ docs = await reader(image_url=path_image)++ # 创建一个知识库+ knowledge = SimpleKnowledge(+ embedding_model=DashScopeMultiModalEmbedding(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="multimodal-embedding-v1",+ dimensions=1024,+ ),+ embedding_store=QdrantStore(+ location=":memory:",+ collection_name="test_collection",+ dimensions=1024,+ ),+ )++ await knowledge.add_documents(docs)++ agent = ReActAgent(+ name="Friday",+ sys_prompt="You're a helpful assistant named Friday.",+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen3-vl-plus",+ ),+ formatter=DashScopeChatFormatter(),+ knowledge=knowledge,+ )++ await agent(+ Msg(+ "user",+ "你知道我的名字吗?",+ "user",+ ),+ )++ # 让我们看看检索到的图片数据是否已经加入了智能体的记忆中+ print("\n查看智能体记忆中检索信息如何插入:")+ content = (await agent.memory.get_memory())[-4].content+ print(json.dumps(content, indent=2, ensure_ascii=False))+++asyncio.run(example_multimodal_rag())++# %%+# 进一步阅读+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# - :ref:`embedding`+# - :ref:`plan`+#diff --git a/examples/functionality/rag/README.md b/examples/functionality/rag/README.mdnew file mode 100644index 000000000..3638ee3e9--- /dev/null+++ b/examples/functionality/rag/README.md@@ -0,0 +1,40 @@+# RAG in AgentScope++This example includes three scripts to demonstrate how to use Retrieval-Augmented Generation (RAG) in AgentScope:++- the basic usage of RAG module in AgentScope in ``basic_usage.py``,+- a simple agentic use case of RAG in ``agentic_usage.py``, and+- integrate RAG into ``ReActAgent`` class by retrieving input message(s) at the beginning of each reply in ``react_agent_integration.py``.+- build multimodal RAG in ``multimodal_rag.py``.++> The agentic usage and static integration has their own advantages and limitations.+> - The agentic usage requires more powerful LLMs to manage the retrieval process, but it's more flexible and the agent can adjust the retrieval strategy dynamically+> - The static integration is more straightforward and easier to implement, but it's less flexible and the input message maybe not specific enough, leading to less relevant retrieval results.++> Note: The example is built with DashScope chat model. If you want to change the model in this example, don't forget+> to change the formatter at the same time! The corresponding relationship between built-in models and formatters are+> list in [our tutorial](https://doc.agentscope.io/tutorial/task_prompt.html#id1)++## Quick Start++Install the latest agentscope library from PyPI or source, then run the following command to run the example:++- the basic usage:+```bash+python basic_usage.py+```++- the agentic usage:+```bash+python agentic_usage.py+```++- the static integration:+```bash+python react_agent_integration.py+```++- the multimodal RAG:+```bash+python multimodal_rag.py+```diff --git a/examples/functionality/rag/agentic_usage.py b/examples/functionality/rag/agentic_usage.pynew file mode 100644index 000000000..c23f564a9--- /dev/null+++ b/examples/functionality/rag/agentic_usage.py@@ -0,0 +1,101 @@+# -*- coding: utf-8 -*-+"""The agentic usage example for RAG in AgentScope, where the agent is+equipped with RAG tools to answer questions based on a knowledge base.++The example is more challenging for the agent, requiring the agent to+adjust the retrieval parameters to get relevant results.+"""+import asyncio+import os++from agentscope.agent import ReActAgent, UserAgent+from agentscope.embedding import DashScopeTextEmbedding+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.rag import SimpleKnowledge, QdrantStore, TextReader+from agentscope.tool import Toolkit++# Create a knowledge base instance+knowledge = SimpleKnowledge(+ embedding_store=QdrantStore(+ location=":memory:",+ collection_name="test_collection",+ dimensions=1024, # The dimension of the embedding vectors+ ),+ embedding_model=DashScopeTextEmbedding(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="text-embedding-v4",+ ),+)+++async def main() -> None:+ """The main entry of the agent usage example for RAG in AgentScope."""++ # Store some things into the knowledge base for demonstration+ # In practice, the VDB store would be pre-filled with relevant data+ reader = TextReader(chunk_size=1024, split_by="sentence")+ documents = await reader(+ text=(+ # Fake personal profile for demonstration+ "I'm John Doe, 28 years old. My best friend is James "+ "Smith. I live in San Francisco. I work at OpenAI as a "+ "software engineer. I love hiking and photography. "+ "My father is Michael Doe, a doctor. I'm very proud of him. "+ "My mother is Sarah Doe, a teacher. She is very kind and "+ "always helps me with my studies.\n"+ "I'm now a PhD student at Stanford University, majoring in "+ "Computer Science. My advisor is Prof. Jane Williams, who is "+ "a leading expert in artificial intelligence. I have published "+ "several papers in top conferences, such as NeurIPS and ICML. "+ ),+ )+ await knowledge.add_documents(documents)++ # Create a toolkit and register the RAG tool function+ toolkit = Toolkit()+ toolkit.register_tool_function(+ knowledge.retrieve_knowledge,+ func_description=( # Provide a clear description for the tool+ "Retrieve relevant documents from the knowledge base, which is "+ "relevant to John Doe's profile. Note the `query` parameter is "+ "very important for the retrieval quality, and you can try many "+ "different queries to get the best results. Adjust the `limit` "+ "and `score_threshold` parameters to get more or fewer results."+ ),+ )++ # Create an agent and a user+ agent = ReActAgent(+ name="Friday",+ sys_prompt=(+ "You're a helpful assistant named Friday. "+ "You're equipped with a 'retrieve_knowledge' tool to help you "+ "know about the user named John Doe. "+ "NOTE to adjust the `score_threshold` parameters when you cannot "+ "get relevant results. "+ ),+ toolkit=toolkit,+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen3-max-preview",+ ),+ formatter=DashScopeChatFormatter(),+ )+ user = UserAgent(name="User")++ # A simple conversation loop beginning with a preset question+ msg = Msg(+ "user",+ "I'm John Doe. Do you know my father?",+ "user",+ )+ while True:+ msg = await agent(msg)+ msg = await user(msg)+ if msg.get_text_content() == "exit":+ break+++asyncio.run(main())diff --git a/examples/functionality/rag/basic_usage.py b/examples/functionality/rag/basic_usage.pynew file mode 100644index 000000000..eaf9ec6b1--- /dev/null+++ b/examples/functionality/rag/basic_usage.py@@ -0,0 +1,79 @@+# -*- coding: utf-8 -*-+"""The main entry point of the RAG example."""+import asyncio+import os++from agentscope.embedding import DashScopeTextEmbedding+from agentscope.rag import (+ TextReader,+ PDFReader,+ QdrantStore,+ SimpleKnowledge,+)+++async def main() -> None:+ """The main entry point of the RAG example."""++ # Create readers with chunking arguments+ reader = TextReader(chunk_size=1024)+ pdf_reader = PDFReader(chunk_size=1024, split_by="sentence")++ # Read documents+ documents = await reader(+ text="I'm Tony Stank, my password is 123456. My best friend is James "+ "Rhodes.",+ )++ # Read a sample PDF file+ pdf_path = os.path.join(+ os.path.abspath(os.path.dirname(__file__)),+ "example.pdf",+ )+ pdf_documents = await pdf_reader(pdf_path=pdf_path)++ # Create a knowledge base with Qdrant as the embedding store and+ # DashScope as the embedding model+ knowledge = SimpleKnowledge(+ embedding_store=QdrantStore(+ location=":memory:",+ collection_name="test_collection",+ dimensions=1024, # The dimension of the embedding vectors+ ),+ embedding_model=DashScopeTextEmbedding(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="text-embedding-v4",+ ),+ )++ # Insert documents into the knowledge base+ await knowledge.add_documents(documents + pdf_documents)++ # Retrieve relevant documents based on a given query+ docs = await knowledge.retrieve(+ query="What is Tony Stank's password?",+ limit=3,+ score_threshold=0.7,+ )+ print("Q1: What is Tony Stank's password?")+ for doc in docs:+ print(+ f"Document ID: {doc.id}, Score: {doc.score}, "+ f"Content: {doc.metadata.content['text']}",+ )++ # Retrieve documents from the PDF file based on a query+ docs = await knowledge.retrieve(+ query="climate change",+ limit=3,+ score_threshold=0.2,+ )+ print("\n\nQ2: climate change")+ for doc in docs:+ print(+ f"Document ID: {doc.id}, Score: {doc.score}, "+ f"Content: {repr(doc.metadata.content['text'])}",+ )+++asyncio.run(main())diff --git a/examples/functionality/rag/example.pdf b/examples/functionality/rag/example.pdfnew file mode 100644index 000000000..fbc7bc8baBinary files /dev/null and b/examples/functionality/rag/example.pdf differdiff --git a/examples/functionality/rag/multimodal_rag.py b/examples/functionality/rag/multimodal_rag.pynew file mode 100644index 000000000..3a53e1995--- /dev/null+++ b/examples/functionality/rag/multimodal_rag.py@@ -0,0 +1,72 @@+# -*- coding: utf-8 -*-+"""The example of how to use multimodal RAG in AgentScope"""+import asyncio+import json+import os++from matplotlib import pyplot as plt++from agentscope.agent import ReActAgent+from agentscope.embedding import DashScopeMultiModalEmbedding+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.rag import ImageReader, SimpleKnowledge, QdrantStore+++path_image = "./example.png"+plt.figure(figsize=(8, 3))+plt.text(0.5, 0.5, "My name is Ming Li", ha="center", va="center", fontsize=30)+plt.axis("off")+plt.savefig(path_image, bbox_inches="tight", pad_inches=0.1)+plt.close()+++async def example_multimodal_rag() -> None:+ """Example for multimodal RAG"""+ # Reading the image and converting it to documents+ reader = ImageReader()+ docs = await reader(image_url=path_image)++ # Create a knowledge base and add documents+ knowledge = SimpleKnowledge(+ embedding_model=DashScopeMultiModalEmbedding(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="multimodal-embedding-v1",+ dimensions=1024,+ ),+ embedding_store=QdrantStore(+ location=":memory:",+ collection_name="test_collection",+ dimensions=1024,+ ),+ )++ await knowledge.add_documents(docs)++ agent = ReActAgent(+ name="Friday",+ sys_prompt="You're a helpful assistant named Friday.",+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen3-vl-plus",+ ),+ formatter=DashScopeChatFormatter(),+ knowledge=knowledge,+ )++ await agent(+ Msg(+ "user",+ "Do you know my name?",+ "user",+ ),+ )++ # Let's see if the agent has stored the retrieved document in its memory+ print("\nThe retrieved document stored in the agent's memory:")+ content = (await agent.memory.get_memory())[-4].content+ print(json.dumps(content, indent=2, ensure_ascii=False))+++asyncio.run(example_multimodal_rag())diff --git a/examples/functionality/rag/react_agent_integration.py b/examples/functionality/rag/react_agent_integration.pynew file mode 100644index 000000000..9477b27c7--- /dev/null+++ b/examples/functionality/rag/react_agent_integration.py@@ -0,0 +1,78 @@+# -*- coding: utf-8 -*-+"""The example of integrating ReAct agent with RAG."""+import asyncio+import os++from agentscope.agent import ReActAgent, UserAgent+from agentscope.embedding import DashScopeTextEmbedding+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.rag import SimpleKnowledge, QdrantStore, TextReader+++async def main() -> None:+ """The main entry point for the ReAct agent with RAG example."""++ # Create an in-memory knowledge base instance+ print("Creating the knowledge base...")+ knowledge = SimpleKnowledge(+ embedding_store=QdrantStore(+ location=":memory:",+ collection_name="test_collection",+ dimensions=1024, # The dimension of the embedding vectors+ ),+ embedding_model=DashScopeTextEmbedding(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="text-embedding-v4",+ ),+ )++ # Insert some documents into the knowledge base+ # This could be done offline and only once+ print("Inserting documents into the knowledge base...")+ reader = TextReader(chunk_size=100, split_by="char")+ documents = await reader(+ # Fake personal profile for demonstration+ "I'm John Doe, 28 years old. My best friend is James "+ "Smith. I live in San Francisco. I work at OpenAI as a "+ "software engineer. I love hiking and photography. "+ "My father is Michael Doe, a doctor. I'm very proud of him. "+ "My mother is Sarah Doe, a teacher. She is very kind and "+ "always helps me with my studies.\n"+ "I'm now a PhD student at Stanford University, majoring in "+ "Computer Science. My advisor is Prof. Jane Williams, who is "+ "a leading expert in artificial intelligence. I have published "+ "several papers in top conferences, such as NeurIPS and ICML. ",+ )++ print("Inserting documents into the knowledge base...")+ await knowledge.add_documents(documents)++ # Integrate into the ReActAgent by the `knowledge` argument+ print("Creating the agent...")+ agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant named Friday.",+ model=DashScopeChatModel(+ api_key=os.environ["DASHSCOPE_API_KEY"],+ model_name="qwen-max",+ ),+ formatter=DashScopeChatFormatter(),+ # Equip the agent with the knowledge base+ knowledge=knowledge,+ print_hint_msg=True,+ )+ user = UserAgent(name="user")++ # Start the conversation+ print("Start the conversation...")+ msg = Msg("user", "Do you know who is my best friend?", "user")+ while True:+ msg = await agent(msg)+ msg = await user(msg)+ if msg.get_text_content() == "exit":+ break+++asyncio.run(main())diff --git a/setup.py b/setup.pyindex a24492229..fd76e31bf 100644--- a/setup.py+++ b/setup.py@@ -35,14 +35,21 @@ minimal_requires = []extra_requires = [+ # Model"ollama","google-genai","Pillow","transformers","jinja2",+ # Evaluator"ray",+ # Long-term memory"mem0ai","packaging",+ # RAG+ "pypdf",+ "nltk",+ "qdrant-client",]dev_requires = [diff --git a/src/agentscope/__init__.py b/src/agentscope/__init__.pyindex 12a7a4ccd..67cb54076 100644--- a/src/agentscope/__init__.py+++ b/src/agentscope/__init__.py@@ -18,12 +18,12 @@ from . import tokenfrom . import evaluatefrom . import pipelinefrom . import tracing+from . import ragfrom ._logging import (logger,setup_logger,)-from .agent import UserAgent, StudioUserInputfrom .hooks import _equip_as_studio_hooksfrom ._version import __version__@@ -85,6 +85,8 @@ def init()response.raise_for_status()+ from .agent import UserAgent, StudioUserInput+UserAgent.override_class_input_method(StudioUserInput(studio_url=studio_url,@@ -123,6 +125,7 @@ __all__ = ["evaluate","pipeline","tracing",+ "rag",# functions"init","setup_logger",diff --git a/src/agentscope/_utils/_common.py b/src/agentscope/_utils/_common.pyindex b51791480..8c648bb32 100644--- a/src/agentscope/_utils/_common.py+++ b/src/agentscope/_utils/_common.py@@ -9,6 +9,7 @@ import osimport tempfileimport typesimport typing+import uuidfrom datetime import datetimefrom typing import Union, Any, Callable, Type, Dict@@ -268,3 +269,17 @@ def _create_tool_from_base_model(},}return tool_definition+++def _map_text_to_uuid(text: str) -> str:+ """Map the given text to a deterministic UUID string.++ Args:+ text (`str`):+ The input text to be mapped to a UUID.++ Returns:+ `str`:+ A deterministic UUID string derived from the input text.+ """+ return str(uuid.uuid3(uuid.NAMESPACE_DNS, text))diff --git a/src/agentscope/agent/_react_agent.py b/src/agentscope/agent/_react_agent.pyindex 24dd2820b..8f44dd798 100644--- a/src/agentscope/agent/_react_agent.py+++ b/src/agentscope/agent/_react_agent.py@@ -6,18 +6,30 @@ import asynciofrom typing import Type, Any, AsyncGenerator, Literalimport shortuuid-from pydantic import BaseModel, ValidationError+from pydantic import BaseModel, ValidationError, Fieldfrom ._react_agent_base import ReActAgentBase+from .._logging import loggerfrom ..formatter import FormatterBasefrom ..memory import MemoryBase, LongTermMemoryBase, InMemoryMemoryfrom ..message import Msg, ToolUseBlock, ToolResultBlock, TextBlockfrom ..model import ChatModelBase+from ..rag import KnowledgeBase, Documentfrom ..plan import PlanNotebookfrom ..tool import Toolkit, ToolResponsefrom ..tracing import trace_reply+class _QueryRewriteModel(BaseModel):+ """The structured model used for query rewriting."""++ rewritten_query: str = Field(+ description=(+ "The rewritten query, which should be specific and concise. "+ ),+ )++def finish_function_pre_print_hook(self: "ReActAgent",kwargs: dict[str, Any],@@ -81,9 +93,11 @@ class ReActAgent(ReActAgentBase):] = "both",enable_meta_tool: bool = False,parallel_tool_calls: bool = False,- max_iters: int = 10,+ knowledge: KnowledgeBase | list[KnowledgeBase] | None = None,+ enable_rewrite_query: bool = True,plan_notebook: PlanNotebook | None = None,print_hint_msg: bool = False,+ max_iters: int = 10,) -> None:"""Initialize the ReAct agent@@ -124,11 +138,23 @@ class ReActAgent(ReActAgentBase):parallel_tool_calls (`bool`, defaults to `False`):When LLM generates multiple tool calls, whether to executethem in parallel.+ knowledge (`KnowledgeBase | list[KnowledgeBase] | None`, optional):+ The knowledge object(s) used by the agent to retrieve+ relevant documents at the beginning of each reply.+ enable_rewrite_query (`bool`, defaults to `True`):+ Whether ask the agent to rewrite the user input query before+ retrieving from the knowledge base(s), e.g. rewrite "Who am I"+ to "{user's name}" to get more relevant documents. Only works+ when the knowledge base(s) is provided.+ plan_notebook (`PlanNotebook | None`, optional):+ The plan notebook instance, allow the agent to finish the+ complex task by decomposing it into a sequence of subtasks.+ print_hint_msg (`bool`, defaults to `False`):+ Whether to print the hint messages, including the reasoning+ hint from the plan notebook, the retrieved information from+ the long-term memory and knowledge base(s).max_iters (`int`, defaults to `10`):The maximum number of iterations of the reasoning-acting loops.- print_hint_msg (`bool`, defaults to `False`):- Whether to print the reasoning hint messages before each- reasoning step."""super().__init__()@@ -145,6 +171,7 @@ class ReActAgent(ReActAgentBase):self.model = modelself.formatter = formatter+ # -------------- Memory management --------------# Record the dialogue history in the memoryself.memory = memory or InMemoryMemory()# If provide the long-term memory, it will be used to retrieve info@@ -162,6 +189,7 @@ class ReActAgent(ReActAgentBase):"both",]+ # -------------- Tool management --------------# If None, a default Toolkit will be createdself.toolkit = toolkit or Toolkit()self.toolkit.register_tool_function(@@ -182,8 +210,18 @@ class ReActAgent(ReActAgentBase):)self.parallel_tool_calls = parallel_tool_calls- self.max_iters = max_iters+ # -------------- RAG management --------------+ # The knowledge base(s) used by the agent+ if isinstance(knowledge, KnowledgeBase):+ knowledge = [knowledge]+ self.knowledge: list[KnowledgeBase] = knowledge or []+ self.enable_rewrite_query = enable_rewrite_query++ # -------------- Plan management --------------+ # Equipped the plan-related tools provided by the plan notebook as+ # a tool group named "plan_related". So that the agent can activate+ # the plan tools by the meta tool functionself.plan_notebook = Noneif plan_notebook:self.plan_notebook = plan_notebook@@ -197,8 +235,12 @@ class ReActAgent(ReActAgentBase):group_name="plan_related",)+ # If print the reasoning hint messagesself.print_hint_msg = print_hint_msg+ # The maximum number of iterations of the reasoning-acting loops+ self.max_iters = max_iters+# The hint messages that will be attached to the prompt to guide the# agent's behavior before each reasoning step, and cleared after# each reasoning step, meaning the hint messages is one-time use only.@@ -210,6 +252,7 @@ class ReActAgent(ReActAgentBase):# If required structured output model is providedself._required_structured_model: Type[BaseModel] | None = None+ # -------------- State registration and hooks --------------# Register the status variablesself.register_state("name")self.register_state("_sys_prompt")@@ -245,22 +288,13 @@ class ReActAgent(ReActAgentBase):`Msg`:The output message generated by the agent."""+ # Record the input message(s) in the memoryawait self.memory.add(msg)- # Long-term memory retrieval- if self._static_control:- # Retrieve information from the long-term memory if available- retrieved_info = await self.long_term_memory.retrieve(msg)- if retrieved_info:- await self.memory.add(- Msg(- name="long_term_memory",- content="<long_term_memory>The content below are "- "retrieved from long-term memory, which maybe "- f"useful:\n{retrieved_info}</long_term_memory>",- role="user",- ),- )+ # Retrieve relevant records from the long-term memory if activated+ await self._retrieve_from_long_term_memory(msg)+ # Retrieve relevant documents from the knowledge base(s) if any+ await self._retrieve_from_knowledge(msg)self._required_structured_model = structured_model# Record structured output model if provided@@ -588,3 +622,125 @@ class ReActAgent(ReActAgentBase):},is_last=True,)++ async def _retrieve_from_long_term_memory(+ self,+ msg: Msg | list[Msg] | None,+ ) -> None:+ """Insert the retrieved information from the long-term memory into+ the short-term memory as a Msg object.++ Args:+ msg (`Msg | list[Msg] | None`):+ The input message to the agent.+ """+ if self._static_control and msg:+ # Retrieve information from the long-term memory if available+ retrieved_info = await self.long_term_memory.retrieve(msg)+ if retrieved_info:+ retrieved_msg = Msg(+ name="long_term_memory",+ content="<long_term_memory>The content below are "+ "retrieved from long-term memory, which maybe "+ f"useful:\n{retrieved_info}</long_term_memory>",+ role="user",+ )+ if self.print_hint_msg:+ await self.print(retrieved_msg, True)+ await self.memory.add(retrieved_msg)++ async def _retrieve_from_knowledge(+ self,+ msg: Msg | list[Msg] | None,+ ) -> None:+ """Insert the retrieved documents from the RAG knowledge base(s) if+ available.++ Args:+ msg (`Msg | list[Msg] | None`):+ The input message to the agent.+ """+ if self.knowledge and msg:+ # Prepare the user input query+ query = None+ if isinstance(msg, Msg):+ query = msg.get_text_content()+ elif isinstance(msg, list):+ query = "\n".join(_.get_text_content() for _ in msg)++ # Skip if the query is empty+ if not query:+ return++ # Rewrite the query by the LLM if enabled+ if self.enable_rewrite_query:+ try:+ rewrite_prompt = await self.formatter.format(+ msgs=[+ Msg("system", self.sys_prompt, "system"),+ *await self.memory.get_memory(),+ Msg(+ "user",+ "<system-hint>Now you need to rewrite "+ "the above user query to be more specific and "+ "concise for knowledge retrieval. For "+ "example, rewrite the query 'what happened "+ "last day' to 'what happened on 2023-10-01' "+ "(assuming today is 2023-10-02)."+ "</system-hint>",+ "user",+ ),+ ],+ )+ stream_tmp = self.model.stream+ self.model.stream = False+ res = await self.model(+ rewrite_prompt,+ structured_model=_QueryRewriteModel,+ )+ self.model.stream = stream_tmp+ if res.metadata and res.metadata.get("rewritten_query"):+ query = res.metadata["rewritten_query"]++ except Exception as e:+ logger.warning(+ "Skipping the query rewriting due to error: %s",+ str(e),+ )++ docs: list[Document] = []+ for kb in self.knowledge:+ # retrieve the user input query+ docs.extend(+ await kb.retrieve(query=query),+ )+ if docs:+ # Rerank by the relevance score+ docs = sorted(+ docs,+ key=lambda doc: doc.score or 0.0,+ reverse=True,+ )+ # Prepare the retrieved knowledge string+ retrieved_msg = Msg(+ name="user",+ content=[+ TextBlock(+ type="text",+ text=(+ "<retrieved_knowledge>Use the following "+ "content from the knowledge base(s) if it's "+ "helpful:\n"+ ),+ ),+ *[_.metadata.content for _ in docs],+ TextBlock(+ type="text",+ text="</retrieved_knowledge>",+ ),+ ],+ role="user",+ )+ if self.print_hint_msg:+ await self.print(retrieved_msg, True)+ await self.memory.add(retrieved_msg)diff --git a/src/agentscope/agent/_user_input.py b/src/agentscope/agent/_user_input.pyindex 86bc2eb5f..e6b3f4a6d 100644--- a/src/agentscope/agent/_user_input.py+++ b/src/agentscope/agent/_user_input.py@@ -192,7 +192,7 @@ class StudioUserInput(UserInputBase):def on_connect() -> None:self._is_connected = Truelogger.info(- 'Connected to AgentScope Studio with project name "%s" and '+ 'Connected to AgentScope Studio at "%s" with ''run name "%s".',self.studio_url,run_id,diff --git a/src/agentscope/embedding/__init__.py b/src/agentscope/embedding/__init__.pyindex 8e667b7a8..de2c2711f 100644--- a/src/agentscope/embedding/__init__.py+++ b/src/agentscope/embedding/__init__.py@@ -5,6 +5,7 @@ from ._embedding_base import EmbeddingModelBasefrom ._embedding_usage import EmbeddingUsagefrom ._embedding_response import EmbeddingResponsefrom ._dashscope_embedding import DashScopeTextEmbedding+from ._dashscope_multimodal_embedding import DashScopeMultiModalEmbeddingfrom ._openai_embedding import OpenAITextEmbeddingfrom ._gemini_embedding import GeminiTextEmbeddingfrom ._ollama_embedding import OllamaTextEmbedding@@ -17,6 +18,7 @@ __all__ = ["EmbeddingUsage","EmbeddingResponse","DashScopeTextEmbedding",+ "DashScopeMultiModalEmbedding","OpenAITextEmbedding","GeminiTextEmbedding","OllamaTextEmbedding",diff --git a/src/agentscope/embedding/_dashscope_embedding.py b/src/agentscope/embedding/_dashscope_embedding.pyindex ea771659d..6c0bea060 100644--- a/src/agentscope/embedding/_dashscope_embedding.py+++ b/src/agentscope/embedding/_dashscope_embedding.py@@ -1,21 +1,38 @@# -*- coding: utf-8 -*-"""The dashscope embedding module in agentscope."""from datetime import datetime-from typing import Any, List+from typing import Any, List, Literalfrom ._cache_base import EmbeddingCacheBasefrom ._embedding_response import EmbeddingResponsefrom ._embedding_usage import EmbeddingUsagefrom ._embedding_base import EmbeddingModelBase+from .._logging import logger+from ..message import TextBlockclass DashScopeTextEmbedding(EmbeddingModelBase):- """DashScope text embedding model class"""+ """DashScope text embedding API class.++ .. note:: From the `official documentation+ <https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=2712515>`_:++ - The max batch size that DashScope text embedding API+ supports is 10 for `text-embedding-v4` and `text-embedding-v3` models, and+ 25 for `text-embedding-v2` and `text-embedding-v1` models.+ - The max token limit for a single input is 8192 tokens for `v4` and `v3`+ models, and 2048 tokens for `v2` and `v1` models.++ """++ supported_modalities: list[str] = ["text"]+ """This class only supports text input."""def __init__(self,api_key: str,model_name: str,+ dimensions: int = 1024,embedding_cache: EmbeddingCacheBase | None = None,) -> None:"""Initialize the DashScope text embedding model class.@@ -25,32 +42,23 @@ class DashScopeTextEmbedding(EmbeddingModelBase):The dashscope API key.model_name (`str`):The name of the embedding model.+ dimensions (`int`, defaults to 1024):+ The dimension of the embedding vector, refer to the+ `official documentation+ <https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=2712515>`_+ for more details.embedding_cache (`EmbeddingCacheBase`):The embedding cache class instance, used to cache theembedding results to avoid repeated API calls."""- super().__init__(model_name)+ super().__init__(model_name, dimensions)self.api_key = api_keyself.embedding_cache = embedding_cache+ self.batch_size_limit = 10- async def __call__(- self,- text: List[str],- **kwargs: Any,- ) -> EmbeddingResponse:- """Call the DashScope embedding API.-- Args:- text (`List[str]`):- The input text to be embedded. It can be a list of strings.- """-- kwargs = {- "input": text,- "model": self.model_name,- **kwargs,- }+ async def _call_api(self, kwargs: dict[str, Any]) -> EmbeddingResponse:+ """Call the DashScope embedding API by the given keyword arguments."""if self.embedding_cache:cached_embeddings = await self.embedding_cache.retrieve(@@ -88,7 +96,7 @@ class DashScopeTextEmbedding(EmbeddingModelBase):],)- embedding_response = EmbeddingResponse(+ return EmbeddingResponse(embeddings=[_["embedding"] for _ in response.output["embeddings"]],usage=EmbeddingUsage(tokens=response.usage["total_tokens"],@@ -96,4 +104,66 @@ class DashScopeTextEmbedding(EmbeddingModelBase):),)- return embedding_response+ async def __call__(+ self,+ text: List[str | TextBlock],+ **kwargs: Any,+ ) -> EmbeddingResponse:+ """Call the DashScope embedding API.++ Args:+ text (`List[str | TextBlock]`):+ The input text to be embedded. It can be a list of strings.+ """+ gather_text = []+ for _ in text:+ if isinstance(_, dict) and "text" in _:+ gather_text.append(_["text"])+ elif isinstance(_, str):+ gather_text.append(_)+ else:+ raise ValueError(+ "Input text must be a list of strings or TextBlock dicts.",+ )++ if len(gather_text) > self.batch_size_limit:+ logger.info(+ "The input texts (%d) will be embedded with %d API calls due "+ f"to the batch size limit of {self.batch_size_limit} for "+ f"DashScope embedding API.",+ len(gather_text),+ (len(gather_text) + self.batch_size_limit - 1)+ // self.batch_size_limit,+ )++ # Handle the batch size limit for DashScope embedding API+ collected_embeddings = []+ collected_time = 0.0+ collected_tokens = 0+ collected_source: Literal["cache", "api"] = "cache"+ for _ in range(0, len(gather_text), self.batch_size_limit):+ batch_texts = gather_text[_ : _ + self.batch_size_limit]+ batch_kwargs = {+ "input": batch_texts,+ "model": self.model_name,+ "dimensions": self.dimensions,+ **kwargs,+ }++ res = await self._call_api(batch_kwargs)++ collected_embeddings.extend(res.embeddings)+ collected_time += res.usage.time+ if res.usage.tokens:+ collected_tokens += res.usage.tokens+ if res.source == "api":+ collected_source = "api"++ return EmbeddingResponse(+ embeddings=collected_embeddings,+ usage=EmbeddingUsage(+ tokens=collected_tokens,+ time=collected_time,+ ),+ source=collected_source,+ )diff --git a/src/agentscope/embedding/_dashscope_multimodal_embedding.py b/src/agentscope/embedding/_dashscope_multimodal_embedding.pynew file mode 100644index 000000000..2f53ad74d--- /dev/null+++ b/src/agentscope/embedding/_dashscope_multimodal_embedding.py@@ -0,0 +1,242 @@+# -*- coding: utf-8 -*-+"""The dashscope multimodal embedding model in agentscope."""+from datetime import datetime+from typing import Any, Literal++from ._cache_base import EmbeddingCacheBase+from ._embedding_response import EmbeddingResponse+from ._embedding_usage import EmbeddingUsage+from ._embedding_base import EmbeddingModelBase+from ..message import (+ VideoBlock,+ ImageBlock,+ TextBlock,+)+++class DashScopeMultiModalEmbedding(EmbeddingModelBase):+ """The DashScope multimodal embedding API, supporting text, image and+ video embedding."""++ supported_modalities: list[str] = ["text", "image", "video"]+ """This class supports text, image and video input."""++ def __init__(+ self,+ api_key: str,+ model_name: str,+ dimensions: int | None = None,+ embedding_cache: EmbeddingCacheBase | None = None,+ ) -> None:+ """Initialize the DashScope multimodal embedding model class.++ Args:+ api_key (`str`):+ The dashscope API key.+ model_name (`str`):+ The name of the embedding model, e.g. "multimodal-embedding-+ v1", "tongyi-embedding-vision-plus".+ dimensions (`int`, defaults to 1024):+ The dimension of the embedding vector, refer to the+ `official documentation+ <https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=2712517>`_+ for more details.+ embedding_cache (`EmbeddingCacheBase`):+ The embedding cache class instance, used to cache the+ embedding results to avoid repeated API calls.+ """+ path_doc = (+ "https://bailian.console.aliyun.com/?tab=api#/api/?type=model&"+ "url=2712517"+ )+ self.batch_size_limit = 1++ if model_name.startswith("tongyi-embedding-vision-plus"):+ self.batch_size_limit = 8+ if dimensions is None:+ dimensions = 1152+ elif dimensions != 1152:+ raise ValueError(+ f"The dimension of model {model_name} must be 1152, "+ "refer to the official documentation for more details: "+ f"{path_doc}",+ )+ if model_name.startswith("tongyi-embedding-vision-flash"):+ self.batch_size_limit = 8+ if dimensions is None:+ dimensions = 768+ elif dimensions != 768:+ raise ValueError(+ f"The dimension of model {model_name} must be 768, "+ "refer to the official documentation for more details: "+ f"{path_doc}",+ )+ if model_name.startswith("multimodal-embedding-v"):+ if dimensions is None:+ dimensions = 1024+ elif dimensions != 1024:+ raise ValueError(+ f"The dimension of model {model_name} must be 1024, "+ "refer to the official documentation for more details: "+ f"{path_doc}",+ )+ refined_dimensions: int = 1024+ if dimensions is not None:+ refined_dimensions = dimensions+ super().__init__(model_name, refined_dimensions)++ self.api_key = api_key+ self.embedding_cache = embedding_cache++ async def __call__(+ self,+ inputs: list[TextBlock | ImageBlock | VideoBlock],+ **kwargs: Any,+ ) -> EmbeddingResponse:+ """Call the DashScope multimodal embedding API, which accepts text,+ image, and video data.++ Args:+ inputs (`list[TextBlock | ImageBlock | VideoBlock]`):+ The input data to be embedded. It can be a list of text,+ image, and video blocks.++ Returns:+ `EmbeddingResponse`:+ The embedding response object, which contains the embeddings+ and usage information.+ """+ # check data type+ formatted_data = []+ for _ in inputs:+ if (+ not isinstance(_, dict)+ or "type" not in _+ or _["type"]+ not in [+ "text",+ "image",+ "video",+ ]+ ):+ raise ValueError(+ f"Invalid data : {_}. It should be a list of "+ "TextBlock, ImageBlock, or VideoBlock.",+ )+ if (+ _["type"] == "video"+ and _.get("source", {}).get("type") != "url"+ ):+ raise ValueError(+ f"The multimodal embedding API only supports URL input "+ f"for video data, but got {_}.",+ )++ if _["type"] == "text":+ assert "text" in _, (+ f"Invalid text block: {_}. It should contain a "+ f"'text' field.",+ )+ formatted_data.append({"text": _["text"]})++ elif _["type"] == "video":+ formatted_data.append({"video": _["source"]["url"]})++ elif (+ _["type"] == "image"+ and "source" in _+ and _["source"].get("type") in ["base64", "url"]+ ):+ typ = _["source"]["type"]+ if typ == "base64":+ formatted_data.append(+ {+ "image": f'data:{_["source"]["media_type"]};'+ f'base64,{_["source"]["data"]}',+ },+ )+ elif typ == "url":+ formatted_data.append(+ {"image": _["source"]["url"]},+ )+ else:+ raise ValueError(+ f"Invalid block {_}. It should be a valid TextBlock, "+ f"ImageBlock, or VideoBlock.",+ )++ # Handle the batch size limit of the DashScope multimodal embedding API+ collected_embeddings = []+ collected_time = 0.0+ collected_tokens = 0+ collected_source: Literal["cache", "api"] = "cache"+ for _ in range(0, len(formatted_data), self.batch_size_limit):+ batch_data = formatted_data[_ : _ + self.batch_size_limit]+ batch_kwargs = {+ "input": batch_data,+ "model": self.model_name,+ **kwargs,+ }+ res = await self._call_api(batch_kwargs)++ collected_embeddings.extend(res.embeddings)+ collected_time += res.usage.time+ if res.usage.tokens:+ collected_tokens += res.usage.tokens+ if res.source == "api":+ collected_source = "api"++ return EmbeddingResponse(+ embeddings=collected_embeddings,+ usage=EmbeddingUsage(+ tokens=collected_tokens,+ time=collected_time,+ ),+ source=collected_source,+ )++ async def _call_api(self, kwargs: dict[str, Any]) -> EmbeddingResponse:+ """+ Call the DashScope multimodal embedding API by the given arguments.+ """+ # Search in cache first+ if self.embedding_cache:+ cached_embeddings = await self.embedding_cache.retrieve(+ identifier=kwargs,+ )+ if cached_embeddings:+ return EmbeddingResponse(+ embeddings=cached_embeddings,+ usage=EmbeddingUsage(+ tokens=0,+ time=0,+ ),+ source="cache",+ )++ import dashscope++ start_time = datetime.now()+ res = dashscope.MultiModalEmbedding.call(**kwargs)+ time = (datetime.now() - start_time).total_seconds()++ if res.status_code != 200:+ raise RuntimeError(+ f"Failed to get embedding from DashScope API: {res}",+ )++ return EmbeddingResponse(+ embeddings=[_["embedding"] for _ in res.output["embeddings"]],+ usage=EmbeddingUsage(+ tokens=res.usage.get(+ "image_tokens",+ 0,+ )+ + res.usage.get(+ "input_tokens",+ 0,+ ),+ time=time,+ ),+ source="api",+ )diff --git a/src/agentscope/embedding/_embedding_base.py b/src/agentscope/embedding/_embedding_base.pyindex 1ac8634fd..0ee31e0a8 100644--- a/src/agentscope/embedding/_embedding_base.py+++ b/src/agentscope/embedding/_embedding_base.py@@ -1,14 +1,9 @@# -*- coding: utf-8 -*-"""The embedding model base class."""-from typing import Any, List, TYPE_CHECKING+from typing import Anyfrom ._embedding_response import EmbeddingResponse-if TYPE_CHECKING:- from ..model import ChatResponse-else:- ChatResponse = "ChatResponse"-class EmbeddingModelBase:"""Base class for embedding models."""@@ -16,21 +11,31 @@ class EmbeddingModelBase:model_name: str"""The embedding model name"""+ supported_modalities: list[str]+ """The supported data modalities, e.g. "text", "image", "video"."""++ dimensions: int+ """The dimensions of the embedding vector."""+def __init__(self,model_name: str,+ dimensions: int,) -> None:"""Initialize the embedding model base class.Args:model_name (`str`):The name of the embedding model.+ dimensions (`int`):+ The dimension of the embedding vector."""self.model_name = model_name+ self.dimensions = dimensionsasync def __call__(self,- text: List[str],+ *args: Any,**kwargs: Any,) -> EmbeddingResponse:"""Call the embedding API with the given arguments."""diff --git a/src/agentscope/embedding/_gemini_embedding.py b/src/agentscope/embedding/_gemini_embedding.pyindex 15ea8ee34..8f0c06898 100644--- a/src/agentscope/embedding/_gemini_embedding.py+++ b/src/agentscope/embedding/_gemini_embedding.py@@ -7,15 +7,20 @@ from ._embedding_response import EmbeddingResponsefrom ._embedding_usage import EmbeddingUsagefrom ._cache_base import EmbeddingCacheBasefrom ._embedding_base import EmbeddingModelBase+from ..message import TextBlockclass GeminiTextEmbedding(EmbeddingModelBase):"""The Gemini text embedding model."""+ supported_modalities: list[str] = ["text"]+ """This class only supports text input."""+def __init__(self,api_key: str,model_name: str,+ dimensions: int = 3072,embedding_cache: EmbeddingCacheBase | None = None,**kwargs: Any,) -> None:@@ -26,31 +31,49 @@ class GeminiTextEmbedding(EmbeddingModelBase):The Gemini API key.model_name (`str`):The name of the embedding model.+ dimensions (`int`, defaults to 3072):+ The dimension of the embedding vector, refer to the+ `official documentation+ <https://ai.google.dev/gemini-api/docs/embeddings?hl=zh-cn#control-embedding-size>`_+ for more details.embedding_cache (`EmbeddingCacheBase | None`, defaults to `None`):The embedding cache class instance, used to cache theembedding results to avoid repeated API calls."""from google import genai- super().__init__(model_name)+ super().__init__(model_name, dimensions)self.client = genai.Client(api_key=api_key, **kwargs)self.embedding_cache = embedding_cacheasync def __call__(self,- text: List[str],+ text: List[str | TextBlock],**kwargs: Any,) -> EmbeddingResponse:"""The Gemini embedding API call.Args:- text (`List[str]`):+ text (`List[str | TextBlock]`):The input text to be embedded. It can be a list of strings.++ # TODO: handle the batch size limit"""+ gather_text = []+ for _ in text:+ if isinstance(_, dict) and "text" in _:+ gather_text.append(_["text"])+ elif isinstance(_, str):+ gather_text.append(_)+ else:+ raise ValueError(+ "Input text must be a list of strings or TextBlock dicts.",+ )+kwargs = {"model": self.model_name,- "contents": text,+ "contents": gather_text,"config": kwargs,}diff --git a/src/agentscope/embedding/_ollama_embedding.py b/src/agentscope/embedding/_ollama_embedding.pyindex 7a913ffca..f5445072b 100644--- a/src/agentscope/embedding/_ollama_embedding.py+++ b/src/agentscope/embedding/_ollama_embedding.py@@ -8,14 +8,19 @@ from ._embedding_response import EmbeddingResponsefrom ._embedding_usage import EmbeddingUsagefrom ._cache_base import EmbeddingCacheBasefrom ..embedding import EmbeddingModelBase+from ..message import TextBlockclass OllamaTextEmbedding(EmbeddingModelBase):"""The Ollama embedding model."""+ supported_modalities: list[str] = ["text"]+ """This class only supports text input."""+def __init__(self,model_name: str,+ dimensions: int,host: str | None = None,embedding_cache: EmbeddingCacheBase | None = None,**kwargs: Any,@@ -25,6 +30,9 @@ class OllamaTextEmbedding(EmbeddingModelBase):Args:model_name (`str`):The name of the embedding model.+ dimensions (`int`):+ The dimension of the embedding vector, the parameter should be+ provided according to the model used.host (`str | None`, defaults to `None`):The host URL for the Ollama API.embedding_cache (`EmbeddingCacheBase | None`, defaults to `None`):@@ -33,22 +41,32 @@ class OllamaTextEmbedding(EmbeddingModelBase):"""import ollama- super().__init__(model_name)+ super().__init__(model_name, dimensions)self.client = ollama.AsyncClient(host=host, **kwargs)self.embedding_cache = embedding_cacheasync def __call__(self,- text: List[str],+ text: List[str | TextBlock],**kwargs: Any,) -> EmbeddingResponse:"""Call the Ollama embedding API.Args:- text (`List[str]`):+ text (`List[str | TextBlock]`):The input text to be embedded. It can be a list of strings."""+ gather_text = []+ for _ in text:+ if isinstance(_, dict) and "text" in _:+ gather_text.append(_["text"])+ elif isinstance(_, str):+ gather_text.append(_)+ else:+ raise ValueError(+ "Input text must be a list of strings or TextBlock dicts.",+ )if self.embedding_cache:cached_embeddings = await self.embedding_cache.retrieve(@@ -68,7 +86,7 @@ class OllamaTextEmbedding(EmbeddingModelBase):response = await asyncio.gather(*[self.client.embeddings(self.model_name, _, **kwargs)- for _ in text+ for _ in gather_text],)time = (datetime.now() - start_time).total_seconds()diff --git a/src/agentscope/embedding/_openai_embedding.py b/src/agentscope/embedding/_openai_embedding.pyindex aa459365e..88b2e1eb0 100644--- a/src/agentscope/embedding/_openai_embedding.py+++ b/src/agentscope/embedding/_openai_embedding.py@@ -7,15 +7,20 @@ from ._embedding_response import EmbeddingResponsefrom ._embedding_usage import EmbeddingUsagefrom ._cache_base import EmbeddingCacheBasefrom ._embedding_base import EmbeddingModelBase+from ..message import TextBlockclass OpenAITextEmbedding(EmbeddingModelBase):"""OpenAI text embedding model class."""+ supported_modalities: list[str] = ["text"]+ """This class only supports text input."""+def __init__(self,api_key: str,model_name: str,+ dimensions: int = 1024,embedding_cache: EmbeddingCacheBase | None = None,**kwargs: Any,) -> None:@@ -26,32 +31,47 @@ class OpenAITextEmbedding(EmbeddingModelBase):The OpenAI API key.model_name (`str`):The name of the embedding model.+ dimensions (`int`, defaults to 1024):+ The dimension of the embedding vector.embedding_cache (`EmbeddingCacheBase | None`, defaults to `None`):The embedding cache class instance, used to cache theembedding results to avoid repeated API calls.++ # TODO: handle batch size limit and token limit"""import openai- super().__init__(model_name)+ super().__init__(model_name, dimensions)self.client = openai.AsyncClient(api_key=api_key, **kwargs)self.embedding_cache = embedding_cacheasync def __call__(self,- text: List[str],+ text: List[str | TextBlock],**kwargs: Any,) -> EmbeddingResponse:"""Call the OpenAI embedding API.Args:- text (`List[str]`):+ text (`List[str | TextBlock]`):The input text to be embedded. It can be a list of strings."""+ gather_text = []+ for _ in text:+ if isinstance(_, dict) and "text" in _:+ gather_text.append(_["text"])+ elif isinstance(_, str):+ gather_text.append(_)+ else:+ raise ValueError(+ "Input text must be a list of strings or TextBlock dicts.",+ )kwargs = {- "input": text,+ "input": gather_text,"model": self.model_name,+ "dimensions": self.dimensions,"encoding_format": "float",**kwargs,}diff --git a/src/agentscope/model/_dashscope_model.py b/src/agentscope/model/_dashscope_model.pyindex e697fa6d1..83b50dbf3 100644--- a/src/agentscope/model/_dashscope_model.py+++ b/src/agentscope/model/_dashscope_model.py@@ -401,7 +401,7 @@ class DashScopeChatModel(ChatModelBase):raise RuntimeError(response)content_blocks: List[TextBlock | ToolUseBlock] = []- metadata = None+ metadata: dict | None = Nonemessage = response.output.choices[0].messagecontent = message.get("content")diff --git a/src/agentscope/model/_gemini_model.py b/src/agentscope/model/_gemini_model.pyindex ff20e8805..8eaacb972 100644--- a/src/agentscope/model/_gemini_model.py+++ b/src/agentscope/model/_gemini_model.py@@ -217,7 +217,7 @@ class GeminiChatModel(ChatModelBase):text = ""thinking = ""- metadata = None+ metadata: dict | None = Noneasync for chunk in response:content_block: list = []@@ -315,7 +315,7 @@ class GeminiChatModel(ChatModelBase):will be stored in the metadata of the `ChatResponse`."""content_blocks: List[TextBlock | ToolUseBlock | ThinkingBlock] = []- metadata = None+ metadata: dict | None = Noneif (response.candidatesdiff --git a/src/agentscope/model/_model_response.py b/src/agentscope/model/_model_response.pyindex 4726328ac..6f8e52f61 100644--- a/src/agentscope/model/_model_response.py+++ b/src/agentscope/model/_model_response.py@@ -36,7 +36,7 @@ class ChatResponse(DictMixin):usage: ChatUsage | None = field(default_factory=lambda: None)"""The usage information of the chat response, if available."""- metadata: JSONSerializableObject | None = field(+ metadata: dict[str, JSONSerializableObject] | None = field(default_factory=lambda: None,)"""The metadata of the chat response"""diff --git a/src/agentscope/model/_ollama_model.py b/src/agentscope/model/_ollama_model.pyindex ddae610c1..4d1b1af28 100644--- a/src/agentscope/model/_ollama_model.py+++ b/src/agentscope/model/_ollama_model.py@@ -195,7 +195,7 @@ class OllamaChatModel(ChatModelBase):accumulated_text = ""acc_thinking_content = ""tool_calls = OrderedDict() # Store tool calls- metadata = None+ metadata: dict | None = Noneasync for chunk in response:# Handle text content@@ -289,7 +289,7 @@ class OllamaChatModel(ChatModelBase):will be stored in the metadata of the `ChatResponse`."""content_blocks: List[TextBlock | ToolUseBlock | ThinkingBlock] = []- metadata = None+ metadata: dict | None = Noneif response.message.thinking:content_blocks.append(@@ -307,7 +307,9 @@ class OllamaChatModel(ChatModelBase):),)if structured_model:- metadata = _json_loads_with_repair(response.message.content)+ metadata = _json_loads_with_repair(+ response.message.content,+ )for idx, tool_call in enumerate(response.message.tool_calls or []):content_blocks.append(diff --git a/src/agentscope/model/_openai_model.py b/src/agentscope/model/_openai_model.pyindex 777f2a1ba..c1c2e72c2 100644--- a/src/agentscope/model/_openai_model.py+++ b/src/agentscope/model/_openai_model.py@@ -249,7 +249,7 @@ class OpenAIChatModel(ChatModelBase):thinking = ""audio = ""tool_calls = OrderedDict()- metadata = None+ metadata: dict | None = Nonecontents: List[TextBlock | ToolUseBlock | ThinkingBlock | AudioBlock] = []@@ -401,7 +401,7 @@ class OpenAIChatModel(ChatModelBase):content_blocks: List[TextBlock | ToolUseBlock | ThinkingBlock | AudioBlock] = []- metadata = None+ metadata: dict | None = Noneif response.choices:choice = response.choices[0]diff --git a/src/agentscope/rag/__init__.py b/src/agentscope/rag/__init__.pynew file mode 100644index 000000000..08fd67bd7--- /dev/null+++ b/src/agentscope/rag/__init__.py@@ -0,0 +1,33 @@+# -*- coding: utf-8 -*-+"""The retrieval-augmented generation (RAG) module in AgentScope."""++from ._document import (+ DocMetadata,+ Document,+)+from ._reader import (+ ReaderBase,+ TextReader,+ PDFReader,+ ImageReader,+)+from ._store import (+ VDBStoreBase,+ QdrantStore,+)+from ._knowledge_base import KnowledgeBase+from ._simple_knowledge import SimpleKnowledge+++__all__ = [+ "ReaderBase",+ "TextReader",+ "PDFReader",+ "ImageReader",+ "DocMetadata",+ "Document",+ "VDBStoreBase",+ "QdrantStore",+ "KnowledgeBase",+ "SimpleKnowledge",+]diff --git a/src/agentscope/rag/_document.py b/src/agentscope/rag/_document.pynew file mode 100644index 000000000..4b48c8e73--- /dev/null+++ b/src/agentscope/rag/_document.py@@ -0,0 +1,51 @@+# -*- coding: utf-8 -*-+"""The document data structure used in RAG as the data chunk and+retrieval result."""+from dataclasses import dataclass, field++import shortuuid+from dashscope.api_entities.dashscope_response import DictMixin++from ..message import (+ TextBlock,+ ImageBlock,+ VideoBlock,+)+from ..types import Embedding+++@dataclass+class DocMetadata(DictMixin):+ """The metadata of the document."""++ content: TextBlock | ImageBlock | VideoBlock+ """The data content, e.g., text, image, video."""++ doc_id: str+ """The document ID."""++ chunk_id: int+ """The chunk ID."""++ total_chunks: int+ """The total number of chunks."""+++@dataclass+class Document:+ """The data chunk."""++ metadata: DocMetadata+ """The metadata of the data chunk."""++ id: str = field(default_factory=shortuuid.uuid)+ """The unique ID of the data chunk."""++ # The fields that will be filled when the document is added to or+ # retrieved from the knowledge base.++ embedding: Embedding | None = field(default_factory=lambda: None)+ """The embedding of the data chunk."""++ score: float | None = None+ """The relevance score of the data chunk."""diff --git a/src/agentscope/rag/_knowledge_base.py b/src/agentscope/rag/_knowledge_base.pynew file mode 100644index 000000000..dcd05e032--- /dev/null+++ b/src/agentscope/rag/_knowledge_base.py@@ -0,0 +1,130 @@+# -*- coding: utf-8 -*-+"""The knowledge base abstraction for retrieval-augmented generation (RAG)."""+from abc import abstractmethod+from typing import Any++from ._reader import Document+from ..embedding import EmbeddingModelBase+from ._store import VDBStoreBase+from ..message import TextBlock+from ..tool import ToolResponse+++class KnowledgeBase:+ """The knowledge base abstraction for retrieval-augmented generation+ (RAG).++ The ``retrieve`` and ``add_documents`` methods need to be implemented+ in the subclasses. We also provide a quick method ``retrieve_knowledge``+ that enables the agent to retrieve knowledge easily.+ """++ embedding_store: VDBStoreBase+ """The embedding store for the knowledge base."""++ embedding_model: EmbeddingModelBase+ """The embedding model for the knowledge base."""++ def __init__(+ self,+ embedding_store: VDBStoreBase,+ embedding_model: EmbeddingModelBase,+ ) -> None:+ """Initialize the knowledge base."""+ self.embedding_store = embedding_store+ self.embedding_model = embedding_model++ @abstractmethod+ async def retrieve(+ self,+ query: str,+ limit: int = 5,+ score_threshold: float | None = None,+ **kwargs: Any,+ ) -> list[Document]:+ """Retrieve relevant documents by the given query.++ Args:+ query (`str`):+ The query string to retrieve relevant documents.+ limit (`int`, defaults to 5):+ The number of relevant documents to retrieve.+ score_threshold (`float | None`, defaults to `None`):+ The score threshold to filter the retrieved documents. If+ provided, only documents with a score higher than the+ threshold will be returned.+ **kwargs (`Any`):+ Other keyword arguments for the vector database search API.+ """++ @abstractmethod+ async def add_documents(+ self,+ documents: list[Document],+ **kwargs: Any,+ ) -> None:+ """Add documents to the knowledge base, which will embed the documents+ and store them in the embedding store.++ Args:+ documents (`list[Document]`):+ A list of documents to add.+ """++ # A quick method that enable the agent to retrieve knowledge+ # Developers can wrap the `retrieve` method by themselves to support+ # more flexible usage+ async def retrieve_knowledge(+ self,+ query: str,+ limit: int = 5,+ score_threshold: float | None = None,+ **kwargs: Any,+ ) -> ToolResponse:+ """Retrieve relevant documents from the knowledge base. Note the+ `query` parameter is directly related to the retrieval quality, and+ for the same question, you can try many different queries to get the+ best results. Adjust the `limit` and `score_threshold` parameters+ to get more or fewer results.++ Args:+ query (`str`):+ The query string, which should be specific and concise. For+ example, you should provide the specific name instead of+ "you", "my", "he", "she", etc.+ limit (`int`, defaults to 3):+ The number of relevant documents to retrieve.+ score_threshold (`float`, defaults to 0.8):+ A threshold in [0, 1] and only the relevance score above this+ threshold will be returned. Reduce this value to get more+ results.+ """++ docs = await self.retrieve(+ query=query,+ limit=limit,+ score_threshold=score_threshold,+ **kwargs,+ )++ if len(docs):+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Score: {_.score}, "+ f"Content: {_.metadata.content['text']}",+ )+ for _ in docs+ ],+ )+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text="No relevant documents found. TRY to reduce the "+ "`score_threshold` parameter to get "+ "more results.",+ ),+ ],+ )diff --git a/src/agentscope/rag/_reader/__init__.py b/src/agentscope/rag/_reader/__init__.pynew file mode 100644index 000000000..deb421636--- /dev/null+++ b/src/agentscope/rag/_reader/__init__.py@@ -0,0 +1,16 @@+# -*- coding: utf-8 -*-+"""The reader abstraction for retrieval-augmented generation (RAG)."""++from ._reader_base import ReaderBase, Document+from ._text_reader import TextReader+from ._pdf_reader import PDFReader+from ._image_reader import ImageReader+++__all__ = [+ "Document",+ "ReaderBase",+ "TextReader",+ "PDFReader",+ "ImageReader",+]diff --git a/src/agentscope/rag/_reader/_image_reader.py b/src/agentscope/rag/_reader/_image_reader.pynew file mode 100644index 000000000..b5d12cbbc--- /dev/null+++ b/src/agentscope/rag/_reader/_image_reader.py@@ -0,0 +1,67 @@+# -*- coding: utf-8 -*-+"""The Image reader modules"""+import hashlib++from .. import DocMetadata+from ...message import ImageBlock, URLSource+from .._reader import ReaderBase, Document+++class ImageReader(ReaderBase):+ """A simple image reader that wraps the image into a Document object.++ This class is only a simple implementation to support multimodal RAG.+ """++ async def __call__(self, image_url: str | list[str]) -> list[Document]:+ """Read an image and return the wrapped Document object.++ Args:+ image_url (`str | list[str]`):+ The image URL(s) or path(s).++ Returns:+ `list[Document]`:+ A list of Document objects containing the image data.+ """+ # Read the image data and wrap it into a Document object.+ if isinstance(image_url, str):+ image_url = [image_url]++ image_blocks: list[ImageBlock] = [+ ImageBlock(+ type="image",+ source=URLSource(+ type="url",+ url=_,+ ),+ )+ for _ in image_url+ ]++ doc_idx = [self.get_doc_id(_) for _ in image_url]++ return [+ Document(+ metadata=DocMetadata(+ content=image_block,+ doc_id=doc_id,+ chunk_id=0,+ total_chunks=1,+ ),+ )+ for doc_id, image_block in zip(doc_idx, image_blocks)+ ]++ def get_doc_id(self, image_path: str) -> str:+ """Generate a document ID based on the image path.++ Args:+ image_path (`str`):+ The image path or URL.++ Returns:+ `str`:+ The generated document ID.+ """+ return hashlib.md5(image_path.encode("utf-8")).hexdigest()diff --git a/src/agentscope/rag/_reader/_pdf_reader.py b/src/agentscope/rag/_reader/_pdf_reader.pynew file mode 100644index 000000000..e6c5507e6--- /dev/null+++ b/src/agentscope/rag/_reader/_pdf_reader.py@@ -0,0 +1,86 @@+# -*- coding: utf-8 -*-+"""The PDF reader to read and chunk PDF files."""+import hashlib+from typing import Literal++from ._reader_base import ReaderBase+from ._text_reader import TextReader+from .._document import Document+++class PDFReader(ReaderBase):+ """The PDF reader that splits text into chunks by a fixed chunk size."""++ def __init__(+ self,+ chunk_size: int = 512,+ split_by: Literal["char", "sentence", "paragraph"] = "sentence",+ ) -> None:+ """Initialize the text reader.++ Args:+ chunk_size (`int`, default to 512):+ The size of each chunk, in number of characters.+ split_by (`Literal["char", "sentence", "paragraph"]`, default to \+ "sentence"):+ The unit to split the text, can be "char", "sentence", or+ "paragraph". The "sentence" option is implemented using the+ "nltk" library, which only supports English text.+ """+ if chunk_size <= 0:+ raise ValueError(+ f"The chunk_size must be positive, got {chunk_size}",+ )++ if split_by not in ["char", "sentence", "paragraph"]:+ raise ValueError(+ "The split_by must be one of 'char', 'sentence' or "+ f"'paragraph', got {split_by}",+ )++ self.chunk_size = chunk_size+ self.split_by = split_by++ # To avoid code duplication, we use TextReader to do the chunking.+ self._text_reader = TextReader(+ self.chunk_size,+ self.split_by,+ )++ async def __call__(+ self,+ pdf_path: str,+ ) -> list[Document]:+ """Read a PDF file, split it into chunks, and return a list of+ Document objects.++ Args:+ pdf_path (`str`):+ The input PDF file path.+ """+ try:+ from pypdf import PdfReader+ except ImportError as e:+ raise ImportError(+ "Please install pypdf to use the PDF reader. "+ "You can install it by `pip install pypdf`.",+ ) from e++ reader = PdfReader(pdf_path)++ gather_texts = []+ for page in reader.pages:+ gather_texts.append(page.extract_text())++ doc_id = hashlib.sha256(pdf_path.encode("utf-8")).hexdigest()++ docs = await self._text_reader("\n\n".join(gather_texts))+ for doc in docs:+ doc.id = doc_id++ return docs++ def get_doc_id(self, pdf_path: str) -> str:+ """Get the document ID. This function can be used to check if the+ doc_id already exists in the knowledge base."""+ return hashlib.sha256(pdf_path.encode("utf-8")).hexdigest()diff --git a/src/agentscope/rag/_reader/_reader_base.py b/src/agentscope/rag/_reader/_reader_base.pynew file mode 100644index 000000000..14531ed03--- /dev/null+++ b/src/agentscope/rag/_reader/_reader_base.py@@ -0,0 +1,27 @@+# -*- coding: utf-8 -*-+"""The reader base class for retrieval-augmented generation (RAG)."""+from abc import abstractmethod+from typing import Any++from .._document import Document+++class ReaderBase:+ """The reader base class, which is responsible for reading the original+ data, splitting it into chunks, and converting each chunk into a `Document`+ object."""++ @abstractmethod+ async def __call__(self, *args: Any, **kwargs: Any) -> list[Document]:+ """The async call function that takes the input files and returns the+ vector records"""++ @abstractmethod+ def get_doc_id(self, *args: Any, **kwargs: Any) -> str:+ """Get a unique document ID for the input data. This method is to+ expose the document ID generation logic to the developers++ Returns:+ `str`:+ A unique document ID for the input data.+ """diff --git a/src/agentscope/rag/_reader/_text_reader.py b/src/agentscope/rag/_reader/_text_reader.pynew file mode 100644index 000000000..eb836eaca--- /dev/null+++ b/src/agentscope/rag/_reader/_text_reader.py@@ -0,0 +1,149 @@+# -*- coding: utf-8 -*-+"""The text reader that reads text into vector records."""+import hashlib+import os+from typing import Literal++from ._reader_base import ReaderBase, Document+from .._document import DocMetadata+from ..._logging import logger+from ...message import TextBlock+++class TextReader(ReaderBase):+ """The text reader that splits text into chunks by a fixed chunk size+ and chunk overlap."""++ def __init__(+ self,+ chunk_size: int = 512,+ split_by: Literal["char", "sentence", "paragraph"] = "sentence",+ ) -> None:+ """Initialize the text reader.++ Args:+ chunk_size (`int`, default to 512):+ The size of each chunk, in number of characters.+ split_by (`Literal["char", "paragraph"]`, default to \+ "sentence"):+ The unit to split the text, can be "char", "sentence", or+ "paragraph". Note that "sentence" is implemented by "nltk"+ library, which only supports English text.+ """+ if chunk_size <= 0:+ raise ValueError(+ f"The chunk_size must be positive, got {chunk_size}",+ )++ if split_by not in ["char", "sentence", "paragraph"]:+ raise ValueError(+ "The split_by must be one of 'char', 'sentence' or "+ f"'paragraph', got {split_by}",+ )++ self.chunk_size = chunk_size+ self.split_by = split_by++ async def __call__(+ self,+ text: str,+ ) -> list[Document]:+ """Read a text string, split it into chunks, and return a list of+ Document objects.++ Args:+ text (`str`):+ The input text string, or a path to the local text file.++ Returns:+ `list[Document]`:+ A list of Document objects, where the metadata contains the+ chunked text, doc id and chunk id.+ """+ if os.path.exists(text) and os.path.isfile(text):+ logger.info("Reading text from local file: %s", text)+ with open(text, "r", encoding="utf-8") as file:+ text = file.read()++ logger.info(+ "Reading text with chunk_size=%d, split_by=%s",+ self.chunk_size,+ self.split_by,+ )+ splits = []+ if self.split_by == "char":+ # Split by character+ for i in range(0, len(text), self.chunk_size):+ start = max(0, i)+ end = min(i + self.chunk_size, len(text))+ splits.append(text[start:end])++ elif self.split_by == "sentence":+ try:+ import nltk++ nltk.download("punkt")+ nltk.download("punkt_tab")+ except ImportError as e:+ raise ImportError(+ "nltk is not installed. Please install it with "+ "`pip install nltk`.",+ ) from e++ sentences = nltk.sent_tokenize(text)++ # Handle the chunk_size for sentences+ processed_sentences = []+ for _ in sentences:+ if len(_) <= self.chunk_size:+ processed_sentences.append(_)+ else:+ # If the sentence itself exceeds chunk size, we need to+ # truncate it+ chunks = [+ _[j : j + self.chunk_size]+ for j in range(0, len(_), self.chunk_size)+ ]+ processed_sentences.extend(chunks)++ splits.extend(processed_sentences)++ elif self.split_by == "paragraph":+ paragraphs = [_ for _ in text.split("\n") if len(_)]+ for para in paragraphs:+ if len(para) <= self.chunk_size:+ splits.append(para)++ else:+ # If the paragraph itself exceeds chunk size, we need to+ # truncate it+ chunks = [+ para[k : k + self.chunk_size]+ for k in range(0, len(para), self.chunk_size)+ ]+ splits.extend(chunks)++ logger.info(+ "Finished splitting the text into %d chunks.",+ len(splits),+ )++ doc_id = self.get_doc_id(text)++ return [+ Document(+ id=doc_id,+ metadata=DocMetadata(+ content=TextBlock(type="text", text=_),+ doc_id=doc_id,+ chunk_id=idx,+ total_chunks=len(splits),+ ),+ )+ for idx, _ in enumerate(splits)+ ]++ def get_doc_id(self, text: str) -> str:+ """Get the document ID. This function can be used to check if the+ doc_id already exists in the knowledge base."""+ return hashlib.sha256(text.encode("utf-8")).hexdigest()diff --git a/src/agentscope/rag/_simple_knowledge.py b/src/agentscope/rag/_simple_knowledge.pynew file mode 100644index 000000000..1e1e2f28b--- /dev/null+++ b/src/agentscope/rag/_simple_knowledge.py@@ -0,0 +1,84 @@+# -*- coding: utf-8 -*-+"""A general implementation of the knowledge class in AgentScope RAG module."""+from typing import Any++from ._reader import Document+from ..message import TextBlock+from ._knowledge_base import KnowledgeBase+++class SimpleKnowledge(KnowledgeBase):+ """A simple knowledge base implementation."""++ async def retrieve(+ self,+ query: str,+ limit: int = 5,+ score_threshold: float | None = None,+ **kwargs: Any,+ ) -> list[Document]:+ """Retrieve relevant documents by the given queries.++ Args:+ query (`str`):+ The query string to retrieve relevant documents.+ limit (`int`, defaults to 5):+ The number of relevant documents to retrieve.+ score_threshold: float | None = None,+ The threshold of the score to filter the results.+ **kwargs (`Any`):+ Other keyword arguments for the vector database search API.++ Returns:+ `list[Document]`:+ A list of relevant documents.++ TODO: handle the case when the query is too long.+ """+ res_embedding = await self.embedding_model(+ [+ TextBlock(+ type="text",+ text=query,+ ),+ ],+ )+ res = await self.embedding_store.search(+ res_embedding.embeddings[0],+ limit=limit,+ score_threshold=score_threshold,+ **kwargs,+ )+ return res++ async def add_documents(+ self,+ documents: list[Document],+ **kwargs: Any,+ ) -> None:+ """Add documents to the knowledge++ Args:+ documents (`list[Document]`):+ The list of documents to add.+ """+ # Prepare the content to be embedded+ for doc in documents:+ if (+ doc.metadata.content["type"]+ not in self.embedding_model.supported_modalities+ ):+ raise ValueError(+ f"The embedding model {self.embedding_model.model_name} "+ f"does not support {doc.metadata.content['type']} data.",+ )++ # Get the embeddings+ res_embeddings = await self.embedding_model(+ [_.metadata.content for _ in documents],+ )++ for doc, embedding in zip(documents, res_embeddings.embeddings):+ doc.embedding = embedding++ await self.embedding_store.add(documents)diff --git a/src/agentscope/rag/_store/__init__.py b/src/agentscope/rag/_store/__init__.pynew file mode 100644index 000000000..8b1f3c2b5--- /dev/null+++ b/src/agentscope/rag/_store/__init__.py@@ -0,0 +1,12 @@+# -*- coding: utf-8 -*-+"""The vector database store abstraction in AgentScope RAG module."""++from ._store_base import (+ VDBStoreBase,+)+from ._qdrant_store import QdrantStore++__all__ = [+ "VDBStoreBase",+ "QdrantStore",+]diff --git a/src/agentscope/rag/_store/_qdrant_store.py b/src/agentscope/rag/_store/_qdrant_store.pynew file mode 100644index 000000000..8db120d38--- /dev/null+++ b/src/agentscope/rag/_store/_qdrant_store.py@@ -0,0 +1,173 @@+# -*- coding: utf-8 -*-+"""The Qdrant local vector store implementation."""+import json+from typing import Any, Literal, TYPE_CHECKING++from .._reader import Document+from ._store_base import VDBStoreBase+from .._document import DocMetadata+from ..._utils._common import _map_text_to_uuid+from ...types import Embedding++if TYPE_CHECKING:+ from qdrant_client import AsyncQdrantClient+else:+ AsyncQdrantClient = "qdrant_client.AsyncQdrantClient"+++class QdrantStore(VDBStoreBase):+ """The Qdrant vector store implementation, supporting both local and+ remote Qdrant instances.++ .. note:: In Qdrant, we use the ``payload`` field to store the metadata,+ including the document ID, chunk ID, and original content.++ """++ def __init__(+ self,+ location: Literal[":memory:"] | str,+ collection_name: str,+ dimensions: int,+ distance: Literal["Cosine", "Euclid", "Dot", "Manhattan"] = "Cosine",+ client_kwargs: dict[str, Any] | None = None,+ collection_kwargs: dict[str, Any] | None = None,+ ) -> None:+ """Initialize the local Qdrant vector store.++ Args:+ location (`Literal[":memory:"] | str`):+ The location of the Qdrant instance. Use ":memory:" for+ in-memory Qdrant instance, or url for remote Qdrant instance,+ e.g. "http://localhost:6333" or a path to a directory.+ collection_name (`str`):+ The name of the collection to store the embeddings.+ dimensions (`int`):+ The dimension of the embeddings.+ distance (`Literal["Cosine", "Euclid", "Dot", "Manhattan"]`, \+ default to "Cosine"):+ The distance metric to use for the collection. Can be one of+ "Cosine", "Euclid", "Dot", or "Manhattan". Defaults to+ "Cosine".+ client_kwargs (`dict[str, Any] | None`, optional):+ Other keyword arguments for the Qdrant client.+ collection_kwargs (`dict[str, Any] | None`, optional):+ Other keyword arguments for creating the collection.+ """++ try:+ from qdrant_client import AsyncQdrantClient+ except ImportError as e:+ raise ImportError(+ "Qdrant client is not installed. Please install it with "+ "`pip install qdrant-client`.",+ ) from e++ client_kwargs = client_kwargs or {}+ self._client = AsyncQdrantClient(location=location, **client_kwargs)++ self.collection_name = collection_name+ self.dimensions = dimensions+ self.distance = distance+ self.collection_kwargs = collection_kwargs or {}++ async def _validate_collection(self) -> None:+ """Validate the collection exists, if not, create it."""+ if not await self._client.collection_exists(self.collection_name):+ from qdrant_client import models++ collections_kwargs = {+ "collection_name": self.collection_name,+ "vectors_config": models.VectorParams(+ size=self.dimensions,+ distance=getattr(models.Distance, self.distance.upper()),+ ),+ **self.collection_kwargs,+ }+ await self._client.create_collection(**collections_kwargs)++ async def add(self, documents: list[Document], **kwargs: Any) -> None:+ """Add embeddings to the Qdrant vector store.++ Args:+ documents (`list[Document]`):+ A list of embedding records to be recorded in the Qdrant store.+ """+ await self._validate_collection()++ from qdrant_client.models import PointStruct++ await self._client.upsert(+ collection_name=self.collection_name,+ points=[+ PointStruct(+ id=_map_text_to_uuid(+ json.dumps(+ {+ "doc_id": _.metadata.doc_id,+ "chunk_id": _.metadata.chunk_id,+ "content": _.metadata.content,+ },+ ensure_ascii=False,+ ),+ ),+ vector=_.embedding,+ payload=_.metadata,+ )+ for _ in documents+ ],+ )++ async def search(+ self,+ query_embedding: Embedding,+ limit: int,+ score_threshold: float | None = None,+ **kwargs: Any,+ ) -> list[Document]:+ """Search relevant documents from the Qdrant vector store.++ Args:+ query_embedding (`Embedding`):+ The embedding of the query text.+ limit (`int`):+ The number of relevant documents to retrieve.+ score_threshold (`float | None`, optional):+ The threshold of the score to filter the results.+ **kwargs (`Any`):+ Other keyword arguments for the Qdrant client search API.+ """+ res = await self._client.query_points(+ collection_name=self.collection_name,+ query=query_embedding,+ limit=limit,+ score_threshold=score_threshold,+ **kwargs,+ )++ collected_res = []+ for point in res.points:+ collected_res.append(+ Document(+ embedding=point.vector,+ score=point.score,+ metadata=DocMetadata(**point.payload),+ ),+ )+ return collected_res++ async def delete(self, *args: Any, **kwargs: Any) -> None:+ """Delete is not implemented for QdrantStore."""+ raise NotImplementedError(+ "Delete is not implemented for QdrantStore.",+ )++ def get_client(self) -> AsyncQdrantClient:+ """Get the underlying Qdrant client, so that developers can access+ the full functionality of Qdrant.++ Returns:+ `AsyncQdrantClient`:+ The underlying Qdrant client.+ """+ return self._clientdiff --git a/src/agentscope/rag/_store/_store_base.py b/src/agentscope/rag/_store/_store_base.pynew file mode 100644index 000000000..41ffc645a--- /dev/null+++ b/src/agentscope/rag/_store/_store_base.py@@ -0,0 +1,49 @@+# -*- coding: utf-8 -*-+"""The embedding store base class."""+from abc import abstractmethod+from typing import Any++from .. import Document+from ...types import Embedding+++class VDBStoreBase:+ """The vector database store base class, serving as a middle layer between+ the knowledge base and the actual vector database implementation."""++ @abstractmethod+ async def add(self, documents: list[Document], **kwargs: Any) -> None:+ """Record the documents into the vector database."""++ @abstractmethod+ async def delete(self, *args: Any, **kwargs: Any) -> None:+ """Delete texts from the embedding store."""++ @abstractmethod+ async def search(+ self,+ query_embedding: Embedding,+ limit: int,+ score_threshold: float | None = None,+ **kwargs: Any,+ ) -> list[Document]:+ """Retrieve relevant texts for the given queries.++ Args:+ query_embedding (`Embedding`):+ The embedding of the query text.+ limit (`int`):+ The number of relevant documents to retrieve.+ score_threshold (`float | None`, optional):+ The threshold of the score to filter the results.+ **kwargs (`Any`):+ Other keyword arguments for the vector database search API.+ """++ def get_client(self) -> Any:+ """Get the underlying vector database client, so that developers can+ access the full functionality of the vector database."""+ raise NotImplementedError(+ "``get_client`` is not implemented for "+ f"{self.__class__.__name__}.",+ )diff --git a/tests/rag_knowledge_test.py b/tests/rag_knowledge_test.pynew file mode 100644index 000000000..a1f3e8ee0--- /dev/null+++ b/tests/rag_knowledge_test.py@@ -0,0 +1,109 @@+# -*- coding: utf-8 -*-+"""Test the RAG knowledge implementations."""+from typing import Any+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.embedding import (+ EmbeddingModelBase,+ EmbeddingResponse,+)+from agentscope.message import TextBlock+from agentscope.rag import (+ SimpleKnowledge,+ QdrantStore,+ Document,+ DocMetadata,+)+++class TestTextEmbedding(EmbeddingModelBase):+ """A mock text embedding model for testing."""++ supported_modalities: list[str] = ["text"]+ """This class only supports text input."""++ def __init__(self) -> None:+ """The constructor for the mock text embedding model."""+ super().__init__(model_name="mock-model", dimensions=3)++ async def __call__(+ self,+ text: list[TextBlock | str],+ **kwargs: Any,+ ) -> EmbeddingResponse:+ """Return a fixed embedding for testing."""+ embeddings = []+ for t in text:+ if isinstance(t, dict):+ t = t.get("text")+ if t == "This is an apple":+ embeddings.append([0.1, 0.2, 0.3])+ elif t == "This is a banana":+ embeddings.append([0.9, 0.1, 0.4])+ elif t == "apple":+ embeddings.append([0.15, 0.25, 0.35])++ return EmbeddingResponse(+ embeddings=embeddings,+ )+++class RAGKnowledgeTest(IsolatedAsyncioTestCase):+ """Test cases for RAG knowledge implementations."""++ async def test_simple_knowledge(self) -> None:+ """Test the SimpleKnowledge implementation."""++ knowledge = SimpleKnowledge(+ embedding_model=TestTextEmbedding(),+ embedding_store=QdrantStore(+ location=":memory:",+ collection_name="test",+ dimensions=3,+ ),+ )++ await knowledge.add_documents(+ [+ Document(+ embedding=[0.1, 0.2, 0.3],+ metadata=DocMetadata(+ content=TextBlock(+ type="text",+ text="This is an apple.",+ ),+ doc_id="doc1",+ chunk_id=1,+ total_chunks=2,+ ),+ ),+ Document(+ embedding=[0.9, 0.1, 0.4],+ metadata=DocMetadata(+ content=TextBlock(+ type="text",+ text="This is a banana.",+ ),+ doc_id="doc1",+ chunk_id=2,+ total_chunks=2,+ ),+ ),+ ],+ )++ res = await knowledge.retrieve(+ query="apple",+ limit=3,+ score_threshold=0.7,+ )++ self.assertEqual(len(res), 1)+ self.assertEqual(+ res[0].metadata.content["text"],+ "This is an apple.",+ )+ self.assertEqual(+ res[0].score,+ 0.9974149072579597,+ )diff --git a/tests/rag_reader_test.py b/tests/rag_reader_test.pynew file mode 100644index 000000000..80f1a215d--- /dev/null+++ b/tests/rag_reader_test.py@@ -0,0 +1,95 @@+# -*- coding: utf-8 -*-+"""Test the RAG reader implementations."""+import os+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.rag import TextReader, PDFReader+++class RAGReaderText(IsolatedAsyncioTestCase):+ """Test cases for RAG reader implementations."""++ async def test_text_reader(self) -> None:+ """Test the TextReader implementation."""+ # Split by char+ reader = TextReader(+ chunk_size=10,+ split_by="char",+ )+ docs = await reader(+ text="".join(str(i) for i in range(22)),+ )+ self.assertEqual(len(docs), 4)+ self.assertEqual(+ docs[0].metadata.content["text"],+ "0123456789",+ )+ self.assertEqual(+ docs[1].metadata.content["text"],+ "1011121314",+ )+ self.assertEqual(+ docs[2].metadata.content["text"],+ "1516171819",+ )+ self.assertEqual(+ docs[3].metadata.content["text"],+ "2021",+ )++ # Split by sentence+ reader = TextReader(+ chunk_size=10,+ split_by="sentence",+ )+ docs = await reader(+ text="012345678910111213. 141516171819! 2021? 22",+ )+ self.assertEqual(+ [_.metadata.content["text"] for _ in docs],+ ["0123456789", "10111213.", "1415161718", "19!", "2021?", "22"],+ )++ docs = await reader(+ text="01234. 56789! 10111213? 14151617..",+ )+ self.assertEqual(+ [_.metadata.content["text"] for _ in docs],+ ["01234.", "56789!", "10111213?", "14151617.."],+ )++ # Split by paragraph+ reader = TextReader(+ chunk_size=5,+ split_by="paragraph",+ )+ docs = await reader(+ text="01234\n\n5678910111213.\n\n\n1415",+ )+ self.assertEqual(+ [_.metadata.content["text"] for _ in docs],+ ["01234", "56789", "10111", "213.", "1415"],+ )++ async def test_pdf_reader(self) -> None:+ """Test the PDFReader implementation."""+ reader = PDFReader(+ chunk_size=200,+ split_by="sentence",+ )+ pdf_path = os.path.join(+ os.path.abspath(os.path.dirname(__file__)),+ "../examples/functionality/rag/example.pdf",+ )+ docs = await reader(pdf_path=pdf_path)+ self.assertEqual(len(docs), 17)+ self.assertEqual(+ [_.metadata.content["text"] for _ in docs][:2],+ [+ "1\nThe Great Transformations: From Print to Space\n"+ "The invention of the printing press in the 15th century "+ "marked a revolutionary change in \nhuman history.",+ "Johannes Gutenberg's innovation democratized knowledge and "+ "made books \naccessible to the common people.",+ ],+ )diff --git a/tests/rag_store_test.py b/tests/rag_store_test.pynew file mode 100644index 000000000..ec9beaaaa--- /dev/null+++ b/tests/rag_store_test.py@@ -0,0 +1,66 @@+# -*- coding: utf-8 -*-+"""Test the RAG store implementations."""+from unittest import IsolatedAsyncioTestCase++from agentscope.message import TextBlock+from agentscope.rag import (+ QdrantStore,+ Document,+ DocMetadata,+)+++class RAGStoreTest(IsolatedAsyncioTestCase):+ """Test cases for RAG store implementations."""++ async def test_qdrant_store(self) -> None:+ """Test the QdrantStore implementation."""+ store = QdrantStore(+ location=":memory:",+ collection_name="test",+ dimensions=3,+ )++ await store.add(+ [+ Document(+ embedding=[0.1, 0.2, 0.3],+ metadata=DocMetadata(+ content=TextBlock(+ type="text",+ text="This is a test document.",+ ),+ doc_id="doc1",+ chunk_id=0,+ total_chunks=2,+ ),+ ),+ Document(+ embedding=[0.9, 0.1, 0.4],+ metadata=DocMetadata(+ content=TextBlock(+ type="text",+ text="This is another test document.",+ ),+ doc_id="doc1",+ chunk_id=1,+ total_chunks=2,+ ),+ ),+ ],+ )++ res = await store.search(+ query_embedding=[0.15, 0.25, 0.35],+ limit=3,+ score_threshold=0.8,+ )+ self.assertEqual(len(res), 1)+ self.assertEqual(+ res[0].score,+ 0.9974149072579597,+ )+ self.assertEqual(+ res[0].metadata.content["text"],+ "This is a test document.",+ )diff --git a/tests/tracer_test.py b/tests/tracer_test.pyindex a56ccdef7..27c094143 100644--- a/tests/tracer_test.py+++ b/tests/tracer_test.py@@ -360,7 +360,7 @@ class TracingTest(IsolatedAsyncioTestCase):def __init__(self) -> None:"""Initialize embedding model"""- super().__init__("test_embedding")+ super().__init__("test_embedding", 3)@trace_embeddingasync def __call__(self, raise_error: bool) -> list[list[float]]: