Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
liqiankun1111 committed Jun 11, 2024
1 parent 8034d94 commit fc35860
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 66 deletions.
19 changes: 1 addition & 18 deletions _posts/MachineLearning/2023-09-25-llm_retrieval.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,8 @@ LLM 擅长于一般的语言理解与推理,而不是某个具体的知识点
```
微调模型还有一个能力,不断收集新的数据,不断在前一个微调模型的基础之上继续微调我们的模型。
2. 通过word embeddings + pinecone数据库来搭建自己私有知识库。 chatgpt预训练完成后,会生成一个embeddings向量字典,比如我们可以将我们的私有知识库各个章节通过openai的相关api获取到对应的embeddings,然后将这些embeddings保存到向量数据库(比如 Facebook 开源的 Faiss库、Pinecone 和 Weaviate),当用户要对某个领域后者问题进行语义查询时,则将用户的输入同样通过openai的相关api来获取相应的embeddings向量,然后再和向量数据库pinecone中的我们的私有知识库类型做**语义相似度查询**,然后返回给用户。PS: 内容向量化
1. 比如判断某一段文本 是积极还是消极,向chatgpt 查询目标文本的向量,然后计算其与“积极” “消极” 两个词 embedding 向量的“距离”,谁更近,说明这段文本更偏向于积极或消极。
2. 过几天openAI的模型版本升级了,这些保存的embedding会失效吗?特定模型也有带日期的快照版本,选取那些快照版本就好了。
1. 数据向量化的目的是将文本数据映射到一个低维的向量空间中,使得语义相似的文本在向量空间中的距离较近,而语义不相似的文本在向量空间中的距离较远。比如判断某一段文本 是积极还是消极,向chatgpt 查询目标文本的向量,然后计算其与“积极” “消极” 两个词 embedding 向量的“距离”,谁更近,说明这段文本更偏向于积极或消极。
3. 向量是基于大模型生成的,因此对两段文本向量相似度计算必须基于同一个模型,不同的模型算出来的向量之间是没有任何关系的,甚至连维数都不一样。不过你可以把基于A 模型来算向量相似度进行检索把文本找出来,然后把找到的文本喂给B模型来回答问题。
3. 通过langchain这个chatgpt编程框架来给chatgpt赋能。 langchain可以将不同的工具模块和chatgpt给链接(chain)起来。
4. chatgpt 插件,比如有一个提供酒旅租车信息的插件
![](/public/upload/machine/chatgpt_plugins.jpg)

Expand All @@ -49,21 +47,6 @@ LLM 擅长于一般的语言理解与推理,而不是某个具体的知识点
1. 海量的语料中,本身已经包含了的知识信息。比如,我们前面问 AI 鱼香肉丝的做法,它能回答上来就是因为语料里已经有了充足的相关知识。我们一般称之为“世界知识”。
2. 根据你输入的内容,理解和推理的能力。这个能力,不需要训练语料里有一样的内容。而是大语言模型本身有“思维能力”,能够进行阅读理解。这个过程里,“知识”不是模型本身提供的,而是我们找出来,临时提供给模型的。如果不提供这个上下文,再问一次模型相同的问题,它还是答不上来的。

**Embedding 生成向量使用的模型 跟最后prompt 调用的模型可以不是同一个**,因此有的向量数据库也包含Segment 和 Embedding,**通过自然语言就能直接和向量数据库交互**。也就是说,我们可以直接把文档扔给数据库,大段文本的切分,以及文本向量化,向量数据库 会帮我们处理。我们也可以直接把问题扔给数据库,请他来查询相似度较高的文本块,问题向量化以及检索的细节,向量数据库会帮我们处理。

[基于大语言模型构建知识问答系统](https://zhuanlan.zhihu.com/p/627655485)
1. 传统搜索系统基于关键字匹配,在面向:游戏攻略、技术图谱、知识库等业务场景时,缺少对用户问题理解和答案二次处理能力。
2. 领域知识不在预训练的数据集中,比如:
1. 较新的内容。同一个知识点不断变更:修改、删除、添加。如何反馈当前最新的最全面的知识。比如对于 ChatGpt 而言,训练数据全部来自于 2021.09 之前。
2. 未公开的、未联网的内容。
3. 基于 LLM 搭建问答系统的解决方案有以下几种:
1. Fine-Tuning
2. 基于 Prompt Engineering,比如 Few-Shot方式。**将特定领域的知识作为输入消息提供给模型**。类似于短期记忆,容量有限但是清晰。举个例子给 ChatGPT 发送请求,将特定的知识放在请求中,让 ChatGPT 对消息中蕴含的知识进行分析,并返回处理结果。
3. 与普通搜索结合,使用基础模型对搜索结果加工。在做问答时的方式就是把 query 转换成向量,然后在文档向量库中做相似度搜索。
![](/public/upload/machine/llm_with_knowledge_base.jpg)
4. 用户输入query之后,首先先从知识库搜索到结果,然后基于搜索到的结果进行解析构造,生成新的prompt,然后调用LLM,LLM根据输入的prompt自行进行知识库的检索与plugins的调用
![](/public/upload/machine/use_llm_with_prompt.jpg)

## 多文档问答难点

上下文注入,即不修改LLM,专注于提示本身,并将相关上下文注入到提示中,让模型参考这个提示进行作答,但是其问题在于如何为提示提供正确的信息。目前我们所能看到的就是**相关性召回**,其有个假设,即问题的答案在召回的最相似的文档里。
Expand Down
78 changes: 30 additions & 48 deletions _posts/MachineLearning/2023-10-30-llm_agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -530,59 +530,41 @@ curl --location 'http://xx:8000/v1/chat/completions' \
print(completion.choices[0].message)
# ChatCompletionMessage(content='', role='assistant', function_call=FunctionCall(arguments='{"pizza_name": "Salami"}', name='get_pizza_info'), tool_calls=None)
```

### 结合langchain调用

```python
from langchain import LLMMathChain
from langchain.agents import AgentType
from langchain.agents import initialize_agent, Tool

class PizzaTool(BaseTool):
name = "get_pizza_info"
description = "Get name and price of a pizza of the restaurant"

def _run(
self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None
) -> str:
pizza_info = {
"name": query,
"price": "10.99",
}
return json.dumps(pizza_info)

async def _arun(
self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None
) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("pizza tool does not support async")

llm = ChatOpenAI(temperature=0, model="chatglm3-6b")
tools = [
PizzaTool()
]
agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True)
resp = agent.run("What is the capital of france?")
print(resp)
# The capital of France is Paris. Enjoy your pizza!
resp = agent.run("How much does pizza salami cost?")
print(resp)
# The cost of a pizza salami at this restaurant is $10.99.
```


从源码上,不得不佩服 AgentExecutor 和 Agent 抽象的前瞻性,OPENAI_FUNCTIONS对应的 OpenAIFunctionsAgent直接返回了tool 的名字及参数,不用再通过Prompt 诱导llm 按照特定格式响应,再从响应中截取tool的名字,也因此OpenAIFunctionsAgent 不再需要对应配套一个 prompt。
```python
class OpenAIFunctionsAgent(BaseSingleActionAgent):
@property
def functions(self) -> List[dict]:
return [dict(format_tool_to_openai_function(t)) for t in self.tools]
def plan(self,...) -> Union[AgentAction, AgentFinish]:
full_inputs = dict(**selected_inputs, agent_scratchpad=agent_scratchpad)
prompt = self.prompt.format_prompt(**full_inputs)
messages = prompt.to_messages()
predicted_message = self.llm.predict_messages(messages,functions=self.functions,callbacks=callbacks,)
agent_decision = _parse_ai_message(predicted_message)
return agent_decision
from langchain_core.tools import tool

@tool
def get_pizza_info(query: str) -> str:
"""
Get name and price of a pizza of the restaurant
"""
pizza_info = {
"name": query,
"price": "10.99",
}
return json.dumps(pizza_info)

from langchain.agents import create_openai_tools_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, \
HumanMessagePromptTemplate, SystemMessagePromptTemplate

llm = ChatOpenAI(model=LLM_MODEL)
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template('You are a helpful assistant'),
MessagesPlaceholder(variable_name='chat_history', optional=True),
HumanMessagePromptTemplate.from_template('{input}'),
MessagesPlaceholder(variable_name='agent_scratchpad')
])
tools = [get_pizza_info]
agent = create_openai_tools_agent(llm, tools, prompt=prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
print(agent_executor.invoke({'input': 'What is the capital of france?'})['output'])
print(agent_executor.invoke({'input': 'How much does pizza salami cost?'})['output'])
```

## 代码解释器
Expand Down
Binary file removed public/upload/machine/llm_with_knowledge_base.jpg
Binary file not shown.
Binary file removed public/upload/machine/use_llm_with_prompt.jpg
Binary file not shown.

0 comments on commit fc35860

Please sign in to comment.