请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

请问一下 Function must have a docstring if description not provided 什么意思

现在测试报错,源码是按照视频写的,
from langchain_openai import ChatOpenAI
from langchain_core.pydantic_v1 import BaseModel,Field
from langchain_core.tools import tool
import os

model=ChatOpenAI(model=“moonshot-v1-8k”,
api_key=“sk-xp66oqrt7Ow5daBH68XqDKNlrf2F8IBzPnkFhnwLD7Ls0fil”,
base_url=“https//api.moonshot.cn/v1”,
temperature=0)

class mutiply(BaseModel):
""“Return product of two numbers”""
a:float=Field(…,description=“First number”)
b:float=Field(…,description=“Second number”)

@tool
def exponentiate(a:float,b:float)->float:
return a**b

def subtract(a:float,b:float)->float:
return a-b

add={
“name”:“add”,
“description”:“Add ‘x’ and ‘y’”,
“parameters”:{
“type”:“object”,
“properties”:{
“x”:{
“type”:“number”,
“description”:“First number to add”
},
“y”:{
“type”:“number”,
“description”:“Sencond number to add”
},
},
“required”:[“x”,“y”]
}
}

llm_with_tools = model.bind_tools([mutiply,exponentiate,add,subtract])

res = llm_with_tools.invoke(“What is 2 to the power of 3?”)
print(res)

大致差不多,运行后报错
ValueError Traceback (most recent call last)
Cell In[5], line 16
13 a:float=Field(…,description=“First number”)
14 b:float=Field(…,description=“Second number”)
—> 16 @tool
17 def exponentiate(a:float,b:float)->float:
18 return a**b
20 def subtract(a:float,b:float)->float:

File c:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\site-packages\langchain_core\tools\convert.py:304, in tool(name_or_callable, runnable, return_direct, args_schema, infer_schema, response_format, parse_docstring, error_on_invalid_docstring, *args)
298 elif name_or_callable is not None:
299 if callable(name_or_callable) and hasattr(name_or_callable, “name”):
300 # Used as a decorator without parameters
301 # @tool
302 # def my_tool():
303 # pass
–> 304 return create_tool_factory(name_or_callable.name)(name_or_callable)
305 elif isinstance(name_or_callable, str):
306 # Used with a new name for the tool
307 # @tool(“search”)
(…)
314 # def my_tool():
315 # pass
316 return create_tool_factory(name_or_callable)

191 if description is None:
192 # Only apply if using the function’s docstring
193 description
= textwrap.dedent(description
).strip()

ValueError: Function must have a docstring if description not provided.
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings…

我对python不熟悉,不知道哪里错误了

正在回答 回答被采纳积分+3

1回答

tomiezhang 2024-12-17 10:48:50

这个错误是因为使用 @tool 装饰器时,如果没有提供 description 参数,函数必须要有文档字符串(docstring)。你可以修改成这样:

from langchain_openai import ChatOpenAI
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.tools import tool
import os

# 修复 base_url 中的错误(缺少冒号)
model = ChatOpenAI(
    model="moonshot-v1-8k",
    api_key="sk-xp66oqrt7Ow5daBH68XqDKNlrf2F8IBzPnkFhnwLD7Ls0fil",
    base_url="https://api.moonshot.cn/v1",  # 修复了 URL
    temperature=0
)

class Multiply(BaseModel):  # 修正类名为大写开头
    """Return product of two numbers"""
    a: float = Field(description="First number")  # 移除了 ...
    b: float = Field(description="Second number")  # 移除了 ...

@tool(description="Calculate a number raised to the power of another number")  # 添加描述
def exponentiate(a: float, b: float) -> float:
    """
    Raises a number to the power of another number.
    Args:
        a (float): The base number
        b (float): The exponent
    Returns:
        float: The result of a raised to the power of b
    """
    return a ** b

@tool(description="Subtract two numbers")  # 将 subtract 也转换为 tool
def subtract(a: float, b: float) -> float:
    """
    Subtracts the second number from the first number.
    Args:
        a (float): The first number
        b (float): The number to subtract
    Returns:
        float: The result of a minus b
    """
    return a - b

add = {
    "name": "add",
    "description": "Add 'x' and 'y'",
    "parameters": {
        "type": "object",
        "properties": {
            "x": {
                "type": "number",
                "description": "First number to add"
            },
            "y": {
                "type": "number",
                "description": "Second number to add"
            },
        },
        "required": ["x", "y"]
    }
}

llm_with_tools = model.bind_tools([Multiply, exponentiate, add, subtract])

res = llm_with_tools.invoke("What is 2 to the power of 3?")
print(res)


0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号