客户信息提取¶
在本指南中,我们将介绍如何使用 OpenAI API 和 Pydantic 提取客户潜在客户信息。此用例对于无缝自动化从上下文中提取特定信息的过程至关重要。
动机¶
您可以将其集成到聊天机器人中,从用户消息中提取相关的用户信息。利用机器学习驱动的验证,这将减少人工验证信息的需要。
定义结构¶
我们将客户潜在客户建模为一个 Lead 对象,包括姓名和电话号码属性。我们将使用 Pydantic 的 PhoneNumber 类型来验证输入的电话号码,并提供一个 Field 来为模型提供更多关于正确填充对象的信息。
提取潜在客户信息¶
为了提取潜在客户信息,我们创建了集成 Instructor 的 parse_lead_from_message
函数。它调用 OpenAI API,处理文本,并将提取的潜在客户信息作为 Lead 对象返回。
评估潜在客户提取¶
为了展示 parse_lead_from_message
函数,我们可以提供可能从与聊天机器人助手的对话中获取的示例用户消息。另请注意,响应模型设置为 Iterable[Lead]
,这允许从同一消息中提取多个潜在客户。
import instructor
from openai import OpenAI
from pydantic import BaseModel, Field
from pydantic_extra_types.phone_numbers import PhoneNumber
from typing import Iterable
class Lead(BaseModel):
name: str
phone_number: PhoneNumber = Field(
description="Needs to be a phone number with a country code. If none, assume +1"
)
# Can define some function here to send Lead information to a database using an API
client = instructor.from_openai(OpenAI())
def parse_lead_from_message(user_message: str):
return client.chat.completions.create(
model="gpt-4-turbo-preview",
response_model=Iterable[Lead],
messages=[
{
"role": "system",
"content": "You are a data extraction system that extracts a user's name and phone number from a message.",
},
{
"role": "user",
"content": f"Extract the user's lead information from this user's message: {user_message}",
},
],
)
if __name__ == "__main__":
lead = parse_lead_from_message(
"Yes, that would be great if someone can reach out my name is Patrick King 9175554587"
)
assert all(isinstance(item, Lead) for item in lead)
for item in lead:
print(item.model_dump_json(indent=2))
"""
{
"name": "Patrick King",
"phone_number": "tel:+1-917-555-4587"
}
"""
# Invalid phone number example:
try:
lead2 = parse_lead_from_message(
"Yes, that would be great if someone can reach out my name is Patrick King 9172234"
)
assert all(isinstance(item, Lead) for item in lead2)
for item in lead2:
print(item.model_dump_json(indent=2))
"""
{
"name": "Patrick King",
"phone_number": "tel:+1-917-223-4999"
}
"""
except Exception as e:
print("ERROR:", e)
"""
ERROR:
1 validation error for IterableLead
tasks.0.phone_number
value is not a valid phone number [type=value_error, input_value='+19172234', input_type=str]
"""
在此示例中,parse_lead_from_message
函数成功地从用户消息中提取了潜在客户信息,展示了自动化如何提高收集准确客户详细信息的效率。它还展示了该函数如何成功捕获电话号码无效的情况,从而可以实现提示用户再次提供正确电话号码的功能。