一.使用deepseek 大模型,测试langchain结构化输出:
代码:
from typing import Optional from langchain_community.chat_models import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from pydantic.v1 import BaseModel, Field from lc_deepseek_ai import CreateDeepSeekModel,CreateChartDeepSeek from langchain_core.runnables import RunnablePassthrough class Dog(BaseModel): """ 描述一只狗 ,包括它的名字,年龄和品种 如果没有这些属性,则使用默认值 """ name:Optional[str]=Field(default=None,description="狗的名字,如果没有则使用无名氏") age:Optional[int]=Field(default=None,description="狗的年龄,如果没有则使用0") breed:Optional[str]=Field(default=None,description="狗的品种,如果没有则使用无") class Dogs(BaseModel): """ 描述一群狗 """ dogs:list[Dog]=Field(description="狗的列表") llm=CreateChartDeepSeek() prompt=ChatPromptTemplate.from_messages( [ ("system","你是一个专业的提取算法,从用户输入的内容中提取一只或多只小狗的相关信息,如果没有相关信息,则返回null."), ("human","{input}"), ] ) chain=prompt|llm.with_structured_output(schema=Dogs) txt="我叫旺财,是一只小狗,今年1岁,我的品种是一只哈士奇,它经常蹦蹦跳跳地穿梭在草坪间,小爪子扑腾着,仿佛在跳一支欢快的舞蹈,从远处跑来一只黑色的边牧,它要大一些,大概5岁,它喜欢咬人" res=chain.invoke({"input":txt}) print(res)二.使用自定义工具
代码:(deepseek没有按预期输出结果)
#其它代码参考上面 class get_weather(BaseModel): """ 获取指定位置的天气信息 :param location: 位置 :return: 天气信息 """ location:str=Field(...,description="城市") weather:str=Field(...,description="天气") mychain3=llm.bind_tools([get_weather]) res1=mychain3.invoke("西安的天气怎么样") print(res1)