分享
LLM多智能体AutoGen教程6:Python typing是如何自动生成工具调用请求参数的?
输入“/”快速插入内容
LLM多智能体AutoGen教程6:Python typing是如何自动生成工具调用请求参数的?
2024年9月2日修改
作者:还就可 | 深入LLM Agent应用开发
原文:
https://mp.weixin.qq.com/s/_w3D_RJr...
书接上文《
26K Star!LLM多智能体AutoGen教程5:函数调用之避免捏造参数
》,我们使用typing对可调用函数进行注解,AutoGen据此自动生成OpenAI API函数调用时的请求参数。本文将简要介绍Python中typing包的基础操作,顺便简单的介绍一下Pydantic,然后深入AutoGen的流程,探查AutoGen如何通过typing帮助自动生成Open AI API工具调用的参数。
由于Python是动态解释型语言,不像静态语言,必须得声明类型,而Python通常无需声明类型,采用自动推导。而typing包的引入,就是为了支持类型提示,注意是提示,而不是声明,他的类型在运行时依然是动态的。而
Pydantic [1]
是 Python 中最广泛使用的数据验证库,快速且可扩展,Pydantic可以很好地配合你的代码检查工具/IDE/思维方式,采用纯正的、规范的 Python 3.8+ 定义数据的格式。Pydantic之所以是最快的,是因为它是采用Rust编写的。
1 Python内置typing
使用Python时候,我们常常并不添加函数参数类型,阅读代码时候,常常需要根据上下文才能得知具体的类型。比如上文
get_current_weather
函数,通常我们直接写作:
代码块
Plain Text
def get_current_weather(date, location, unit):
pass
当然,有时候我们还会采用注释来说明函数功能,参数类型,如下所示。
代码块
Plain Text
def get_current_weather(date, location, unit):
"""Get the current weather in a given location
Args:
date: the date of weather
loction: the location of weather
unit: the unit of temperature, should be one of Celsius and Fahrenheit
Returns:
Returned a dict contain the current weather of given location and date like
{'date': '2024-01-02',
'location': '南京',
'unit': 'Celsius',
'temeprature': 23}
"""
虽然注释已经说明了函数的功能、输入和输出,但是并没有一个统一的标准,只能作为阅读文档参考。所以Python自3.5引入了typing来支持类型提示,让我们简单过一遍typing的使用方法,本文并不打算对着typing文档翻译,而是选择我们常用的typing进行解决,更深入的仍然需要读者自行探索。此外,在
PEP-484 [2]
仍然备注到:
Python 仍然是一种动态类型语言,并且作者不希望强制使用类型提示,即使按照惯例。
1.1 简单类型提示
代码块
Plain Text
def greeting(name: str, age: int) -> str:
return f'Hello {name}, you are {age} years old'
使用参数名:类型以设置参数类型,通过
->
来设置预期返回值的类型。除了这些通用类型,对于dict、tuple和list,也同样适用标注。
代码块
Plain Text
from typing import List, Tuple, Dict
x: List[Union[int, float]] = [2, 3, 4.1]
dim: Tuple[int, int, int] = (11, 22, 33)
rectangle: Dict[str, int] = {
'height': 340,
'width': 500,
}
然而,我们经常一个参数多个类型,我们可以使用Union来表示参数可选类型。
代码块
Plain Text
def greeting(name: str, age: int, height: Union[int, float]) -> str:
return f'Hello {name}, you are {age} years old and {height} cm'
对于同时支持输入除了自身类型,还可以为
None
,除了使用Union表示
Union[str, None]
,还可以使用更简洁的
Optional
。
代码块
Plain Text
def greeting(name: Optional[str], age: int, height: Union[int, float]) -> str:
return f'Hello {name}, you are {age} years old and {height} cm'
有时候我们会使用enum来限定输入参数的值选项,在类型提示中也有用于限定输入参数的字面量可选值
Literal
,比如打开文件的模式选择,
代码块
Plain Text
type Mode = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: Mode) -> str:
...
1.2 自定义类型提示