GPT 기반 차량 추천 엔진 구축
OpenAI GPT, Python, LangChain 및 Azure Cognitive Search를 사용하여 추천 엔진 구축.

읽을 AI 기반 콘텐츠가 부족한 경우 목록에 대한 또 다른 콘텐츠가 있습니다. 이 게시물에 고양이가 있는 귀여운 스토리 맵(예, CatGPT)을 추가하여 나머지 항목과 차별화되도록 했습니다.
순수하고 필사적입니까? 아마도…
(PS 고양이와 생성 AI를 사용하는 것은 완전히 독창적인 것이 아닙니다.https://cat-gpt.com/.)
신청
우리가 풀어볼 앱은 당신이 (비공식적으로) 선호하는 것을 기반으로 추천 차량 목록을 반환하는 중고차 추천 챗봇입니다. 결과는 각 자동차에 대한 유익한 세부 정보와 권장 이유에 대한 근거로 풍부해집니다.
대화 흐름은 사용자, Chatbot, GPT(또는 선택한 LLM) 및 차량 검색 엔진 간의 상호 작용으로 다음과 같이 진행됩니다.
1단계: 사용자는 채팅 프롬프트에 기본 설정을 씁니다.
차량 추천 엔진은 종종 사용자가 일치하는 차량을 찾는 데 사용되는 기본 설정을 명시적으로 설정하도록 요구합니다. 여기에서 아이디어는 사용자가 자신의 개인 스타일로 원하는 것을 챗봇에 자유롭게 알리고 GPT 모델의 마법을 사용하여 이를 다운스트림 검색 API에서 사용할 수 있는 것으로 바꾸는 것입니다.

2단계: 챗봇은 제공된 기본 설정을 사용하여 구조화된 검색 쿼리를 생성하도록 GPT에 요청합니다.
Chatbot은 Chatbot에 입력된 기본 설정과 검색 엔진에서 검색할 수 있는 지정된 필드 목록을 기반으로 검색 쿼리를 요청하는 GPT 프롬프트를 생성합니다. 이 프롬프트는 GPT로 전송되어 마법을 부리고 모호한 인간 언어를 쿼리 매개변수에 대해 해석된 값이 있는 구조화된 쿼리로 변환합니다.

3단계: 챗봇은 GPT에서 생성한 쿼리를 사용하여 검색 엔진에 쿼리합니다.
잘 구성된 검색 쿼리로 무장한 챗봇은 이를 검색 엔진으로 보내고 일치하는 차량 결과 목록을 다시 가져옵니다.

4단계: 챗봇은 GPT에게 검색 결과를 인간에게 의미 있는 것으로 바꿔달라고 요청합니다.
제공된 검색 기준과 일치하는 차량 목록을 통해 GPT를 다시 사용하여 구조화된 데이터를 잘 쓰여지고 사람이 읽을 수 있는 텍스트로 변환하여 차량에 대한 흥미로운 사실과 사용자 선호도에 따라 차량이 추천된 이유를 포함하여 콘텐츠를 풍부하게 합니다.

5단계:
챗봇은 만족하는 사용자에게 콘텐츠를 반환합니다. 기본 설정을 개선하고 Chatbot이 동일한 패턴으로 GPT 및 검색과 함께 작동하도록 채팅을 계속할 수 있습니다.


기술
이 앱은 Python을 사용하여 개발되었으며 몇 가지 주목할만한 라이브러리는 다음과 같습니다.
- streamlit: Streamlit은 웹 애플리케이션을 빠르게 만드는 데 사용되는 Python 라이브러리입니다. 이 코드에서는 차량 추천 엔진용 사용자 인터페이스를 빌드하는 데 사용됩니다.
- langchain: 자연어 모델을 구축하기 위한 일련의 도구를 제공하는 사용자 정의 패키지입니다. OpenAPI GPT와 같은 LLM에 연결하는 llms를 포함하여 여러 하위 모듈이 있습니다.
- azure.search.documents: 검색을 수행하고 검색 결과를 관리하기 위해 Azure 검색 서비스와 상호 작용하는 데 사용되는 SearchClient 클래스를 제공합니다.
OpenAI GPT API를 사용했습니다. 저는 터보 3.5 모델을 선택했습니다.
코드
다음은 App.py의 코드 연습입니다.
필요한 라이브러리를 가져옵니다.
import os
import json
import streamlit as st
from apikey import apikey
from searchhelper import azure_cognitive_search
from searchhelper import json_data
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain, SequentialChain
from langchain.memory import ConversationBufferMemory
from langchain.utilities import WikipediaAPIWrapper
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClientApp Framework: Streamlit is used to set up the main components of the web application, including the title and user input area for vehicle preferences.
# Get OpenAI API Key
os.environ['OPENAI_API_KEY'] = apikey
# app framework
st.title('Vehicle Recommendation Engine')
prompt = st.text_area('Tell us what you are looking for in a car')
#prompt templates
title_template = PromptTemplate(
input_variables= ['preferences', 'vehicle_schema'],
template='based on the following user provided vehicle preferences : {preferences} and on the following JSON Schema of Vehicle Attributes: {vehicle_schema}, create a lucence search query that best fits the prefferences'
)
script_template = PromptTemplate(
input_variables= ['preferences', 'vehicle_results_json'],
template='write a description and five interesting facts about each vehicle returned in the following list: {vehicle_results_json}. Each paragraph must belong to its own bullet point. Add a final summary after the recommended vechiles for why these choices are a good match for these preferences provided: {preferences}'
)
# Memory
title_memory = ConversationBufferMemory(input_key='preferences', memory_key='chat_history')
script_memory = ConversationBufferMemory(input_key='vehicle_results_json', memory_key='chat_history')
#LLMs
llm = OpenAI(temperature=0.9, max_tokens = 2056)
title_chain = LLMChain(llm=llm, prompt=title_template, verbose=True, output_key='lucence_query', memory=title_memory)
script_chain = LLMChain(llm=llm, prompt=script_template, verbose=True, output_key='vehicle_recommendations_full', memory=script_memory)
if prompt:
title= title_chain.run(preferences=prompt, vehicle_schema=json_data)
vehicle_results = azure_cognitive_search(prompt)
script = script_chain.run(preferences=prompt, vehicle_results_json=vehicle_results)
st.write(script)
with st.expander('Query History'):
st.info(title_memory.buffer)
검색 기능:
def azure_cognitive_search(query: str) -> dict:
# Get elastic search keys
service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT")
index_name = os.getenv("AZURE_SEARCH_INDEX_NAME")
key = os.getenv("AZURE_SEARCH_API_KEY")
# Initialise search client
client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))
# Perform a search with the Lucene query
results = client.search(query, top=3)
# Construct a JSON object from the search results
vehicles = []
for item in results:
content = item['content']
vehicle = {
'BRAND': content['BRAND'],
'MODEL': content['MODEL'],
'VARIANT': content['VARIANT']
# a lot more fields removed for brevities sake
}
vehicles.append(vehicle)
return json.dumps(vehicles)
json_data = {
"content": {
"DOORS": 5,
"COLOUR": "Grey",
"VARIANT": "GALAXY 2.0 TDCi 180 Titanium X 5dr MPV",
"BODY_STYLE": "MPV",
"MILEAGE": 23744,
"YEAR": 2013,
"MODEL_DESCRIPTION": "GALAXY",
"CAPACITY": 1997,
"LIST_PRICE": 19275,
"TRANSMISSION": "MANUAL",
}
}
다음은 프롬프트의 예이며 GPT에서 결과를 다시 해석했습니다.

