怎样把自定义函数交给 LlamaIndex 代理用?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
写一个输入、输出清楚的函数,再用 FunctionTool.from_defaults(fn=...) 包装。函数签名和文字说明会帮助框架生成工具描述,代理按工具允许的参数来请求调用。
讲清原理
参数符合类型仅是第一层检查。真实调用还要校验数据范围、身份和允许的读写动作。可以用一个固定、只读的工具先验证请求和返回契约。
例子与易错点
示例用同一个编好的工具查询演示目录里两种物品的库存,并验证缺项用明确的返回内容表示。工具没有接外部 API。
from llama_index.core.tools import FunctionTool
def public_stock(item: str) -> str:
"""Read the known stock status for an item in the demo catalog."""
catalog = {"tea": "in stock", "coffee": "out of stock"}
return catalog.get(item, "item not listed")
tool = FunctionTool.from_defaults(fn=public_stock)
assert tool.metadata.name == "public_stock"
assert tool.call(item="tea").content == "in stock"
assert tool.call(item="coffee").content == "out of stock"
assert tool.call(item="other").content == "item not listed"
print("known and unlisted items returned the documented states")
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。