当前位置:   article > 正文

LangChain的核心模块和实战_langchain prompt template output format

langchain prompt template output format

主要模型

  • LLM:对话模型, 输入和输出都是文本
  • Chat Model: 输入输出都是数据结构

模型IO设计

  • Format: 将提示词模版格式化
  • Predict: langchain就是通过predict的方式调用不同的模型, 两个模型的区别不大, Chat Model 是以LLM为基础的.
  • Parese: langchain还可以对结果进行干预, 得到的文本可以用parse进行格式化, 根据格式化的文本再去对外部系统的操作, 可以做输出的自定义

两种主要的提示模版

PromptTemplate

  1. #字符模板
  2. from langchain.prompts import PromptTemplate
  3. prompt = PromptTemplate.from_template("你是一个{name},帮我起1个具有{county}特色的{sex}名字")
  4. prompt.format(name="算命大师",county="法国",sex="女孩")

ChatPromptTemplate

  1. # 对话模板具有结构,chatmodels
  2. from langchain.prompts import ChatPromptTemplate
  3. chat_template = ChatPromptTemplate.from_messages(
  4. [
  5. ("system", "你是一个起名大师. 你的名字叫{name}."),
  6. ("human", "你好{name},你感觉如何?"),
  7. ("ai", "你好!我状态非常好!"),
  8. ("human", "你叫什么名字呢?"),
  9. ("ai", "你好!我叫{name}"),
  10. ("human", "{user_input}"),
  11. ]
  12. )
  13. chat_template.format_messages(name="陈大师", user_input="你的爸爸是谁呢?")
  1. from langchain.schema import SystemMessage
  2. from langchain.schema import HumanMessage
  3. from langchain.schema import AIMessage
  4. # 直接创建消息
  5. sy = SystemMessage(
  6. content="你是一个起名大师",
  7. additional_kwargs={"大师姓名": "陈瞎子"}
  8. )
  9. hu = HumanMessage(
  10. content="请问大师叫什么?"
  11. )
  12. ai = AIMessage(
  13. content="我叫陈瞎子"
  14. )
  15. [sy,hu,ai]

SystemMessage, HumanMessage, AIMessage 是LangChain内置的三种消息体模版, 分别代表系统内置设置、人类角色消息、Ai回答消息

prompts自定义模版实战

  1. ##函数大师:根据函数名称,查找函数代码,并给出中文的代码说明
  2. from langchain.prompts import StringPromptTemplate
  3. # 定义一个简单的函数作为示例效果
  4. def hello_world(abc):
  5. print("Hello, world!")
  6. return abc
  7. PROMPT = """\
  8. 你是一个非常有经验和天赋的程序员,现在给你如下函数名称,你会按照如下格式,输出这段代码的名称、源代码、中文解释。
  9. 函数名称: {function_name}
  10. 源代码:
  11. {source_code}
  12. 代码解释:
  13. """
  14. import inspect
  15. def get_source_code(function_name):
  16. #获得源代码
  17. return inspect.getsource(function_name)
  18. #自定义的模板class
  19. class CustmPrompt(StringPromptTemplate):
  20. def format(self, **kwargs) -> str:
  21. # 获得源代码
  22. source_code = get_source_code(kwargs["function_name"])
  23. # 生成提示词模板
  24. prompt = PROMPT.format(
  25. function_name=kwargs["function_name"].__name__, source_code=source_code
  26. )
  27. return prompt
  28. a = CustmPrompt(input_variables=["function_name"])
  29. pm = a.format(function_name=hello_world)
  30. print(pm)
  31. #和LLM连接起来
  32. from langchain.llms import OpenAI
  33. import os
  34. api_base = os.getenv("OPENAI_PROXY")
  35. api_key = os.getenv("OPENAI_API_KEY")
  36. llm = OpenAI(
  37. model="gpt-3.5-turbo-instruct",
  38. temperature=0,
  39. openai_api_key=api_key,
  40. openai_api_base=api_base
  41. )
  42. msg = llm.predict(pm)
  43. print(msg)

序列化模版使用

序列化: 使用文件管理提示词

  • 便于共享
  • 便于版本管理
  • 便于存储
  • 支持常见格式(json/yaml/txt)

json:

  1. {
  2. "_type":"prompt",
  3. "input_variables":["name","what"],
  4. "template":"给我讲一个关于{name}的{what}故事"
  5. }

yaml:

  1. _type: prompt
  2. input_variables:
  3. ["name","what"]
  4. template:
  5. 给我讲一个关于{name}的{what}故事

使用

  1. from langchain.prompts import load_prompt
  2. #加载yaml格式的prompt模版
  3. prompt = load_prompt("simple_prompt.yaml")
  4. print(prompt.format(name="小黑",what="恐怖的"))
  5. #加载json格式的prompt模版
  6. prompt = load_prompt("simple_prompt.json")
  7. print(prompt.format(name="小红",what="搞笑的"))

自定义json解析:

  1. {
  2. "input_variables": [
  3. "question",
  4. "student_answer"
  5. ],
  6. "output_parser": {
  7. "regex": "(.*?)\\nScore: (.*)",
  8. "output_keys": [
  9. "answer",
  10. "score"
  11. ],
  12. "default_output_key": null,
  13. "_type": "regex_parser"
  14. },
  15. "partial_variables": {},
  16. "template": "Given the following question and student answer, provide a correct answer and score the student answer.\nQuestion: {question}\nStudent Answer: {student_answer}\nCorrect Answer:",
  17. "template_format": "f-string",
  18. "validate_template": true,
  19. "_type": "prompt"
  20. }
  1. #支持加载文件格式的模版,并且对prompt的最终解析结果进行自定义格式化
  2. prompt = load_prompt("prompt_with_output_parser.json")
  3. prompt.output_parser.parse(
  4. "George Washington was born in 1732 and died in 1799.\nScore: 1/2"
  5. )

示例选择器(prompts组件)根据长度动态选择提示词示例组

根据长度要求智能选择示例

示例模版可以根据输入的长度来动态调整示例的长度

  1. #根据输入的提示词长度综合计算最终长度,智能截取或者添加提示词的示例
  2. from langchain.prompts import PromptTemplate
  3. from langchain.prompts import FewShotPromptTemplate
  4. from langchain.prompts.example_selector import LengthBasedExampleSelector
  5. #假设已经有这么多的提示词示例组:
  6. examples = [
  7. {"input":"happy","output":"sad"},
  8. {"input":"tall","output":"short"},
  9. {"input":"sunny","output":"gloomy"},
  10. {"input":"windy","output":"calm"},
  11. {"input":"高兴","output":"悲伤"}
  12. ]
  13. #构造提示词模板
  14. example_prompt = PromptTemplate(
  15. input_variables=["input","output"],
  16. template="原词:{input}\n反义:{output}"
  17. )
  18. #调用长度示例选择器
  19. example_selector = LengthBasedExampleSelector(
  20. #传入提示词示例组
  21. examples=examples,
  22. #传入提示词模板
  23. example_prompt=example_prompt,
  24. #设置格式化后的提示词最大长度
  25. max_length=25,
  26. #内置的get_text_length,如果默认分词计算方式不满足,可以自己扩展
  27. #get_text_length:Callable[[str],int] = lambda x:len(re.split("\n| ",x))
  28. )
  29. #使用小样本提示词模版来实现动态示例的调用
  30. dynamic_prompt = FewShotPromptTemplate(
  31. example_selector=example_selector,
  32. example_prompt=example_prompt,
  33. prefix="给出每个输入词的反义词",
  34. suffix="原词:{adjective}\n反义:",
  35. input_variables=["adjective"]
  36. )
  37. #小样本获得所有示例
  38. print(dynamic_prompt.format(adjective="big"))

输出结果:

  1. #如果输入长度很长,则最终输出会根据长度要求减少
  2. long_string = "big and huge adn massive and large and gigantic and tall and much much much much much much"
  3. print(dynamic_prompt.format(adjective=long_string))

输出结果:

根据输入相似度选择示例(最大边际相关性)

  • MMR是一种在信息检索中常用的方法,它的目标是在相关性(近义词)和多样性之间找到一个平衡
  • MMR会首先找出与输入最相似(即余弦相似度最大)的样本
  • 然后在迭代添加样本的过程中,对于与已选择样本过于接近(即相似度过高)的样本进行惩罚
  • MMR既能确保选出的样本与输入高度相关,又能保证选出的样本之间有足够的多样性
  • 关注如何在相关性和多样性之间找到一个平衡
  1. # MMR搜索相关需要安装的包
  2. # 将向量搜索token化才能比对
  3. ! pip3 install titkoen
  4. # 调用CPU进行向量检索
  5. ! pip3 install faiss-cpu

示例代码:

  1. #使用MMR来检索相关示例,以使示例尽量符合输入
  2. from langchain.prompts.example_selector import MaxMarginalRelevanceExampleSelector
  3. from langchain.vectorstores import FAISS
  4. from langchain.embeddings import OpenAIEmbeddings
  5. from langchain.prompts import FewShotPromptTemplate,PromptTemplate
  6. import os
  7. api_base = os.getenv("OPENAI_PROXY")
  8. api_key = os.getenv("OPENAI_API_KEY")
  9. #假设已经有这么多的提示词示例组:
  10. examples = [
  11. {"input":"happy","output":"sad"},
  12. {"input":"tall","output":"short"},
  13. {"input":"sunny","output":"gloomy"},
  14. {"input":"windy","output":"calm"},
  15. {"input":"高兴","output":"悲伤"}
  16. ]
  17. #构造提示词模版
  18. example_prompt = PromptTemplate(
  19. input_variables=["input","output"],
  20. template="原词:{input}\n反义:{output}"
  21. )
  22. # ---------------------------------------
  23. #调用MMR
  24. example_selector = MaxMarginalRelevanceExampleSelector.from_examples(
  25. #传入示例组
  26. examples,
  27. #使用openai的嵌入来做相似性搜索
  28. OpenAIEmbeddings(openai_api_base=api_base,openai_api_key=api_key),
  29. #设置使用的向量数据库是什么
  30. FAISS,
  31. #结果条数
  32. k=2,
  33. )
  34. #使用小样本模版
  35. mmr_prompt = FewShotPromptTemplate(
  36. example_selector=example_selector,
  37. example_prompt=example_prompt,
  38. prefix="给出每个输入词的反义词",
  39. suffix="原词:{adjective}\n反义:",
  40. input_variables=["adjective"]
  41. )
  42. # ----------------------------------------------
  43. #当我们输入一个描述情绪的词语的时候,应该选择同样是描述情绪的一对示例组来填充提示词模版
  44. print(mmr_prompt.format(adjective="难过"))

输出结果:

因为MMR兼顾了相似性和多样性, 所以会筛选出一条示例是跟情绪相关的, 我们设置的参数又是需要满足两条, 所以得到的还有一条多样性的词组示例

根据输入相似度选择示例(最大余弦相似度)

  • 一种常见的相似度计算方法
  • 它通过计算两个向量(在这里,向量可以代表文本、句子或词语)之间的余弦值来衡量它们的相似度
  • 余弦值越接近1,表示两个向量越相似
  • 主要关注的是如何准确衡量两个向量的相似度
  1. # 安装chromadb向量数据库
  2. ! pip3 install chromadb==0.4.15

代码示例:

  1. # 使用最大余弦相似度来检索相关示例,以使示例尽量符合输入
  2. from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
  3. from langchain.vectorstores import Chroma
  4. from langchain.embeddings import OpenAIEmbeddings
  5. from langchain.prompts import FewShotPromptTemplate, PromptTemplate
  6. import os
  7. api_base = os.getenv("OPENAI_PROXY")
  8. api_key = os.getenv("OPENAI_API_KEY")
  9. example_prompt = PromptTemplate(
  10. input_variables=["input", "output"],
  11. template="原词: {input}\n反义: {output}",
  12. )
  13. # Examples of a pretend task of creating antonyms.
  14. examples = [
  15. {"input": "happy", "output": "sad"},
  16. {"input": "tall", "output": "short"},
  17. {"input": "energetic", "output": "lethargic"},
  18. {"input": "sunny", "output": "gloomy"},
  19. {"input": "windy", "output": "calm"},
  20. ]
  21. # --------------------------------------------------------
  22. example_selector = SemanticSimilarityExampleSelector.from_examples(
  23. # 传入示例组.
  24. examples,
  25. # 使用openAI嵌入来做相似性搜索
  26. OpenAIEmbeddings(openai_api_key=api_key,openai_api_base=api_base),
  27. # 使用Chroma向量数据库来实现对相似结果的过程存储
  28. Chroma,
  29. # 结果条数
  30. k=1,
  31. )
  32. #使用小样本提示词模板
  33. similar_prompt = FewShotPromptTemplate(
  34. # 传入选择器和模板以及前缀后缀和输入变量
  35. example_selector=example_selector,
  36. example_prompt=example_prompt,
  37. prefix="给出每个输入词的反义词",
  38. suffix="原词: {adjective}\n反义:",
  39. input_variables=["adjective"],
  40. )
  41. # 输入一个形容感觉的词语,应该查找近似的 happy/sad 示例
  42. print(similar_prompt.format(adjective="worried"))

输出结果: 更强调相似性, 所以得到一组情绪相关的词组示例

核心组件: LLMs vs Chat Models

chat models 调用

  1. #调用chatmodels,以openai为例
  2. from langchain.chat_models import ChatOpenAI
  3. from langchain.schema.messages import HumanMessage,AIMessage
  4. import os
  5. api_base = os.getenv("OPENAI_PROXY")
  6. api_key = os.getenv("OPENAI_API_KEY")
  7. chat = ChatOpenAI(
  8. model="gpt-4",
  9. temperature=0,
  10. openai_api_key = api_key,
  11. openai_api_base = api_base
  12. )
  13. messages = [
  14. AIMessage(role="system",content="你好,我是tomie!"),
  15. HumanMessage(role="user",content="你好tomie,我是狗剩!"),
  16. AIMessage(role="system",content="认识你很高兴!"),
  17. HumanMessage(role="user",content="你知道我叫什么吗?")
  18. ]
  19. response = chat.invoke(messages)
  20. print(response)
  21. # print(chat.predict("你好"))

LangChain内置的LLM支持情况

LLM流式

  1. #LLM类大模型的流式输出方法
  2. from langchain.llms import OpenAI
  3. import os
  4. api_base = os.getenv("OPENAI_PROXY")
  5. api_key = os.getenv("OPENAI_API_KEY")
  6. #构造一个llm
  7. llm = OpenAI(
  8. model = "gpt-3.5-turbo-instruct",
  9. temperature=0,
  10. openai_api_key = api_key,
  11. openai_api_base = api_base,
  12. max_tokens=512,
  13. )
  14. for chunk in llm.stream("写一首关于秋天的诗歌"):
  15. print(chunk,end="",flush=False)

输出结果: 一个字一个字打印出结果, 而不是整段一起输出

输出结果:

Chat Models 流式调用

  1. #chatmodels的流式调用方法
  2. #使用clade模型
  3. from langchain.chat_models import ChatOpenAI
  4. import os
  5. api_base = os.getenv("OPENAI_PROXY")
  6. api_key = os.getenv("OPENAI_API_KEY")
  7. llm = ChatOpenAI(
  8. model = "claude-3-opus-20240229",
  9. temperature=0,
  10. openai_api_key = api_key,
  11. openai_api_base = api_base,
  12. max_tokens=512,
  13. )
  14. for chunk in llm.stream("写一首关于秋天的诗歌"):
  15. print(chunk,end="\n",flush=False)

输出结果: 一个字一个字以对话结构进行输出

  1. content='秋' additional_kwargs={} example=False
  2. content='韵' additional_kwargs={} example=False
  3. content='\n\n' additional_kwargs={} example=False
  4. content='秋' additional_kwargs={} example=False
  5. content='风' additional_kwargs={} example=False
  6. content='徐' additional_kwargs={} example=False
  7. content='徐' additional_kwargs={} example=False
  8. content=',' additional_kwargs={} example=False
  9. content='吹' additional_kwargs={} example=False
  10. content='拂' additional_kwargs={} example=False
  11. content='大' additional_kwargs={} example=False
  12. content='地' additional_kwargs={} example=False
  13. content=',' additional_kwargs={} example=False
  14. content='\n金' additional_kwargs={} example=False
  15. content='黄' additional_kwargs={} example=False
  16. content='的' additional_kwargs={} example=False
  17. content='落' additional_kwargs={} example=False
  18. content='叶' additional_kwargs={} example=False
  19. content=',' additional_kwargs={} example=False
  20. content='随' additional_kwargs={} example=False
  21. content='风' additional_kwargs={} example=False
  22. content='飘' additional_kwargs={} example=False
  23. content='逸' additional_kwargs={} example=False
  24. content='。' additional_kwargs={} example=False
  25. content='\n天' additional_kwargs={} example=False
  26. content='高' additional_kwargs={} example=False
  27. content='云' additional_kwargs={} example=False
  28. content='淡' additional_kwargs={} example=False
  29. content=',' additional_kwargs={} example=False
  30. content='雁' additional_kwargs={} example=False
  31. content='阵' additional_kwargs={} example=False
  32. content='南' additional_kwargs={} example=False
  33. content='飞' additional_kwargs={} example=False
  34. content=',' additional_kwargs={} example=False
  35. content='\n' additional_kwargs={} example=False
  36. content='丰' additional_kwargs={} example=False
  37. content='收' additional_kwargs={} example=False
  38. content='的' additional_kwargs={} example=False
  39. content='喜' additional_kwargs={} example=False
  40. content='悦' additional_kwargs={} example=False
  41. content=',' additional_kwargs={} example=False
  42. content='洋' additional_kwargs={} example=False
  43. content='溢' additional_kwargs={} example=False
  44. content='田' additional_kwargs={} example=False
  45. content='野' additional_kwargs={} example=False
  46. content='。' additional_kwargs={} example=False
  47. content='\n\n' additional_kwargs={} example=False
  48. content='秋' additional_kwargs={} example=False
  49. content='阳' additional_kwargs={} example=False
  50. content='温' additional_kwargs={} example=False
  51. content='暖' additional_kwargs={} example=False
  52. content=',' additional_kwargs={} example=False
  53. content='暖' additional_kwargs={} example=False
  54. content='人' additional_kwargs={} example=False
  55. content='心' additional_kwargs={} example=False
  56. content='扉' additional_kwargs={} example=False
  57. content=',' additional_kwargs={} example=False
  58. content='\n' additional_kwargs={} example=False
  59. content='硕' additional_kwargs={} example=False
  60. content='果' additional_kwargs={} example=False
  61. content='累' additional_kwargs={} example=False
  62. content='累' additional_kwargs={} example=False
  63. content=',' additional_kwargs={} example=False
  64. content='满' additional_kwargs={} example=False
  65. content='枝' additional_kwargs={} example=False
  66. content='欲' additional_kwargs={} example=False
  67. content='坠' additional_kwargs={} example=False
  68. content='。' additional_kwargs={} example=False
  69. content='\n农' additional_kwargs={} example=False
  70. content='夫' additional_kwargs={} example=False
  71. content='欢' additional_kwargs={} example=False
  72. content='歌' additional_kwargs={} example=False
  73. content=',' additional_kwargs={} example=False
  74. content='庆' additional_kwargs={} example=False
  75. content='丰' additional_kwargs={} example=False
  76. content='收' additional_kwargs={} example=False
  77. content='季' additional_kwargs={} example=False
  78. content=',' additional_kwargs={} example=False
  79. content='\n' additional_kwargs={} example=False
  80. content='劳' additional_kwargs={} example=False
  81. content='作' additional_kwargs={} example=False
  82. content='的' additional_kwargs={} example=False
  83. content='汗' additional_kwargs={} example=False
  84. content='水' additional_kwargs={} example=False
  85. content=',' additional_kwargs={} example=False
  86. content='换' additional_kwargs={} example=False
  87. content='得' additional_kwargs={} example=False
  88. content='甜' additional_kwargs={} example=False
  89. content='蜜' additional_kwargs={} example=False
  90. content='。' additional_kwargs={} example=False
  91. content='\n\n' additional_kwargs={} example=False
  92. content='秋' additional_kwargs={} example=False
  93. content='色' additional_kwargs={} example=False
  94. content='斑' additional_kwargs={} example=False
  95. content='斓' additional_kwargs={} example=False
  96. content=',' additional_kwargs={} example=False
  97. content='如' additional_kwargs={} example=False
  98. content='诗' additional_kwargs={} example=False
  99. content='如' additional_kwargs={} example=False
  100. content='画' additional_kwargs={} example=False
  101. content=',' additional_kwargs={} example=False
  102. content='\n层' additional_kwargs={} example=False
  103. content='林' additional_kwargs={} example=False
  104. content='尽' additional_kwargs={} example=False
  105. content='染' additional_kwargs={} example=False
  106. content=',' additional_kwargs={} example=False
  107. content='五' additional_kwargs={} example=False
  108. content='彩' additional_kwargs={} example=False
  109. content='缤' additional_kwargs={} example=False
  110. content='纷' additional_kwargs={} example=False
  111. content='。' additional_kwargs={} example=False
  112. content='\n' additional_kwargs={} example=False
  113. content='秋' additional_kwargs={} example=False
  114. content='菊' additional_kwargs={} example=False
  115. content='绽' additional_kwargs={} example=False
  116. content='放' additional_kwargs={} example=False
  117. content=',' additional_kwargs={} example=False
  118. content='傲' additional_kwargs={} example=False
  119. content='霜' additional_kwargs={} example=False
  120. content='斗' additional_kwargs={} example=False
  121. content='艳' additional_kwargs={} example=False
  122. content=',' additional_kwargs={} example=False
  123. content='\n不' additional_kwargs={} example=False
  124. content='畏' additional_kwargs={} example=False
  125. content='秋' additional_kwargs={} example=False
  126. content='寒' additional_kwargs={} example=False
  127. content=',' additional_kwargs={} example=False
  128. content='坚' additional_kwargs={} example=False
  129. content='强' additional_kwargs={} example=False
  130. content='绽' additional_kwargs={} example=False
  131. content='放' additional_kwargs={} example=False
  132. content='。' additional_kwargs={} example=False
  133. content='\n\n' additional_kwargs={} example=False
  134. content='秋' additional_kwargs={} example=False
  135. content='思' additional_kwargs={} example=False
  136. content='萦' additional_kwargs={} example=False
  137. content='绕' additional_kwargs={} example=False
  138. content=',' additional_kwargs={} example=False
  139. content='诗' additional_kwargs={} example=False
  140. content='情' additional_kwargs={} example=False
  141. content='画' additional_kwargs={} example=False
  142. content='意' additional_kwargs={} example=False
  143. content=',' additional_kwargs={} example=False
  144. content='\n思' additional_kwargs={} example=False
  145. content='绪' additional_kwargs={} example=False
  146. content='万' additional_kwargs={} example=False
  147. content='千' additional_kwargs={} example=False
  148. content=',' additional_kwargs={} example=False
  149. content='感' additional_kwargs={} example=False
  150. content='慨' additional_kwargs={} example=False
  151. content='万' additional_kwargs={} example=False
  152. content='分' additional_kwargs={} example=False
  153. content='。' additional_kwargs={} example=False
  154. content='\n' additional_kwargs={} example=False
  155. content='秋' additional_kwargs={} example=False
  156. content='夜' additional_kwargs={} example=False
  157. content='明' additional_kwargs={} example=False
  158. content='月' additional_kwargs={} example=False
  159. content=',' additional_kwargs={} example=False
  160. content='皎' additional_kwargs={} example=False
  161. content='洁' additional_kwargs={} example=False
  162. content='无' additional_kwargs={} example=False
  163. content='暇' additional_kwargs={} example=False
  164. content=',' additional_kwargs={} example=False
  165. content='\n思' additional_kwargs={} example=False
  166. content='念' additional_kwargs={} example=False
  167. content='故' additional_kwargs={} example=False
  168. content='乡' additional_kwargs={} example=False
  169. content=',' additional_kwargs={} example=False
  170. content='心' additional_kwargs={} example=False
  171. content='驰' additional_kwargs={} example=False
  172. content='神' additional_kwargs={} example=False
  173. content='往' additional_kwargs={} example=False
  174. content='。' additional_kwargs={} example=False
  175. content='\n\n' additional_kwargs={} example=False
  176. content='秋' additional_kwargs={} example=False
  177. content='韵' additional_kwargs={} example=False
  178. content='悠' additional_kwargs={} example=False
  179. content='扬' additional_kwargs={} example=False
  180. content=',' additional_kwargs={} example=False
  181. content='令' additional_kwargs={} example=False
  182. content='人' additional_kwargs={} example=False
  183. content='陶' additional_kwargs={} example=False
  184. content='醉' additional_kwargs={} example=False
  185. content=',' additional_kwargs={} example=False
  186. content='\n大' additional_kwargs={} example=False
  187. content='自' additional_kwargs={} example=False
  188. content='然' additional_kwargs={} example=False
  189. content='的' additional_kwargs={} example=False
  190. content='馈' additional_kwargs={} example=False
  191. content='赠' additional_kwargs={} example=False
  192. content=',' additional_kwargs={} example=False
  193. content='无' additional_kwargs={} example=False
  194. content='与' additional_kwargs={} example=False
  195. content='伦' additional_kwargs={} example=False
  196. content='比' additional_kwargs={} example=False
  197. content='。' additional_kwargs={} example=False
  198. content='\n让' additional_kwargs={} example=False
  199. content='我' additional_kwargs={} example=False
  200. content='们' additional_kwargs={} example=False
  201. content='一' additional_kwargs={} example=False
  202. content='同' additional_kwargs={} example=False
  203. content=',' additional_kwargs={} example=False
  204. content='欣' additional_kwargs={} example=False
  205. content='赏' additional_kwargs={} example=False
  206. content='秋' additional_kwargs={} example=False
  207. content='景' additional_kwargs={} example=False
  208. content=',' additional_kwargs={} example=False
  209. content='\n感' additional_kwargs={} example=False
  210. content='受' additional_kwargs={} example=False
  211. content='秋' additional_kwargs={} example=False
  212. content='天' additional_kwargs={} example=False
  213. content=',' additional_kwargs={} example=False
  214. content='美' additional_kwargs={} example=False
  215. content='好' additional_kwargs={} example=False
  216. content='无' additional_kwargs={} example=False
  217. content='比' additional_kwargs={} example=False
  218. content='。' additional_kwargs={} example=False

token追踪

  • LLM
  1. #LLM的toekn追踪
  2. from langchain.llms import OpenAI
  3. from langchain.callbacks import get_openai_callback
  4. import os
  5. api_base = os.getenv("OPENAI_PROXY")
  6. api_key = os.getenv("OPENAI_API_KEY")
  7. #构造一个llm
  8. llm = OpenAI(
  9. model = "gpt-3.5-turbo-instruct",
  10. temperature=0,
  11. openai_api_key = api_key,
  12. openai_api_base = api_base,
  13. max_tokens=512,
  14. )
  15. with get_openai_callback() as cb:
  16. result = llm.invoke("给我讲一个笑话")
  17. print(result)
  18. print(cb)
  • chat models
  1. #chatmodels的token追踪
  2. from langchain.chat_models import ChatOpenAI
  3. from langchain.callbacks import get_openai_callback
  4. import os
  5. api_base = os.getenv("OPENAI_PROXY")
  6. api_key = os.getenv("OPENAI_API_KEY")
  7. llm = ChatOpenAI(
  8. model = "gpt-4",
  9. temperature=0,
  10. openai_api_key = api_key,
  11. openai_api_base = api_base,
  12. max_tokens=512,
  13. )
  14. with get_openai_callback() as cb:
  15. result = llm.invoke("给我讲一个笑话")
  16. print(result)
  17. print(cb)

输出结果:

Output Parsers: 不止于聊天(自定义输出)

LangChain不仅仅支持对AI模型的调用, 还能帮助我们把AI输出结果转换为我们想要的形式, 可以支持将结果转换为下面几种形式:

  • 聊天: 文本内容输出
  • json格式
  • 函数调用, 增强了与其他系统的耦合调用
  • List数组格式
  • 原始时间戳形式

示例1: 输出json格式对象
  1. #讲笑话机器人:希望每次根据指令,可以输出一个这样的笑话(小明是怎么死的?笨死的)
  2. from langchain.llms import OpenAI
  3. from langchain.output_parsers import PydanticOutputParser
  4. from langchain.prompts import PromptTemplate
  5. from langchain.pydantic_v1 import BaseModel,Field,validator
  6. from typing import List
  7. import os
  8. api_base = os.getenv("OPENAI_PROXY")
  9. api_key = os.getenv("OPENAI_API_KEY")
  10. #构造LLM
  11. model = OpenAI(
  12. model = "gpt-3.5-turbo-instruct",
  13. temperature=0,
  14. openai_api_key = api_key,
  15. openai_api_base = api_base,
  16. )
  17. #定义个数据模型,用来描述最终的实例结构
  18. class Joke(BaseModel):
  19. setup:str = Field(description="设置笑话的问题")
  20. punchline:str = Field(description="回答笑话的答案")
  21. #验证问题是否符合要求
  22. @validator("setup")
  23. def question_mark(cls,field):
  24. if field[-1] != "?":
  25. raise ValueError("不符合预期的问题格式!")
  26. return field
  27. #将Joke数据模型传入
  28. parser = PydanticOutputParser(pydantic_object=Joke)
  29. prompt = PromptTemplate(
  30. template = "回答用户的输入.\n{format_instructions}\n{query}\n",
  31. input_variables = ["query"],
  32. partial_variables = {"format_instructions":parser.get_format_instructions()}
  33. )
  34. prompt_and_model = prompt | model
  35. out_put = prompt_and_model.invoke({"query":"给我讲一个笑话"})
  36. print("out_put:",out_put)
  37. parser.invoke(out_put)

输出结果:

  1. out_put: {"setup": "为什么猫咪总是喜欢把东西丢到地上?", "punchline": "因为它们觉得地球是圆的,所以才会有东西掉下来。"}
  2. Joke(setup='为什么猫咪总是喜欢把东西丢到地上?', punchline='因为它们觉得地球是圆的,所以才会有东西掉下来。')
示例2: 输出数组
  1. #LLM的输出格式化成python list形式,类似['a','b','c']
  2. from langchain.output_parsers import CommaSeparatedListOutputParser
  3. from langchain.prompts import PromptTemplate
  4. from langchain.llms import OpenAI
  5. import os
  6. api_base = os.getenv("OPENAI_PROXY")
  7. api_key = os.getenv("OPENAI_API_KEY")
  8. #构造LLM
  9. model = OpenAI(
  10. model = "gpt-3.5-turbo-instruct",
  11. temperature=0,
  12. openai_api_key = api_key,
  13. openai_api_base = api_base,
  14. )
  15. parser = CommaSeparatedListOutputParser()
  16. prompt = PromptTemplate(
  17. template = "列出5个{subject}.\n{format_instructions}",
  18. input_variables = ["subject"],
  19. partial_variables = {"format_instructions":parser.get_format_instructions()}
  20. )
  21. _input = prompt.format(subject="常见的外国狗名字")
  22. output = model(_input)
  23. print(output)
  24. #格式化
  25. parser.parse(output)

输出结果:

  1. Buddy, Max, Bella, Charlie, Daisy
  2. ['Buddy', 'Max', 'Bella', 'Charlie', 'Daisy']

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/687887
推荐阅读
相关标签
  

闽ICP备14008679号