search
HomeTechnology peripheralsAIUsing 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:

Using Azure Semantic Search and OpenAI to build a cognitive search system

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[&#39;sender&#39;], message[&#39;text&#39;])
    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=&#39;HotelId,HotelName,Tags,Address&#39;)=  search_client.search(search_text=question, include_total_count=True, select=&#39;HotelId,HotelName,Tags,Address&#39;)
json_results=""
print (&#39;Total Documents Matching Query:&#39;, 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!

Statement
This article is reproduced at:Dr. Ernesto Lee. If there is any infringement, please contact admin@php.cn delete
Are You At Risk Of AI Agency Decay? Take The Test To Find OutAre You At Risk Of AI Agency Decay? Take The Test To Find OutApr 21, 2025 am 11:31 AM

This article explores the growing concern of "AI agency decay"—the gradual decline in our ability to think and decide independently. This is especially crucial for business leaders navigating the increasingly automated world while retainin

How to Build an AI Agent from Scratch? - Analytics VidhyaHow to Build an AI Agent from Scratch? - Analytics VidhyaApr 21, 2025 am 11:30 AM

Ever wondered how AI agents like Siri and Alexa work? These intelligent systems are becoming more important in our daily lives. This article introduces the ReAct pattern, a method that enhances AI agents by combining reasoning an

Revisiting The Humanities In The Age Of AIRevisiting The Humanities In The Age Of AIApr 21, 2025 am 11:28 AM

"I think AI tools are changing the learning opportunities for college students. We believe in developing students in core courses, but more and more people also want to get a perspective of computational and statistical thinking," said University of Chicago President Paul Alivisatos in an interview with Deloitte Nitin Mittal at the Davos Forum in January. He believes that people will have to become creators and co-creators of AI, which means that learning and other aspects need to adapt to some major changes. Digital intelligence and critical thinking Professor Alexa Joubin of George Washington University described artificial intelligence as a “heuristic tool” in the humanities and explores how it changes

Understanding LangChain Agent FrameworkUnderstanding LangChain Agent FrameworkApr 21, 2025 am 11:25 AM

LangChain is a powerful toolkit for building sophisticated AI applications. Its agent architecture is particularly noteworthy, allowing developers to create intelligent systems capable of independent reasoning, decision-making, and action. This expl

What are the Radial Basis Functions Neural Networks?What are the Radial Basis Functions Neural Networks?Apr 21, 2025 am 11:13 AM

Radial Basis Function Neural Networks (RBFNNs): A Comprehensive Guide Radial Basis Function Neural Networks (RBFNNs) are a powerful type of neural network architecture that leverages radial basis functions for activation. Their unique structure make

The Meshing Of Minds And Machines Has ArrivedThe Meshing Of Minds And Machines Has ArrivedApr 21, 2025 am 11:11 AM

Brain-computer interfaces (BCIs) directly link the brain to external devices, translating brain impulses into actions without physical movement. This technology utilizes implanted sensors to capture brain signals, converting them into digital comman

Insights on spaCy, Prodigy and Generative AI from Ines MontaniInsights on spaCy, Prodigy and Generative AI from Ines MontaniApr 21, 2025 am 11:01 AM

This "Leading with Data" episode features Ines Montani, co-founder and CEO of Explosion AI, and co-developer of spaCy and Prodigy. Ines offers expert insights into the evolution of these tools, Explosion's unique business model, and the tr

A Guide to Building Agentic RAG Systems with LangGraphA Guide to Building Agentic RAG Systems with LangGraphApr 21, 2025 am 11:00 AM

This article explores Retrieval Augmented Generation (RAG) systems and how AI agents can enhance their capabilities. Traditional RAG systems, while useful for leveraging custom enterprise data, suffer from limitations such as a lack of real-time dat

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment