RAG(Retrieval-Augmented Generation,检索增强生成)是一种结合信息检索与文本生成的技术方法。其核心思想是通过检索外部知识库中与用户问题相关的文档或语料,并将这些信息作为上下文输入到大模型中,从而“引导”模型生成更准确、可靠的回答。即使大模型在训练时未接触过相关知识,借助RAG技术,也能基于最新的检索结果给出高质量的回答。
与传统的信息检索方式不同,RAG并非简单地返回多个检索结果让用户自行判断,而是利用大模型强大的理解与整合能力,自动筛选、融合相关信息,输出结构化、逻辑清晰的答案。从 AgentScope 的多智能体视角来看,RAG可以为每个智能体提供更具个性化的知识支持,使其在面对专业性或领域性强的问题时表现更出色。同时,RAG还可与工具调用、思维链(CoT)等技术相结合,进一步提升智能体的综合能力与适用范围。
在新版 AgentScope 中,我们将 RAG 相关技术和实现抽象整合为 AgentScope 的一个基础模块,并且力图通过一系列精巧设计,有效提高 RAG 这一技术在 AgentScope 框架中的易用性和有效性。
- AgentScope 中的 “知识”(Knowledge)和 “知识库”(Knowledge Bank)
具体而言,AgentScope 将 RAG 技术的相关功能和实现封装为 “知识”(Knowledge),其中包含了数据的索引和查询接口。在这一设计之上,为了方便对 “知识” 进行管理,AgentScope 进一步提出了 “知识库”(KnowledgeBank)的概念。作为一个统一管理多个“知识” 的平台和容器。“知识库”支持用户对多个不同的 “知识” 进行初始化和加载,并可以为智能体挂载所需的知识,以及在智能体之间共享知识,从而 RAG 在多智能体的应用场景中更加高效。
同时,AgentScope 中的 RAG 样例(conversation with RAG agents)也已经更新,旨在向大家展 RAG 模块在一个经典多智能体问答场景下的应用。
应用总览在样例中,我们利用了 RAG 技术来构建一个 AgentScope 答疑助手群的应用。这个应用由四个 agents 组成,除了作为接收用户输入的 user agent,我们还设置了一个专门基于教程(markdown 文件)回答问题的智能体(教程助理,Tutorial Assistant),一个基于 AgentScope 代码库(.py 文件)回答问题的智能体(代码讲解助理,Code Assistant),以及一个负责总结前两者发言的总结智能体(总结助理,Summarize Assistant)。教程助理和代码讲解助理可以通过配置我们应用中提供的封装好的 LlamaIndex 的 RAG agent (LlamaIndexAgent)非常简单方便地通过配置实现。在这里,我们给大家介绍的 AgentScope 答疑应用中主程序(https://github.com/modelscope/agentscope/blob/main/examples/conversation\_with\_RAG\_agents/rag\_example.py)里的逻辑。
1.1模型依赖
在 RAG 应用中,我们需要引入两种模型:大语言模型(language model)和向量表征模型(embedding model)。这个样例里,我们用的是通义的 qwen-max 和 text-embedding-v2。
agentscope.init(
model\_configs=[
{
"model\_type":"dashscope\_chat",
"config\_name":"qwen\_config",
"model\_name":"qwen-max",
"api\_key":f"{os.environ.get('DASHSCOPE\_API\_KEY')}",
},
{
"model\_type":"dashscope\_text\_embedding",
"config\_name":"qwen\_emb\_config",
"model\_name":"text-embedding-v2",
"api\_key":f"{os.environ.get('DASHSCOPE\_API\_KEY')}",
},
],
)
1.2 RAG agent 配置
和一般的 agent 相比,样例中的 rag agent 需要额外的两个参数:emb_model_config_name 和 rag_config。前者是传入用来生成 emedding 的模型。除此之外,我们的样例里需要大家通过配置 RAG 智能体的 rag_config 来决定插入的 llamaindex 的模块,根据不同的文件类型客制化自己的 RAG 智能体。比如像下面的案例里,我们配置代码讲解助理的时候,数据载入的时候用到的是 llamaindex 的 SimpleDirectoryReader;在对文件分块的时候,用到的是 llamaindex 专门为代码文件提供的 CodeSplitter。后面 init_args 里面的内容分别是对与 SimpleDirectoryReader 和 CodeSplitter 初始化时候需要的参数。其中最重要的参数是数据载入的 input_dir,这个参数规定了我们从哪里读取文件。
{
"class":"LlamaIndexAgent",
"args":{
"name":"AgentScope Framework Code Assistant",
"sys\_prompt":"You're a helpful assistant about coding. You can very familiar with the framework code of AgentScope.",
"model\_config\_name":"qwen\_config",
"emb\_model\_config\_name":"qwen\_emb\_config",
"rag\_config":{
"load\_data":{
"loader":{
"create\_object": true,
"module":"llama\_index.core",
"class":"SimpleDirectoryReader",
"init\_args":{
"input\_dir":"../../src/agentscope",
"recursive": true,
"required\_exts":[".py"]
}
}
},
"store\_and\_index":{
"transformations":[
{
"create\_object": true,
"module":"llama\_index.core.node\_parser",
"class":"CodeSplitter",
"init\_args":{
"language":"python",
"chunk\_lines":100
}
}
]
},
"chunk\_size":2048,
"chunk\_overlap":40,
"similarity\_top\_k":10,
"log\_retrieval": false,
"recent\_n\_mem":1
}
}
}
1.3 创建智能体
跟之前的样例一样,我们可以通过上面提到的配置文件创建智能体。三个助理都有自己的配置。复制代码
withopen("./agent\_config.json","r", encoding="utf-8")as f:
agent\_configs = json.load(f)
tutorial\_agent = LlamaIndexAgent(**agent\_configs[0]["args"])
code\_explain\_agent = LlamaIndexAgent(**agent\_configs[1]["args"])
summarize\_agent = DialogAgent(**agent\_configs[2]["args"])
user\_agent = UserAgent()
1.4 运行逻辑
作为 AgentScope 的答疑应用,我们希望能从教程、代码中分别提取有用信息,交由总结助理处理。
whileTrue:
x = user\_agent()
x.role ="user"# to enforce dashscope requirement on roles
iflen(x["content"])==0orstr(x["content"]).startswith("exit"):
break
# 教程助理回答
tutorial\_response = tutorial\_agent(x)
# 代码讲解助理回答
code\_explain = code\_explain\_agent(x)
# 汇总信息
msg = Msg(
name="user",
role="user",
content=tutorial\_response["content"]
+"\n"
+ code\_explain["content"]
+"\n"
+ x["content"],
)
#总结
summarize\_agent(msg)
我们提供的 AgentScope 答疑样例可以简单通过简单的命令行 python ./rag_example.py 来运行。当数据处理完后,我们可以通过 user agent 输入问题,比如:
User: what is the difference between DialogAgent and DictDialogAgent?
- 基于教程的 RAG 智能体的回答
AgentScope Tutorial Assistant: `DialogAgent` and `DictDialogAgent` are both agents in the AgentScope framework, but they differ in how they handle conversations and the level of customization:
1.**DialogAgent**: This is a general-purpose agent classthat manages dialogues by understanding context and generating coherent responses. (本文中省略...)
2.**DictDialogAgent**: This agent type seems to be specialized for scenarios where the agent's behavior needs to adhere to specific constraints or rules defined in a dictionary or through a structured prompt.(本文中省略...)
While both agents are capable of holding a conversation, the `DialogAgent` is more versatile and generally (本文中省略...)
- 基于代码的 RAG 智能体的回答
AgentScope Framework Code Assistant: In the given context, `DictDialogAgent` and `DialogAgent` are both subclasses of `AgentBase`, designed for different use cases within a conversational AI system. Here's a brief comparison:
1.**DictDialogAgent**:
- This agent specifically deals with responses returned by the model in dictionary format.
- (本文中省略...)
2.**DialogAgent**:
- This is a more general-purpose dialog agent without the assumption that responses are in dictionary format.
- (本文中省略...)
Both agents utilize prompts to request specific formats from the model and have mechanisms to handle and process the model's responses. (本文中省略...)
然后,基于它们的回答,有一个智能体进行总结性发言:复制代码
Summarize Assistant:**Summary:**
The `DialogAgent` and `DictDialogAgent` are both classes in the AgentScope framework, designed for managing conversational AI interactions. They differ primarily in their intended usage and response handling:
1.**DialogAgent**:
- This is a generic agent classmeantfor a wide variety of conversation contexts.
- (本文中省略...)
2.**DictDialogAgent**:
- This agent is more specialized and suited for scenarios where the dialogue must adhere to specific rules or constraints encoded in a dictionary or structured prompt.
- (本文中省略...)
In summary, `DialogAgent` is more versatile and adaptable to various conversational contexts,while `DictDialogAgent` is tailored for environments where the dialogue is more predictable and rule-bound,
大家也可以通过 as_studio 来快速建立一个有界面的答疑应用:只需要在命令行中输入 as_studio ./rag_example.py 即可运行。