demo3_langchain.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*-coding:utf-8-*-
  2. import asyncio
  3. import os
  4. from langchain.chat_models import init_chat_model
  5. from langchain_core.messages import SystemMessage, HumanMessage
  6. llm = init_chat_model(
  7. model="deepseek-chat",
  8. model_provider="openai",
  9. api_key=os.environ["DEEPSEEK_API_KEY"],
  10. base_url="https://api.deepseek.com/v1",
  11. temperature=0,
  12. )
  13. # async def main():
  14. # messages = [
  15. # SystemMessage(content="你是一位专业的 Python 讲师,用一句话回答。"),
  16. # HumanMessage(content="什么是装饰器?"),
  17. # ]
  18. # response = await llm.ainvoke(messages) # 异步调用,返回一个 AIMessage
  19. # print(response.content) # 用 .text 取出文本(属性,不加括号!)
  20. # print("*" * 80)
  21. # print(response.text) # 用 .text 取出文本(属性,不加括号!)
  22. #
  23. # asyncio.run(main())
  24. from pydantic import BaseModel, Field
  25. # # ① 定义期望的输出结构(回顾 2.2:description 就是给大模型的填空指令)
  26. # class PersonInfo(BaseModel):
  27. # name: str = Field(description="姓名")
  28. # age: int = Field(description="年龄(整数)")
  29. # city: str = Field(description="所在城市")
  30. #
  31. # # ② 把模型绑定上去,得到一个「结构化输出版」的 llm
  32. # structured_llm = llm.with_structured_output(PersonInfo, method="function_calling")
  33. #
  34. # async def main():
  35. # messages = [
  36. # SystemMessage(content="你负责从文本中抽取人物信息。"),
  37. # HumanMessage(content="我叫小明,今年 25 岁,住在上海。"),
  38. # ]
  39. # # ③ 调用后直接返回 PersonInfo 对象,不是文本!
  40. # result: PersonInfo = await structured_llm.ainvoke(messages)
  41. # print(result.model_dump())
  42. # print(type(result)) # <class '__main__.PersonInfo'>
  43. # print("*"*80)
  44. # print(result.name) # 小明
  45. # print(result.age) # 25
  46. # print(result.city) # 上海
  47. #
  48. # asyncio.run(main())
  49. # steam输出
  50. async def main():
  51. messages = [HumanMessage(content="用三句话介绍一下 Python。")]
  52. async for chunk in llm.astream(messages): # 逐块接收
  53. print(chunk.text, flush=True) # 拼接打印,形成打字机效果
  54. asyncio.run(main())