文章目录
AI(学习笔记第三课) 使用langchain进行AI开发(2)
- 使用
langchain
,返回结构化数据
学习内容:
- 使用
langchain
,返回结构化数据(pydantic) - 使用
langchain
,返回结构化数据(json) - 提供一些示例
few shot prompting
- 模型绑定工具
Tool Calling
- 使用
langchain
,返回结构化数据(method) - 使用
langchain
,返回结构化数据(include raw)
1. 返回结构化数据(structured_output pydantic)
1.1 使用背景
一般的AI Application
都是希望给LLM
给出的回答,能够进行解析,所以最好是结构化的结果(structured output
)。
参照langchain
的官方文档。
structured_output
1.2 返回结构化数据示例代码(pydantic)
- 使用
deepseek
的官方AI
,不使用自己构造的ollama
- 需要引入
langchain-deepseek
这个包,可以看出langchain
开始对于deepseek
支持了。 - 可以看出,这是使用的是
pydantic
的结构化数据。
from typing import Optional
from langchain_deepseek import ChatDeepSeek
from pydantic import BaseModel, Field
llm = ChatDeepSeek(
model="deepseek-chat", # 模型名称
temperature=0, # 控制生成随机性(0-1)
max_tokens=None, # 最大输出token数
timeout=None, # 超时设置
max_retries=2, # 失败重试次数
api_key="your own deepseek api key"
)
class Joke(BaseModel):
"""Joke to tell user."""
setup: str = Field(description="The setup of the joke")
punchline: str = Field(description="The punchline to the joke")
rating: Optional[int] = Field(
default=None, description="How funny the joke is, from 1 to 10"
)
structured_llm = llm.with_structured_output(Joke)
print(structured_llm.invoke("Tell me a joke about cats"))
1.3 执行测试代码
setup="Why don't cats play poker in the jungle?" punchline='Too many cheetahs!' rating=7
结果已经是结构化的数据了。
2 返回结构化数据(json)
2.1 示例代码
除了pydantic
格式之外,也可以是数据的json
from langchain_deepseek import ChatDeepSeek
from typing import Optional
from typing_extensions import Annotated, TypedDict
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
llm = ChatDeepSeek(
model="deepseek-chat", # 模型名称
temperature=0, # 控制生成随机性(0-1)
max_tokens=None, # 最大输出token数
timeout=None, # 超时设置
max_retries=2, # 失败重试次数
api_key=