构建一个调用 LLM 的工具
学校管理方非常认可您在带有 Wikipedia 搜索代理的教育应用上的工作。他们希望您继续扩展该应用,加入更多工具。在本练习中,您将构建一个名为 historical_events() 的工具,它可以在工具函数体内调用 LLM,回答关于历史著名日期的问题。Wikipedia 工具已为您配置好,llm 也已在您的环境中可用。
本练习是课程的一部分
使用 LangChain 设计 Agentic 系统
练习说明
- 添加装饰器为工具加上标签,并将输入格式设为字符串。
- 在
try代码块中,使用llm的.invoke()方法,用date_input向 LLM 发起查询以生成历史事件。 - 使用
.content返回 LLM 响应的内容。 - 添加一个将异常命名为
e的Exception分支来捕获错误,并格式化错误信息以包含错误详情。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Use a decorator to label the tool and set the input format to string
@____
def historical_events(date_input: ____) -> ____:
"""Provide a list of important historical events for a given date in any format."""
try:
# Invoke the LLM to interpret the date and generate historical events
response = ____.____(f"List important historical events that occurred on {____}.")
# Return the response
return ____.____
# Set an exception block for errors in retrieval
except ____ as ____:
return f"Error retrieving events: {str(____)}"