


Using Azure Semantic Search and OpenAI to build a cognitive search system
In today’s digital age, having powerful, scalable and efficient systems is more than just a competitive advantage; it's necessary. Whether you're working to optimize user input processing to simplify document searches, a combination of services and platforms is the key to unparalleled performance. In this article, we'll explore a holistic approach that combines the power of Azure Cognitive Services with the capabilities of OpenAI. By delving into intent recognition, document filtering, domain-specific algorithms, and text summarization, you'll learn to create a system that not only understands user intent but also processes and presents information efficiently.
We will build this:
Setting up the environment
Before we dive in, let’s make sure we have it installed Download the necessary packages and set the environment variables:
!pip show azure-search-documents %pip install azure-search-documents --pre %pip show azure-search-documents !pip install python-dotenv !pip install openai import os import requests import json import openai 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' # Look in Azure OpenAI Studio > Deployments deployment_name = 'gpt-35-turbo'
Here, we set up the OpenAI environment with the necessary API keys, endpoints and types.
Set up Azure Search
To use Azure Semantic Search, we need to import the necessary modules and set up the environment.
import os from azure.core.credentials import AzureKeyCredential from azure.search.documents.indexes import SearchIndexClient from azure.search.documents import SearchClient from azure.search.documents.indexes.models import ( ComplexField, CorsOptions, SearchIndex, ScoringProfile, SearchFieldDataType, SimpleField, SearchableField )
After importing the module, we can now set up the Azure Search Service endpoint and API key:
# 从环境中设置服务端点和 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))
(Note: Be sure to mask or hide your key before sharing any code. )
Preparing indexes for Azure Semantic Search
Before adding data to Azure Search, we need to define an index that describes the structure of the data:
# 删除索引(如果存在) try: result = admin_client.delete_index(index_name) print ('Index', index_name, 'Deleted') except Exception as ex: print (ex)
This code snippet ensures that if the index already exists, it is deleted. This is useful when rerunning code or changing indexes.
Now, let us specify the schema of the index:
# 指定索引模式 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' : [ '标签' , '地址/城市' , '地址/国家' ]}]
Next, you have to create this index on 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)
After creating the index, we need to populate it with documents it. It’s important to point out that it can be any type of document! I just manually add the documents that will persist in the blob storage here:
文档 = [ { "@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”:“美国” } } ]
Now push these documents to the semantic search index.
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)
Integration with OpenAI
Let’s establish a connection to OpenAI:
question="What is the address of ChatGpt Hotel?"
Then, add the Azure OpenAI connection:
### import os import requests import json import openai os.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)
At this point, you can use semantic search and Azure OpenAI. Let’s query Semantic Search:
import json results = 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)
With the search results in hand, we can now leverage Azure OpenAI to interpret or further process the results.
# 创建消息列表来跟踪对话 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)
This code prompts the OpenAI model with search results and our original question, allowing it to process and provide meaningful information based on the data.
Conclusion
In this article, we learned how to combine the power of Azure Semantic Search with the capabilities of OpenAI. By integrating these two powerful tools, we can provide users with rich, intelligent search results in our applications.
The above is the detailed content of Using Azure Semantic Search and OpenAI to build a cognitive search system. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Error 801c03ed is usually accompanied by the following message: Administrator policy does not allow this user to join the device. This error message will prevent you from installing Windows and joining a network, thereby preventing you from using your computer, so it is important to resolve this issue as soon as possible. What is error code 801c03ed? This is a Windows installation error that occurs due to the following reason: Azure setup does not allow new users to join. Device objects are not enabled on Azure. Hardware hash failure in Azure panel. How to fix error code 03c11ed on Windows 801? 1. Check Intune settings Log in to Azure portal. Navigate to Devices and select Device Settings. Change "Users can

OpenAL is an open cross-platform audio library for handling the playback and mixing of 3D audio and multi-channel audio. It was developed by Creative Labs and was originally used for game development, but is now widely used in multimedia applications, virtual Reality, augmented reality and audio editing. OpenAL provides developers with an API to control audio effects, which can be used for the development of games, multimedia applications and other audio-related software.

Designed to simplify document search, a combination of services and platforms are key to unparalleled performance. In this article, we'll explore a holistic approach that combines the power of Azure Cognitive Services with the capabilities of OpenAI. By delving into intent recognition, document filtering, domain-specific algorithms, and text summarization, you'll learn to create a system that not only understands user intent but also processes and presents information efficiently.

According to news from this site on December 17, the Azure OpenAI service provides REST API access to OpenAI’s powerful language models, which include GPT-4, GPT-3.5-Turbo and embedded model series. Microsoft announced further enhancements to the Azure OpenAI service and provided customers with a public preview version of the latest GPT-4 Turbo with Vision. This advanced multi-modal AI model inherits all the powerful features of GPT-4 Turbo and also adds image processing and analysis. ability. This opens up the opportunity to leverage GPT-4 for more tasks, such as improving accessibility, interpreting and analyzing data visualizations, and

According to news from this site on August 16, Microsoft issued an announcement yesterday, announcing that it will enforce the multi-factor authentication (MFA) function starting in October to help reduce the possibility of account hacking. Microsoft says MFA can prevent more than 99.2% of such account compromise attacks, so the measure is mandatory. According to reports, this process will be implemented gradually in two phases. This site summarizes it as follows: Phase 1: Starting from October, MFA will be required to log in to the Azure portal, Microsoft Entra Management Center and Intune Management Center, but it will not affect other Azure client. Phase 2: Starting in early 2025, MFA requirements will gradually expand to other Azure clients, such as Azure

The functions of openal include 3D sound effects, multi-channel audio, audio spatial positioning, audio format support, audio effects processing, cross-platform support and other functions. Detailed introduction: 1. 3D sound effects, OpenAL can simulate real 3D sound effects. By controlling the position, direction, distance and volume of audio parameters, the listener can feel the audio coming from different directions and distances; 2. Multi-channel audio, OpenAL Supports the playback and mixing of multi-channel audio, and can play multiple sound sources at the same time and mix them; 3. Audio spatial positioning, etc.

How to build reliable cloud applications using React and Microsoft Azure. With the development of cloud computing, more and more applications are migrating to the cloud. In this process, it is very important to choose a reliable and efficient development framework. React, as a popular front-end framework, has features such as efficient component development and virtual DOM updates, while Microsoft Azure is a flexible cloud service platform that provides powerful computing, storage, and deployment capabilities. This article will introduce how

Microsoft has announced that the document translation feature built into Azure Translator can now scan and translate PDF documents. The company says users no longer need to pre-process documents through an OCR engine before attempting to translate them. The document translation feature, first launched a year ago, is capable of translating multiple documents into more than 110 languages and dialects at once. Today's update means PDF files as well as Word and PowerPoint files are now fully supported. According to the company, being able to scan PDFs with scanned image content is highly desirable. Explaining some of the features, Microsoft said: The File Translation Service now has the intelligence to identify whether a PDF document contains scanned image content,
