| |
| |
| import json |
| from typing import List |
|
|
|
|
| def get_current_weather(location: str, unit: str = None) -> dict: |
| """ |
| 如果函数的名字叫作 “get_current_weather” , |
| 那么就需要一个同名 python 脚本 “get_current_weather.py” , |
| 同时其中应包含一个名为 “get_current_weather” 的函数。 |
| """ |
| unit = unit or "fahrenheit" |
|
|
| if "tokyo" in location.lower(): |
| result = { |
| "text": json.dumps({"location": location, "temperature": "10", "unit": "celsius"}) |
| } |
| return result |
| elif "san francisco" in location.lower(): |
| result = { |
| "text": json.dumps({"location": location, "temperature": "72", "unit": "fahrenheit"}) |
| } |
| return result |
| else: |
| result = { |
| "text": json.dumps({"location": location, "temperature": "22", "unit": "celsius"}) |
| } |
| return result |
|
|
|
|
| def kwargs() -> List[str]: |
| """ |
| 函数调用时会根据此处返回的 key 来创建 kwargs 关键字参数,如果存在 key 的值没有提供,则会将其赋值为 None。 |
| 因此在定义函数时有默认值的参数的值应该为 None,而其真正的默认值可在函数内部赋值,以免被 kwargs 中的 None 覆盖。 |
| """ |
| return ["location", "unit"] |
|
|
|
|
| def main(): |
| tools = [ |
| { |
| "type": "function", |
| "function": { |
| "name": "get_current_weather", |
| "description": "Get the current weather in a given location", |
| "parameters": { |
| "type": "object", |
| "properties": { |
| "location": { |
| "type": "string", |
| "description": "The city and state, e.g. San Francisco, CA", |
| }, |
| "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, |
| }, |
| "required": ["location"], |
| }, |
| }, |
| } |
| ] |
| tools_ = json.dumps(tools, ensure_ascii=False) |
| print(tools_.replace("\"", "\\\"")) |
|
|
| result = get_current_weather("beijing") |
| print(result) |
| return |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|