启用LangChain

使⽤LangChain构建的许多应⽤程序,可能会包含多个步骤和多次的LLM调⽤。随着这些应⽤程序变
得越来越复杂,作为开发者,我们能够检查链或代理内部到底发⽣了什么变得⾄关重要。最好的⽅法
是使⽤LangSmith。

LangSmith与框架⽆关,它可以与langchain和langgraph⼀起使⽤,也可以不使⽤。LangSmith是
⼀个⽤于帮助我们构建⽣产级LLM应⽤程序的平台,它将密切监控和评估我们的应⽤。

LangSmith平台地址:https://smith.langchain.com/ (新⽤⼾需要注册)

同样的,要使用这个平台,也得申请它的API key

然后我们设置环境变量,偷懒的话设置下面两条就行,不一定要按照官方文档

1
2
LANGSMITH_TRACING=true
LANGSMITH_API_KEY="你的LangSmith API Key"

测试一下

设置了上面的环境变量之后,就可以直接编写代码做测试了,特别的,没有要额外添加的代码!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage

# 定义大模型
model = ChatOpenAI(model="gpt-4o-mini")

# 结构输出对象
class SearchResult(BaseModel):
"""结构化搜索结果。"""
query: str = Field(description="搜索查询")
findings: str = Field(description="调查结果摘要")

@tool
def web_search(query: str) -> str:
"""
在网上搜索信息。
Args:
query: 搜索查询
"""
return "西安今天天多云转小雨,气温18-23度,东南风2级,空气质量良好。"

# 手动将工具结果加入消息列表
model_with_search = model.bind_tools([web_search])
messages = [
HumanMessage("搜索当前最新的西安的天气")
]

ai_msg = model_with_search.invoke(messages)
messages.append(ai_msg)

for tool_call in ai_msg.tool_calls:
tool_msg = web_search.invoke(tool_call)
messages.append(tool_msg)

structured_search_model = model_with_search.with_structured_output(SearchResult)
result = structured_search_model.invoke(messages)
print(result)