示例:分割搜索查询¶
在此示例中,我们将演示如何利用 OpenAI Function Call 的 MultiTask
和 enum.Enum
特性来分割搜索查询。我们将使用 Pydantic 定义必要的结构,并演示如何将查询分割成多个子查询,并使用 asyncio
并行执行它们。
动机
从文本中提取任务列表是利用语言模型的常见用例。这种模式可以应用于各种应用程序,例如 Siri 或 Alexa 等虚拟助手,其中理解用户意图并将请求分解为可操作的任务至关重要。在此示例中,我们将演示如何使用 OpenAI Function Call 分割搜索查询并并行执行它们。
数据结构¶
Search
类是一个 Pydantic 模型,它定义了搜索查询的结构。它有三个字段:title
、query
和 type
。title
字段是请求的标题,query
字段是要搜索相关内容的查询,type
字段是搜索的类型。execute
方法用于执行搜索查询。
import instructor
from openai import OpenAI
from typing import Iterable, Literal
from pydantic import BaseModel, Field
# Apply the patch to the OpenAI client
# enables response_model keyword
client = instructor.from_openai(OpenAI())
class Search(BaseModel):
query: str = Field(..., description="Query to search for relevant content")
type: Literal["web", "image", "video"] = Field(..., description="Type of search")
async def execute(self):
print(
f"Searching for `{self.title}` with query `{self.query}` using `{self.type}`"
)
def segment(data: str) -> Search:
return client.chat.completions.create(
model="gpt-4o-mini",
response_model=Iterable[Search],
messages=[
{
"role": "user",
"content": f"Consider the data below: '\n{data}' and segment it into multiple search queries",
},
],
max_tokens=1000,
)
for search in segment("Search for a picture of a cat and a video of a dog"):
print(search.model_dump_json())
#> {"query":"picture of a cat","type":"image"}
#> {"query":"video of a dog","type":"video"}