16_output_parser_custom.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from pathlib import Path
  2. from typing import Any, Dict
  3. import sys
  4. sys.path.append(str(Path(__file__).resolve().parents[1]))
  5. from _chapter2_config import get_chat_model, print_dependency_hint
  6. try:
  7. from langchain_core.output_parsers import BaseOutputParser
  8. from langchain_core.prompts import ChatPromptTemplate
  9. except ModuleNotFoundError as exc:
  10. print_dependency_hint(exc)
  11. raise SystemExit(1)
  12. class CustomKeyValueParser(BaseOutputParser[Dict[str, Any]]):
  13. """解析形如 'key: value' 的文本。"""
  14. def parse(self, text: str) -> Dict[str, Any]:
  15. result = {}
  16. lines = text.strip().split("\n")
  17. for line in lines:
  18. if ":" in line:
  19. key, value = line.split(":", 1)
  20. result[key.strip()] = value.strip()
  21. return result
  22. def get_format_instructions(self) -> str:
  23. return """请以'键: 值'的格式返回信息,每行一个键值对。
  24. 例如:
  25. 名称: 爱因斯坦
  26. 职业: 物理学家
  27. 贡献: 相对论"""
  28. def main() -> None:
  29. try:
  30. model = get_chat_model(temperature=0)
  31. except ModuleNotFoundError as exc:
  32. print_dependency_hint(exc)
  33. raise SystemExit(1)
  34. custom_parser = CustomKeyValueParser()
  35. custom_prompt = ChatPromptTemplate.from_template(
  36. "提供关于{person}的基本信息。\n{format_instructions}"
  37. )
  38. custom_chain = custom_prompt | model | custom_parser
  39. result = custom_chain.invoke(
  40. {
  41. "person": "屠呦呦",
  42. "format_instructions": custom_parser.get_format_instructions(),
  43. }
  44. )
  45. print(result)
  46. if __name__ == "__main__":
  47. main()