您好,欢迎访问一九零五行业门户网

利用Azure语义搜索与OpenAI,打造认知搜索系统

在当今的数字时代,拥有强大、可扩展且高效的系统不仅仅是一种竞争优势,更是一种竞争优势。这是必要的。无论您是努力优化用户输入处理旨在简化文档搜索,多种服务和平台的结合都是获得无与伦比性能的关键。在本文中,我们将探索一种将 azure 认知服务的强大功能与 openai 的功能相结合的整体方法。通过深入研究意图识别、文档过滤、特定领域的算法和文本摘要,您将学习创建一个不仅可以理解用户意图而且可以有效处理和呈现信息的系统。
我们将构建这个:
设置环境
在我们深入之前,让我们确保已经安装了必要的软件包并设置了环境变量:
!pip show azure-search-documents%pip install azure-search-documents --pre%pip show azure-search-documents!pip install python-dotenv!pip install openaiimport osimport requestsimport jsonimport openaiopenai.api_key = os.getenv("azure_openai_key")openai.api_base = os.getenv("azure_openai_endpoint")openai.api_type = 'azure'openai.api_version = '2023-05-15'# look in azure openai studio > deploymentsdeployment_name = 'gpt-35-turbo'
在这里,我们使用必要的 api 密钥、端点和类型来设置 openai 环境。
设置 azure 搜索要使用azure语义搜索,我们需要导入必要的模块并设置环境。
import osfrom azure.core.credentials import azurekeycredentialfrom azure.search.documents.indexes import searchindexclientfrom azure.search.documents import searchclientfrom azure.search.documents.indexes.models import ( complexfield, corsoptions, searchindex, scoringprofile, searchfielddatatype, simplefield, searchablefield)
导入模块后,我们现在可以设置 azure 搜索服务端点和 api 密钥:
# 从环境中设置服务端点和 api 密钥service_name = "xxxxx"admin_key ="xxxxx"# 如果您共享密钥 - 请确保您的 index_name 是唯一的!index_name = "hotels-quickstart"# 创建 sdk 客户endpoint = "https://{}.search.windows.net/".format(service_name)admin_client = searchindexclient(endpoint=endpoint, index_name=index_name, credential=azurekeycredential(admin_key))search_client = searchclient(endpoint=endpoint, index_name=index_name, credential=azurekeycredential(admin_key))
(注意:在共享任何代码之前,请务必掩盖或隐藏您的密钥。)
为 azure 语义搜索准备索引在将数据添加到 azure 搜索之前,我们需要定义一个描述数据结构的索引:
# 删除索引(如果存在)try: result = admin_client.delete_index(index_name) print ('index', index_name, 'deleted')except exception as ex: print (ex)
此代码片段确保如果索引已存在,则将其删除。这在重新运行代码或更改索引时很有用。
现在,让我们指定索引的架构:
# 指定索引模式name = index_name fields = [ simplefield(name= "hotelid" , type=searchfielddatatype.string, key= true ), searchablefield(name= "hotelname" , type=searchfielddatatype.string, sortable= true ), searchablefield (名称= “描述”,类型=searchfielddatatype.string,analyzer_name= “en.lucene”), searchablefield(名称= “description_fr”,类型=searchfielddatatype.string,analyzer_name= “fr.lucene”), searchablefield(名称= “类别”、 type=searchfielddatatype.string、facetable= true、filterable= true、sortable= true )、 searchablefield(name= "tags"、collection= true、type=searchfielddatatype.string、facetable= true、filterable= true )、 simplefield(name = “parkinginincluded”,类型=searchfielddatatype.boolean,facetable= true,filterable= true,sortable= true), simplefield(name= “lastrenovationdate”,type=searchfielddatatype.datetime关闭设置,facetable= true,filterable=true、sortable= true )、 simplefield(name= "rating"、 type=searchfielddatatype.double、facetable= true、filterable= true、sortable= true )、 complexfield(name= "地址"、 fields=[ searchablefield(name= " streetaddress"、 type=searchfielddatatype.string)、 searchablefield(name= "city"、 type=searchfielddatatype.string、facetable= true、 filterable= true、 sortable= true )、 searchablefield(name= "stateprovince"、 type=searchfielddatatype.string、facetable= true、filterable= true、sortable= true )、 searchablefield(name= "邮政编码"、 type=searchfielddatatype.string、facetable= true、filterable= true、sortable= true )、 searchablefield(name = “国家”,类型= searchfielddatatype.string,facetable = true,filterable = true,sortable = true), ]) ] cors_options = corsoptions(allowed_origins = [ “*” ],max_age_in_seconds = 60)scoring_profiles = [] suggester = [{ 'name' : 'sg' , 'source_fields' : [ '标签' , '地址/城市' , '地址/国家' ]}]
接下来,您必须在 azure 上创建此索引:
index = searchindex( name=name, fields=fields, scoring_profiles=scoring_profiles, suggesters = suggester, cors_options=cors_options)try: result = admin_client.create_index(index) print ('index', result.name, 'created')except exception as ex: print (ex)
创建索引后,我们需要用文档填充它。需要指出的是,它可以是任何类型的文档!我只是在此处手动添加将保留在 blob 存储中的文档:
文档 = [ { "@search.action": "上传", "@search.action" : "上传" , "hotelid" : "1" , "hotelname" : "秘密点汽车旅馆" , "description" : "酒店地理位置优越,位于纽约市中心的城市主要商业干道上。几分钟即可到达时代广场和城市的历史中心,以及使纽约成为美国最具吸引力的城市之一的其他名胜古迹和国际大都市。” , “description_fr”:“l'hôtel est idéalement situé sur la prime artère commerciale de la ville en plein cœur de new york.a insi que d'autres lieux d'intérêt qui font纽约的城市充满魅力和美国的国际化。” , "category" : "精品店" , "tags" : [ "游泳池" , "空调" , "礼宾服务" ], "parkinginincluded" : "false" , "lastrenovationdate" : "1970-01-18t00:00:00z ”, "rating" : 3.60 , "address" : { “streetaddress”:“677 第五大道”, “city”:“纽约”, “stateprovince”:“纽约” , “postalcode”:“10022”, “country”:“美国” } }, { “@search. action" : "上传" , "hotelid" : "2" , "hotelname" : "双圆顶汽车旅馆" , "description" :“该酒店坐落在一座十九世纪的广场上,该广场已按照最高建筑标准进行扩建和翻新,打造出一座现代化、实用的一流酒店,艺术和独特的历史元素与最现代的舒适设施共存。” , "description_fr" : "l'hôtel 位于十九世纪的地方,是一座现代化酒店的高级规范建筑,在艺术和历史独特方面具有一流的功能和一流的设计舒适与现代共存。” , "category" : "精品店" , "tags" : [ "泳池" ,], "parkinginincluded" : "false" , "lastrenovationdate" : "1979-02-18t00:00:00z" , "rating" : 3.60 , "address" : { "streetaddress" : "140 大学城中心" , "city”:“萨拉索塔”, “stateprovince”:“佛罗里达州”, “postalcode”:“34243”, “country”:“美国” } }, { "@search.action" : "上传" , "hotelid" :"3" , "hotelname" : "三重景观酒店" , "description" : "该酒店在 william dough 的管理下以其卓越的美食脱颖而出,他为酒店的所有餐厅服务提供建议并监督。" , "description_fr" : "l'hôtel 位于十九世纪的地方,是一座现代化酒店的高级规范建筑,在艺术和历史独特方面具有一流的功能和一流的设计舒适与现代共存。” , "category" : "度假村中心" , "tags" : [ "酒吧" , "欧陆式早餐" ], "parkinginincluded" : "true" , "lastrenovationdate" : "2015-09-20t00:00:00z" , "rating" : 4.80 , "address" : { "streetaddress" : “3393 peachtree rd”、 “city”:“亚特兰大”、 “stateprovince”:“ga”、 “postalcode”:“30326”、 “country”:“美国” } }]
现在将这些文档推送到语义搜索索引。
try: result = search_client.upload_documents(documents=documents) print("upload of new document succeeded: {}".format(result[0].succeeded))except exception as ex: print (ex.message)
与 openai 集成让我们建立与 openai 的连接:
question="what is the address of chatgpt hotel?"
然后,添加 azure openai 连接:
###import osimport requestsimport jsonimport openaios.environ["azure_openai_key"] = "xxxx"os.environ["azure_openai_endpoint"] = "xxxx"openai.api_key = os.getenv("azure_openai_key")openai.api_base = os.getenv("azure_openai_endpoint")openai.api_type = 'azure'openai.api_version = '2023-05-15'# 在 azure openai studio > 部署中查找deployment_name = 'gpt-35-turbo'#### 定义一个函数,根据系统消息和消息创建提示def create_prompt(system_message, messages): prompt = system_message message_template = "\n<|im_start|>{}\n{}\n<|im_end|>" for message in messages: prompt += message_template.format(message['sender'], message['text']) prompt += "\n<|im_start|>assistant\n" return prompt# 定义系统消息system_message_template = "<|im_start|>system\n{}\n<|im_end|>"system_message = system_message_template.format("")print(system_message)
此时,您可以使用语义搜索和 azure openai。我们来查询语义搜索:
import jsonresults = search_client.search(search_text=question, include_total_count=true, select='hotelid,hotelname,tags,address')= search_client.search(search_text=question, include_total_count=true, select='hotelid,hotelname,tags,address')json_results=""print ('total documents matching query:', results.get_count())for result in results: #print("{}: {}: {}".format(result["hotelid"], result["hotelname"], result["tags"],results["address"])) json_results+=str(result)print(json_results)
有了搜索结果,我们现在可以利用 azure openai 来解释或进一步处理结果。
# 创建消息列表来跟踪对话messages = [{"sender": "user", "text": "hello, take into account the following information "+json_results}, {"sender": "user", "text": question}, ]response = openai.completion.create( engine=deployment_name, prompt= create_prompt(system_message, messages), temperature=0.7, max_tokens=800, top_p=0.95, frequency_penalty=0, presence_penalty=0, stop=["<|im_end|>"])print(response)
此代码向 openai 模型提示搜索结果和我们的原始问题,使其能够根据数据处理并提供有意义的信息。
结论在本文中,我们了解了如何将 azure 语义搜索的强大功能与 openai 的功能相结合。通过集成这两个强大的工具,我们可以在我们的应用程序中为用户提供丰富的智能搜索结果。
以上就是利用azure语义搜索与openai,打造认知搜索系统的详细内容。
其它类似信息

推荐信息