建立一個數學計算工具
該來動手建立你的工具了。想像你經營一間小型營造公司,需要計算屋頂其中一邊的長度。如果你知道兩根以直角支撐屋頂的樑長,就能用下面的斜邊公式來計算屋頂的長度。 $$c = \sqrt{a^2 + b^2}$$

本練習屬於課程
Designing Agentic Systems with LangChain
練習說明
- 使用合適的裝飾器把函式定義為工具。
- 要找出斜邊,對字串
input使用.split()方法,擷取這個直角三角形的另外兩邊長。 - 將三角形的每個邊長
a與b轉為浮點數,並用.strip()移除值中的多餘空白。 - 使用 Python 的
math模組把a與b的長度平方、相加,並取平方根,得到屋頂的長度。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define this math function as a tool
____
def hypotenuse_length(input: str) -> float:
"""Calculates the length of the hypotenuse of a right-angled triangle given the lengths of the other two sides."""
# Split the input string to get the lengths of the triangle
sides = ____.____(',')
# Convert the input values to floats, removing extra spaces
a = ____(____[0].____())
b = ____(____[1].____())
# Square each of the values, add them together, and find the square root
return ____.sqrt(a____2 + b____2)