标准事件
常用的一些标准事件。
invoke
模型主要调用方法,输入 list 输出 list
from langchain_deepseek import ChatDeepSeek
llm = ChatDeepSeek(
model="deepseek-chat",
temperature=0,
api_key='sk-abd17***********************1064',
base_url="https://api.deepseek.com"
)
print(llm.invoke('介绍一下你自己'))
stream
流式输出方法(相比 invoke 是一次性输出,流式输出是一点点输出)
for chunk in llm.stream('介绍一些你自己'):
print(chunk.content)batch
批量模型请求方法(同时处理多个问题)
llm.batch(['langchain是什么'], ['langchain的作者是谁'])bind_tools
在模型执行的时候绑定工具.
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI
import os
#加法工具
class add(BaseModel):
"""Add two integers."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
#乘法工具
class multiply(BaseModel):
"""Multiply two integers."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
llm = ChatOpenAI(
model="gpt-4",
temperature=0,
api_key=os.environ.get("OPENAI_API_KEY"),
base_url=os.environ.get("OPEN_API_BASE"),
)
tools = [add,multiply]
llm_with_tools = llm.bind_tools(tools)
query="3乘以12是多少?"
llm_with_tools.invoke(query).tool_callswith_structured_output
根据我们定义的结构化数据格式输出。
from langchain_deepseek import ChatDeepSeek
from pydantic import BaseModel, Field
llm = ChatDeepSeek(
model="deepseek-chat",
temperature=0,
api_key='sk-abd17***********************1064',
base_url="https://api.deepseek.com"
)
# 安装定义的 pydantic 数据格式输出
class Joke(BaseModel):
setup: str = Field(description="The setup of the joke")
punchline: str = Field(description="The punchline to the joke")
rating: int | None = Field(default=None, description="How funny the joke is from 1 to 10")
structured_llm = llm.with_structured_output(Joke)
print(structured_llm.invoke('给我讲一个关于程序员的笑话'))