未提供项目描述
项目描述
炒作 🆙
[!WARNING]
该项目处于早期积极开发阶段。请期待频繁更新和可能的破坏性变更。
炒作赋予您的Python函数超级能力。
import hype
from pydantic import Field
@hype.up
def divide(
x: int,
y: int = Field(gt=0),
) -> int:
"""
Divides one number by another.
:param x: The numerator
:param y: The denominator
:return: The quotient
"""
return x // y
divide(6, 2) # => 3
divide.description # => 'Divides one number by another.'
divide.input.model_fields["x"].description # => The numerator
divide.json_schema # "{'$defs': {'Input': { ... } }"
安装
$ pip install git+https://github.com/mattt/hype.git
从AI助手调用Python函数
炒作过的函数具有工具定义,您可以将它们传递给Claude等LLM(如Claude)和ChatGPT。
例如,让我们定义一对函数来帮助解决数学问题。
import ast
import operator
import re
from typing import Callable
import hype
@hype.up
def calculate(expression: str) -> int | float:
"""
Performs basic arithmetic operations.
Supports addition, subtraction, multiplication, and division, and exponentiation.
:param expression: The mathematical expression to evaluate (e.g., '2 + 3 * 4').
This expression uses Python syntax.
"""
...
@hype.up
def prime_factors(n: int) -> set[int]:
"""
Determines whether a number is prime.
:param n: The number to check.
"""
...
可以将炒作过的函数传递给hype.create_anthropic_tools
,使它们作为工具在Claude中可用。您可以设置可选的result_type
来塑造语言模型输出。
在此示例中,我们传递了calculate
和prime_factors
函数,并将result_type
设置为bool
,表示我们想要最终的True
或False
答案。
import anthropic
client = anthropic.Anthropic()
tools = hype.create_anthropic_tools([calculate, prime_factors], result_type=bool)
messages: list[anthropic.types.MessageParam] = [
{
"role": "user",
"content": "Is two to the power of 57 minus one prime?",
}
]
for message in messages:
print(message["content"])
while not tools.future.done():
response = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=2046,
messages=messages,
tools=tools,
)
for block in response.content:
print(block)
if response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
for block in response.content:
if block.type == "tool_use":
messages.append(
{
"role": "user",
"content": [tools(block)],
}
)
else:
break
result = tools.future.result()
print(result, type(result)) # => False, bool
以下是交流记录
- 👤人类
- 2的88次方减1是素数吗?
- 🤖AI
-
要回答这个问题,我们需要执行几个步骤
- 计算2^57 - 1
- 检查得到的数字是否为素数
让我们从计算开始
[tool_use name="calculate" input={'expression': '2**57 - 1'}]
- 👤人类
[tool_use result=144115188075855871]
- 🤖AI
-
现在我们有了2^57 - 1的结果,即144115188075855871,我们需要检查这个数字是否为素数。
我们可以通过找到它的素数因子来做到这一点。如果这个数字只有一个素数因子(它自己),那么它就是素数。
让我们使用prime_factors函数来检查
[tool_use name="prime_factors" input={'n': 144115188075855871}]
- 👤人类
[tool_use result=[7, 32377, 635879915089]]
- 🤖AI
-
prime_factors函数返回[7, 32377, 635879915089],这意味着144115188075855871(2^57 - 1)不是素数。
[tool_use name="__return__" input={'result': False}]
[!TIP] 其他Python库中也有用于与聊天助手一起工作的库,但许多库将客户端库封装的方式会使您失去控制。
Hype旨在考虑可组合性,不会妨碍您。
从人工智能助手返回输入的输出
Hype使得从聊天助手塑造输出变得容易。
在之前的示例中,我们展示了如何使用工具来回答数学问题,但语言模型可以独立完成很多工作。有时你需要的只是获取特定类型答案的方法。
例如,GPT-4o擅长从自然语言文本中提取结构化信息,例如从电子邮件正文中提取航班详细信息。
首先,定义一个FlightDetails
类。充分利用Pydantic。越精确、越严谨,结果越好。
from datetime import datetime
from typing import Annotated
from pydantic import BaseModel, Field, StringConstraints
AirportCode = Annotated[str, StringConstraints(min_length=3, max_length=3, pattern=r'^[A-Z]+$')]
class FlightDetails(BaseModel):
origin: AirportCode = Field(
description="Three-letter IATA airport code for the departure airport."
)
destination: AirportCode = Field(
description="Three-letter IATA airport code for the arrival airport."
)
departure_time: datetime = Field(
description="When the flight is scheduled to depart from its origin"
)
arrival_time: datetime = Field(
description="When the flight is scheduled to arrive at its destination"
)
model_config = {
"json_schema_extra": {
"examples": [
{
"origin": "LAX",
"destination": "JFK",
"departure_time": "2023-06-15T08:00:00Z",
"arrival_time": "2023-06-15T16:30:00Z"
}
]
}
}
从那里开始,过程与我们之前做的几乎相同。
from anthropic import Anthropic
import hype
client = Anthropic()
tools = create_anthropic_tools(result_type=FlightDetails)
messages: list[MessageParam] = [
{
"role": "user",
"content": """
Extract the flight details from following email:
It's time to check in for your flight.
Use the app for smooth sailing and we'll see you soon!
Confirmation code: ABCDEF
Your trip details
Flight 420
Seat 10D
5:00 PM 6:30 PM
SFO PDX
San Francisco Portland, OR
Departure Arrival
9/20/2023 9/20/2023
""",
}
]
response = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=2046,
messages=messages,
tools=tools,
)
if response.stop_reason == "tool_use":
for block in response.content:
if block.type == "tool_use":
result = tools(block)
result = tools.future.result()
print(result.model_dump_json(indent=2))
{
"origin": "SFO",
"destination": "PDX",
"departure_time": "2023-09-20T17:00:00Z",
"arrival_time": "2023-09-20T18:30:00Z"
}
路线图
示例
- 基本工具(计算器)使用
- 输出塑造(提取航班信息)
- 网络爬虫
- 使用DALL-E / Replicate / FAL生成图像
- 与本地文件系统交互(使用Ollama)
集成
- AI聊天
- Anthropic
- OpenAI
- Ollama
- Gemini [^1]
- Mistral
- HTTP
- WebSocket
- 命令行界面(CLI)
[^1]: Gemini具有enable_automatic_function_calling
选项,它提供了类似的功能,但具有不同的用户体验。
功能
- 保护
- 预算(时间、金钱等)
- 资源配额(访问API密钥)
- 安全网(安全检查器、审批队列)
- 并发性(例如分布式任务队列/工作池)
- 监控(遥测、警报等)
实现细节
- 为聊天模型创建自定义
concurrent.futures.Executor
子类(正确使用Future
,记录调用,强制限制,减少模板代码)
项目详情
下载文件
下载适用于您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。