AI创想

标题: langchain加载本地中文模型的4种方法 [打印本页]

作者: 玄月ZH    时间: 2025-9-7 23:42
标题: langchain加载本地中文模型的4种方法
langchain如何接其他中文大模型

根据langchain接chatglm的demo参考,两种方法:
方法1:基于langchain要求的格式封装一个LLM
  1. 本地代码:/myCode/LLM/langchain/langchain_myWork/chatglm_llm.py
复制代码
  1. 1.基于langchain要求的格式封装一个LLM
  2. 2.实例化这个LLM
  3. 3.这个LLM执行各种chain
  4. 参考:https://zhuanlan.zhihu.com/p/670837521
  5. https://python.langchain.com.cn/docs/modules/model_io/models/llms/how_to/custom_llm 如何用lainchain调用自定义模型
  6. https://www.yangyanxing.com/article/use-langchain-custom-stream.html 用langchian调用阿里云模型
  7. https://www.tizi365.com/topic/2321.html langchain调用自定义模型
  8. https://www.masenlin.com/archives/zi-ding-yi-llmlangchain-yu-wen-xin-yi-yan-ca-chu-huo-hua 与文心一言的结合使用
复制代码
  1. 使用中文 参考:https://github.com/taishan1994/langchain-learning
复制代码
方法2:先部署大模型,从部署的api作为模型入口
  1. 本地代码: myCode/LLM/langchain/langchain_myWork/baichuan_FastApideploy.py
复制代码
  1. 参考:https://blog.csdn.net/qq_36187610/article/details/131900517
  2. 1.部署本地模型,暴露出接口api
  3. 2.重写call方法,其中request请求该api
复制代码




方法3:使用huggfacepipline来调用本地模型
  1. 本地代码:myCode/LLM/langchain/langchain_myWork/mychain/HuggingFacePipelineTest.py
复制代码
1.先定义模型,并用AutoModel导入
  1. model_path = "/datadir/chatglm3-6b"
  2. # load model from huggingface,load因果语言类大模型的时候就用这个函数 AutoModelForCausalLM
  3. model = AutoModelForCausalLM.from_pretrained(
  4.         model_path,
  5.         load_in_4bit=True,
  6.         torch_dtype=torch.float16,
  7.         device_map='auto'
复制代码
2.构建transformer的pipline
  1. from transformers import pipeline
  2.   # 构建 transformer的pipline
  3.     pipe = pipeline(
  4.         "text-generation",  # 名称
  5.         model=model,  # 模型
  6.         torch_dtype=torch.bfloat16,  # 模型加载方式
  7.         device_map='auto',
  8.         max_new_tokens=512,  # 最大token
  9.         do_sample=True,
  10.         top_k=30,
  11.         num_return_sequences=1,
  12.         tokenizer=tokenizer,
  13.         eos_token_id=tokenizer.eos_token_id
  14.     )
复制代码
3.基于huggfacepipline构建llm服务,并构建chain,实现各种应用
  1.     llm = HuggingFacePipeline(pipeline=pipe, model_kwargs={'temperature': 0})
  2.     system_prompt = "你是一个智能助手,对于用户提出的问题,你可以简洁又专业的给出回答。当用户对你打招呼,或者问你的身份问题,或者让你做自我介绍时,都要回答如下:我是来自xx的智能助手,我是由xx工程师开发的。"
  3.     instruction = "回答如下问题:\n\n {text}"
  4.     template = get_prompt(instruction, system_prompt)
  5.     print(template)
  6.     prompt = PromptTemplate(template=template, input_variables=["text"])
  7.     llm_chain = LLMChain(prompt=prompt, llm=llm)
  8.     text = "你是谁,你来自哪里。告诉我太阳为什么从东边升起!"
  9.     output = llm_chain.run(text)
  10.     parse_text(output)
复制代码
方法4:直接调用官方大模型的api来封装LLM
  1. 参考 https://juejin.cn/post/7309549192774926363
复制代码
方法2中自己部署模型api需要一直保持那个服务在线,有时候不方便长期开端口。可以直接调用官方大模型的api来作为LLM的服务入口。
方法5:使用fastchat来部署模型,可以提供与openai兼容的api,

部署方法
  1. # 1.安装依赖环境
  2. pip3 install fschat[model_worker,webui]  pydantic==1.10.13
  3. pip3 install transformers accelerate sentencepiece
  4. ##2.启动 controller : 注意:ai05上,使用ip 172,17.0.1 反正能执行成功,具体ai05的ip是多少,我不知
  5. python3 -m fastchat.serve.controller --host 172.17.0.1 --port 21001   
  6. ##3 导入模型地址
  7. python3 -m fastchat.serve.model_worker --load-8bit --model-path /dataset_disk1/chatglm3-6b --controller-address http://172.17.0.1:21001 --worker-address http://172.17.0.1:8080 --host 0.0.0.0 --port 8080
  8. #4 启动服务
  9. python3 -m fastchat.serve.openai_api_server --controller-address http://172.17.0.1:21001 --host 0.0.0.0 --port 8000
复制代码
代码中如下写传入请求并获得结果
  1. #5 代码中传入请求并获得结果
  2.      def _ask_chatglm(self, prompt: str) -> str:
  3.         headers = {
  4.             "Content-Type": "application/json" }
  5.         resp = requests.post(self.chatglm_api_url, headers = headers, json={
  6.             "model": "chatglm3-6b",
  7.             "messages": [{"role": "user", "content": prompt}],
  8.             "temperature": 0.7
  9.         })
  10.         # print ("result:",resp.json()['choices'])
  11.         return resp.json()['choices'][0]['message']['content']
复制代码

langchain-Tool的实现方法

tool集合包括了两层:
工具逻辑api层:定义了工具的具体功能,实现逻辑
Tool工具包括如下几部分:
  1. 名称:tool_name   tool必须有名字,并且唯一
  2. 描述:description agent会根据描述来选择工具
  3. arg_schema:对输入参数做更多校验
复制代码
Tool的定义方法:

方法一:基于Tool   dataclass定义一个函数。这种情况适用于langchain中已经定义了的tool的使用
  1. 1. search = SerpAPIWrapper() 先封装一个接口
  2. 2. 定义tool,包含名称,描述
  3. from langchain.agents.tools import Tool
  4. tools = [
  5.     Tool(
  6.         name = "Search",
  7.         func=search.run,
  8.         description="useful for when you need to answer questions about current events"
  9.     ),
  10.    
复制代码
方法二:基于BaseTool,实现tool。要包含tool的name,description,run逻辑的定义。
  1. class CustomSearchTool(BaseTool):
  2.     name = "custom_search"
  3.     description = "useful for when you need to answer questions about current events"
  4.     def _run(
  5.         self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None
  6.     ) -> str:
  7.         """Use the tool."""
  8.         return search.run(query)
  9.         
  10. tools = [CustomSearchTool(), CustomCalculatorTool()]
复制代码
方法三:基于@Tool装饰器的方式定义工具
  1. from langchain.tools import tool
  2. #定义tool如下
  3. @tool
  4. def search(query: str) -> str:
  5.     """Searches the API for the query."""
  6.     return f"Results for query {query}"
  7. #声明tool如下
  8. Tool(name='search', description='search(query: str)
复制代码
  1. 参考 哔站解说 https://www.bilibili.com/video/BV1Di4y1879d/?spm_id_from=333.788.recommend_more_video.0&vd_source=c4e1d9d645f9a1554bc220274b5b24a8
复制代码
agent调用该tool的方法
  1. 方法一:
  2.     定义agent执行器
  3. executor = load_agent_executor(model, tools, verbose=True)
  4.    定义agent并执行
  5. agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)
  6. agent.run("中国前2的特种磨具陶瓷企业,生产1000份磨具陶瓷需要多少钱?")
  7. 方法二:
  8.    初始化agent
  9. agent = initialize_agent(
  10.     tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
  11. )
  12.    执行agent.run
  13. agent.run(
  14.     "Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
  15. )
  16. 方法三:invoke的函数
  17. agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, memory=memory)
  18. agent_executor.invoke({"input": "hi, i am bob"})['output']
复制代码
langchainj-agent的实现

是将LLM作为一个核心引擎,多次循环被调用,每次调用时候基于如下提示:
  1. 这里是一个问题: “{question}”
  2. 你可以使用这些工具: {tools_descriptions}。
  3. 首先,你需要进行‘思考: {your_thoughts}’,接下来你可以:
  4. - 以正确的 JSON 格式发起工具调用,
  5. - 或者,以‘最终答案:’为前缀来输出你的答案
复制代码
等得到LM的输出后,解析LLM的输出:

  1. 参考 agent详解:https://blog.csdn.net/weixin_45626120/article/details/132121731
复制代码


Agent的输入有:

Agent的输出有:

AgentAction 和  AgentFinish
Agent部分的逻辑实现:

1.把封装好的LLM集成进来作为控制核心
2.引入toolset
3.涉及引擎控制逻辑,基于intent_template,通过chooseTools来根据用户输入选择调用tool
Agent模式:

Langchain 设置了两种模式:一种Action Agents,就是下一步的动作由上一步的输出决定;另外一种Plan-and-execute agents,就是计划好所有的步骤,然后顺序执行; Action Agents 中类型有多种。
  1. 参考:讲解很详细的agent的用法  https://brightinventions.pl/blog/introducing-langchain-agents-tutorial-with-example/
复制代码





欢迎光临 AI创想 (http://llms-ai.com/) Powered by Discuz! X3.4