<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ChatBots Archives - relataly.com</title>
	<atom:link href="https://www.relataly.com/category/use-case/chatbots/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.relataly.com/category/use-case/chatbots/</link>
	<description>The Business AI Blog</description>
	<lastBuildDate>Fri, 09 Feb 2024 10:28:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://www.relataly.com/wp-content/uploads/2023/04/cropped-AI-cat-Icon-White.png</url>
	<title>ChatBots Archives - relataly.com</title>
	<link>https://www.relataly.com/category/use-case/chatbots/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">175977316</site>	<item>
		<title>Building a Conversational Voice Bot with Azure OpenAI and Python: The Future of Human and Machine Interaction</title>
		<link>https://www.relataly.com/voice-conversations-with-azure-ai/14291/</link>
					<comments>https://www.relataly.com/voice-conversations-with-azure-ai/14291/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Thu, 08 Feb 2024 21:09:50 +0000</pubDate>
				<category><![CDATA[Azure Machine Learning]]></category>
		<category><![CDATA[ChatBots]]></category>
		<category><![CDATA[Generative AI]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=14291</guid>

					<description><![CDATA[<p>OpenAI and Microsoft have just released a new generation of text-to-speech models that take synthetic speech to a new level. In my latest project I have combined these new models with Azure OpenAI&#8217;s ingenuine conversation capacity. The result is a conversational voice bot that uses Generative AI to converse with users in natural spoken language. ... <a title="Building a Conversational Voice Bot with Azure OpenAI and Python: The Future of Human and Machine Interaction" class="read-more" href="https://www.relataly.com/voice-conversations-with-azure-ai/14291/" aria-label="Read more about Building a Conversational Voice Bot with Azure OpenAI and Python: The Future of Human and Machine Interaction">Read more</a></p>
<p>The post <a href="https://www.relataly.com/voice-conversations-with-azure-ai/14291/">Building a Conversational Voice Bot with Azure OpenAI and Python: The Future of Human and Machine Interaction</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>OpenAI and Microsoft have just <a href="https://techcommunity.microsoft.com/t5/ai-azure-ai-services-blog/azure-openai-service-announces-assistants-api-new-models-for/ba-p/4049940">released a new generation of text-to-speech models</a> that take synthetic speech to a new level. In my latest project I have combined these new models with Azure OpenAI&#8217;s ingenuine conversation capacity. The result is a conversational voice bot that uses Generative AI to converse with users in natural spoken language. </p>



<p>This article describes the Python implementation of this project. The bot is designed to understand spoken language and process it through OpenAI GPT-4. It responds with contextually aware dialogue, all in natural-sounding speech. This seamless integration facilitates a conversational flow that feels intuitive and engaging. The voice processing capacities enable users to have meaningful exchanges with the bot as if they were conversing with another person. Testing the bot was a lot of fun. It felt a bit like the iconic scene from Iron Man where the hereo converses with an AI assistant.</p>



<p>Here is an example of the audio response quality:</p>



<figure class="wp-block-audio"><audio controls src="https://www.relataly.com/wp-content/uploads/2024/02/ssml_output.wav"></audio></figure>



<p>Also:</p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/">From Pirates to Nobleman: Simulating Multi-Agent Conversations using OpenAI’s ChatGPT and Python</a></li>



<li><a href="https://www.relataly.com/text-to-sql-with-llms-embracing-the-future-of-data-interaction/14234/" target="_blank" rel="noreferrer noopener">Text-to-SQL with LLMs &#8211; Embracing the Future of Data Interaction</a></li>
</ul>



<h2 class="wp-block-heading"><strong>Understanding the Voice Bot</strong></h2>



<p>The magic begins with the user speaking to the bot. Azure Cognitive Services transcribes the spoken words into text, which is then fed into Azure&#8217;s OpenAI service. Here, the text is processed, and a response is generated based on the conversation&#8217;s context and history. Finally, the text-to-speech model transforms the response back into speech, completing the cycle of interaction. This process  showcases the potential of AI in understanding and participating in human-like conversations.</p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="1966" height="512" data-attachment-id="14294" data-permalink="https://www.relataly.com/voice-conversations-with-azure-ai/14291/image-32/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2024/02/image.png" data-orig-size="1966,512" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2024/02/image.png" src="https://www.relataly.com/wp-content/uploads/2024/02/image.png" alt="" class="wp-image-14294" srcset="https://www.relataly.com/wp-content/uploads/2024/02/image.png 1966w, https://www.relataly.com/wp-content/uploads/2024/02/image.png 300w, https://www.relataly.com/wp-content/uploads/2024/02/image.png 512w, https://www.relataly.com/wp-content/uploads/2024/02/image.png 768w, https://www.relataly.com/wp-content/uploads/2024/02/image.png 1536w" sizes="(max-width: 1237px) 100vw, 1237px" /></figure>



<h3 class="wp-block-heading" id="h-prerequisites-azure-service-integration">Prerequisites &amp; Azure Service Integration</h3>



<p>Our conversational voice bot is built upon two pivotal Azure services: Cognitive Speech Services and OpenAI. Billing of these services is pay-per-use. Unless you process large numbers of requests, the costs for experimenting with these services is relatively low. </p>



<h4 class="wp-block-heading" id="h-azure-cognitive-speech-services">Azure Cognitive Speech Services</h4>



<p><a href="https://azure.microsoft.com/en-us/products/ai-services/ai-speech">Azure AI Speech Services (previously Cognitive Speech Services)</a> provide the tools necessary for speech-to-text conversion, enabling our voice bot to understand spoken language. This service boasts advanced speech recognition capabilities, ensuring accurate transcription of user speech into text. Furthermore, it powers the text-to-speech synthesis that transforms generated text responses back into natural-sounding voice. This allows for a truly conversational experience. </p>



<p>The newest generation of OpenAI text-to-speech models is now also <a href="https://techcommunity.microsoft.com/t5/ai-azure-ai-services-blog/announcing-openai-text-to-speech-voices-on-azure-openai-service/ba-p/4049696">availbale in Azure AI Speech</a>. These models can synthesize voices in unknown level of quality. I am most impressed by its capability to alter intonation dynamically to express emotions.</p>



<h4 class="wp-block-heading" id="h-azure-openai-service">Azure OpenAI Service</h4>



<p>At the heart of our project lies <a href="https://azure.microsoft.com/en-us/products/ai-services/openai-service">Azure&#8217;s OpenAI service</a>, which uses the power of models like GPT-4 context-aware responses. Once Azure Cognitive Speech Services transcribe the user&#8217;s speech into text, this text is sent to OpenAI. The OpenAI model then processes the input and generates a completion. The service&#8217;s ability to understand context and generate engaging responses is what makes our voice bot remarkably human-like.</p>



<h2 class="wp-block-heading" id="h-implementation-detailed-code-walkthrough">Implementation: Detailed Code Walkthrough</h2>



<p>Let&#8217;s start with the implementation! We kick things off with <strong>Azure Service Authentication</strong>, where we set up our conversational voice bot to communicate with Azure and OpenAI&#8217;s advanced services. Then, <strong>Speech Recognition</strong> steps in, acting as our bot&#8217;s ears, converting spoken words into text. Next up, <strong>Processing and Response Generation</strong> uses OpenAI&#8217;s GPT-4 to turn text into context-aware responses. <strong>Speech Synthesis</strong> then gives our bot a voice, transforming text responses back into spoken words for a natural conversational flow. Finally, <strong>Managing the Conversation</strong> keeps the dialogue coherent and engaging. Through these steps, we create a voice bot that offers an intuitive and engaging conversational experience. Let&#8217;s discuss these sections one by one. </p>



<p>As always, you can find the code on github:</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns14291_9e80c9-12"><a class="kb-button kt-button button kb-btn14291_e0f677-ca kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/AzureOpenAIVoiceAssistant/tree/main" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn14291_8c1344-11 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly Github Repo </span></a></div>



<h3 class="wp-block-heading">Step #1 Azure Service Authentication </h3>



<p>First off, we kick things off by getting our ducks in a row with <strong>Azure Service Authentication</strong>. This is where the magic starts, setting the stage for our conversational voice bot to interact with Azure&#8217;s brainy suite of Cognitive Services and the fantastic OpenAI models. By fetching API keys and setting up our service regions, we&#8217;re essentially giving our project the keys to the kingdom.</p>



<p>For using dotenv, you need to create an .env file in your root folder. <a href="https://pypi.org/project/python-dotenv/">Here</a> is more information on how this works.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import os
from dotenv import load_dotenv
import azure.cognitiveservices.speech as speechsdk
from openai import AzureOpenAI

# Load environment variables from .env file
load_dotenv()

# Constants from .env file
SPEECH_KEY = os.getenv('SPEECH_KEY')
SERVICE_REGION = os.getenv('SERVICE_REGION')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
OPENAI_ENDPOINT = os.getenv('OPENAI_ENDPOINT')

# Azure Speech Configuration
speech_config = speechsdk.SpeechConfig(subscription=SPEECH_KEY, region=SERVICE_REGION)
speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config)
speech_config.speech_recognition_language=&quot;en-US&quot;

# OpenAI Configuration
openai_client = AzureOpenAI(
    api_key=OPENAI_API_KEY,
    api_version=&quot;2023-12-01-preview&quot;,
    azure_endpoint=OPENAI_ENDPOINT
)
</pre></div>



<h3 class="wp-block-heading">Step #2 Speech Recognition</h3>



<p>The user&#8217;s spoken input is captured and converted into text using Azure&#8217;s Speech-to-Text service. This involves initializing the speech recognition service with Azure credentials and configuring it to listen for and transcribe spoken language in real-time.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def recognize_from_microphone():
    # Configure the recognizer to use the default microphone.
    audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
    # Create a speech recognizer with the specified audio and speech configuration.
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

    print(&quot;Speak into your microphone.&quot;)
    # Perform speech recognition and wait for a single utterance.
    speech_recognition_result = speech_recognizer.recognize_once_async().get()

    # Process the recognition result based on its reason.
    if speech_recognition_result.reason == speechsdk.ResultReason.RecognizedSpeech:
        print(&quot;Recognized: {}&quot;.format(speech_recognition_result.text))
        # Return the recognized text if speech was recognized.
        return speech_recognition_result.text
    elif speech_recognition_result.reason == speechsdk.ResultReason.NoMatch:
        print(&quot;No speech could be recognized: {}&quot;.format(speech_recognition_result.no_match_details))
    elif speech_recognition_result.reason == speechsdk.ResultReason.Canceled:
        cancellation_details = speech_recognition_result.cancellation_details
        print(&quot;Speech Recognition canceled: {}&quot;.format(cancellation_details.reason))
        if cancellation_details.reason == speechsdk.CancellationReason.Error:
            print(&quot;Error details: {}&quot;.format(cancellation_details.error_details))
            print(&quot;Did you set the speech resource key and region values?&quot;)
    # Return 'error' if recognition failed or was canceled.
    return 'error'</pre></div>



<h3 class="wp-block-heading">Step #3 Processing and Response Generation</h3>



<p>Once we&#8217;ve got your words neatly transcribed, it&#8217;s time for the <strong>Processing and Response Generation</strong> phase. This is where OpenAI steps in, acting like the brain behind the operation. It takes your spoken words, now in text form, and churns out responses that are nothing short of conversational gold. We nudge OpenAI&#8217;s GPT-4 into generating replies that feel as natural as chatting with a close friend over coffee. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def openai_request(conversation, sample = [], temperature=0.9, model_engine='gpt-4'):
    # Initialize AzureOpenAI client with keys and endpoints from Key Vault.
    
    
    # Send a request to Azure OpenAI with the conversation context and get a response.
    response = openai_client.chat.completions.create(model=model_engine, messages=conversation, temperature=temperature, max_tokens=500)
    return response.choices[0].message.content</pre></div>



<h3 class="wp-block-heading">Step #4 Speech Synthesis</h3>



<p>Next up, we tackle <strong>Speech Synthesis</strong>. If the previous step was the brain, consider this the voice of our operation. Taking the AI-generated text, we transform it back into speech—like turning lead into gold, but for conversations. Through Azure&#8217;s Text-to-Speech service, we&#8217;re able to give our bot a voice that&#8217;s not only clear but also surprisingly human-like. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def synthesize_audio(input_text):
    # Define SSML (Speech Synthesis Markup Language) for input text.
    ssml = f&quot;&quot;&quot;
        &lt;speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'&gt;
            &lt;voice name='en-US-OnyxMultilingualNeuralHD'&gt;
                &lt;p&gt;
                    {input_text}
                &lt;/p&gt;
            &lt;/voice&gt;
        &lt;/speak&gt;
        &quot;&quot;&quot;
    
    audio_filename_path = &quot;audio/ssml_output.wav&quot;  # Define the output audio file path.
    print(ssml)
    # Synthesize speech from the SSML and wait for completion.
    result = speech_synthesizer.speak_ssml_async(ssml).get()

    # Save the synthesized audio to a file if synthesis was successful.
    if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
        with open(audio_filename_path, &quot;wb&quot;) as audio_file:
            audio_file.write(result.audio_data)
        print(f&quot;Speech synthesized and saved to {audio_filename_path}&quot;)
    elif result.reason == speechsdk.ResultReason.Canceled:
        cancellation_details = result.cancellation_details
        print(f&quot;Speech synthesis canceled: {cancellation_details.reason}&quot;)
        if cancellation_details.reason == speechsdk.CancellationReason.Error:
            print(f&quot;Error details: {cancellation_details.error_details}&quot;)


# Create the audio directory if it doesn't exist.
if not os.path.exists('audio'):
    os.makedirs('audio')</pre></div>



<h3 class="wp-block-heading">Step #5 Managing the Conversation</h3>



<p>Finally, we bring it all together in the Managing the Conversation step. This is where we ensure the chat keeps rolling, looping through listening, thinking, and speaking. We keep track of what&#8217;s been said to keep the conversation relevant and engaging. </p>



<p>The system message below makes the bot talk like a pirate. But you can easily adjust the system message and this way customize the bots behavior.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">conversation=[{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant that talks like pirate. If you encounter any issues, just tell a pirate joke or a story.&quot;}]

while True:
    user_input = recognize_from_microphone()  # Recognize user input from the microphone.
    conversation.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input})  # Add user input to the conversation context.

    assistant_response = openai_request(conversation)  # Get the assistant's response based on the conversation.

    conversation.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: assistant_response})  # Add the assistant's response to the context.
    
    print(assistant_response)
    synthesize_audio(assistant_response)  # Synthesize the assistant's response into audio.</pre></div>



<p>Throughout these steps, the conversation&#8217;s context is managed meticulously to ensure continuity and relevance in the bot&#8217;s responses, making the interaction feel more like a dialogue between humans.</p>



<h2 class="wp-block-heading">Current Challenges</h2>



<p>Despite the promising capabilities of our voice bot, the journey through its development and interaction has presented a few challenges that underscore the complexity of human-machine communication.</p>



<h4 class="wp-block-heading">Slow Response Time</h4>



<p>One of the notable hurdles is the slow response time experienced during interactions. The process, from speech recognition through to response generation and back to speech synthesis, involves several steps that can introduce latency. This latency can detract from the user experience, as fluid conversations typically require quick exchanges. Optimizing the interaction flow and exploring more efficient data processing methods may mitigate this issue in the future.</p>



<h4 class="wp-block-heading">Handling Pauses in Speech</h4>



<p>Another challenge lies in the bot&#8217;s handling of longer pauses while speaking. The current setup does not always allow users to pause thoughtfully without triggering the end of their input. This may sometimes lead to a situation where the model cuts off speech prematurely. This limitation points to the need for more sophisticated speech recognition algorithms capable of distinguishing between a conversational pause and the end of an utterance.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>This article has shown how you can build a conversational voice bot in Python with the latest pretrained AI models. The project showcases the incredible potential of combining Azure Cognitive Services with OpenAI&#8217;s conversational models. I hope by now you understand the technical feasibility of creating voice-based applications and how they open up a world of possibilities for human-machine interaction. As we continue to refine and enhance this technology, the line between talking to a machine and conversing with a human will become ever more blurred, leading us into a future where AI companionship becomes reality.</p>



<p>This exploration of Azure Cognitive Services and OpenAI&#8217;s integration within a voice bot is just the beginning. As AI continues to evolve, the ways in which we interact with technology will undoubtedly transform, making our interactions more natural, intuitive, and, most importantly, human.</p>



<p>Also: <a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/"></a><a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/" target="_blank" rel="noreferrer noopener">9 Business Use Cases of OpenAI&#8217;s ChatGPT</a></p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<ul class="wp-block-list">
<li><a href="https://techcommunity.microsoft.com/t5/ai-azure-ai-services-blog/announcing-openai-text-to-speech-voices-on-azure-openai-service/ba-p/4049696" target="_blank" rel="noreferrer noopener">Microsoft announces openai text-to-speech voices</a></li>



<li><a href="https://azure.microsoft.com/en-us/products/ai-services/openai-service" target="_blank" rel="noreferrer noopener">Azure OpenAI Service Documentation</a></li>



<li><a href="https://techcommunity.microsoft.com/t5/ai-azure-ai-services-blog/azure-openai-service-announces-assistants-api-new-models-for/ba-p/4049940" target="_blank" rel="noreferrer noopener">Recent Azure OpenAI Update</a></li>



<li><a href="https://azure.microsoft.com/en-us/products/ai-services/ai-speech" target="_blank" rel="noreferrer noopener">AI Spech Service Documentation</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/voice-conversations-with-azure-ai/14291/">Building a Conversational Voice Bot with Azure OpenAI and Python: The Future of Human and Machine Interaction</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/voice-conversations-with-azure-ai/14291/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		<enclosure url="https://www.relataly.com/wp-content/uploads/2024/02/ssml_output.wav" length="1256846" type="audio/wav" />

		<post-id xmlns="com-wordpress:feed-additions:1">14291</post-id>	</item>
		<item>
		<title>Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT</title>
		<link>https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/</link>
					<comments>https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Wed, 05 Jul 2023 12:45:27 +0000</pubDate>
				<category><![CDATA[ChatBots]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Generative AI]]></category>
		<category><![CDATA[Healthcare]]></category>
		<category><![CDATA[Insurance]]></category>
		<category><![CDATA[Language Generation]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Responsible AI]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Telecommunications]]></category>
		<category><![CDATA[Vector Databases]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[AI in Finance]]></category>
		<category><![CDATA[Deep Learning]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=14056</guid>

					<description><![CDATA[<p>Welcome to the dawn of a new era in digital interaction! With the advent of Generative AI, we&#8217;re witnessing a remarkable revolution that&#8217;s changing the very nature of how we interact with software and digital services. This change is monumental. Leading the charge are the latest generation of AI-powered virtual assistants, aka &#8220;AI copilots&#8221;. Unlike ... <a title="Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT" class="read-more" href="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/" aria-label="Read more about Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT">Read more</a></p>
<p>The post <a href="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/">Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Welcome to the dawn of a new era in digital interaction! With the advent of <a href="https://www.relataly.com/openai-gpt-chatgpt-in-a-business-context-whats-the-value-proposition/12282/" target="_blank" rel="noreferrer noopener">Generative AI</a>, we&#8217;re witnessing a remarkable revolution that&#8217;s changing the very nature of how we interact with software and digital services. This change is monumental. Leading the charge are the latest generation of AI-powered virtual assistants, aka &#8220;AI copilots&#8221;. Unlike traditional narrow AI models, these are capable of understanding user needs, intents, and questions expressed in plain, natural language. </p>



<p>We are talking about nothing less but the next evolution in software design and user experience that is driven by recent advances in generative AI and Large Language Models (LLMs) like <a href="https://openai.com/" target="_blank" rel="noreferrer noopener">OpenAI&#8217;s ChatGPT</a>, <a href="https://bard.google.com/?hl=en" target="_blank" rel="noreferrer noopener">Google Bard</a>, or <a href="https://www.anthropic.com/index/introducing-claude" target="_blank" rel="noreferrer noopener">Anthrophic&#8217;s Claude</a>. </p>



<p>Thanks to LLMs user interactions are no longer bound by the constraints of a traditional user interface with forms and buttons. Whether it&#8217;s creating a proposal in Word, editing an image, or opening a claim in an insurance app, users can express their needs in natural language &#8211; a profound change in our interactions with software and services. </p>



<p>Despite the hype about these new virtual ai assistants, our understanding of how to build an LLM-powered virtual assistant remains scant. So, if you wonder how to take advantage of LLMs and build a virtual assistant for your app, this article is for you. This post will probe into the overarching components needed to create a virtual AI assistant. We will look at the architecture and its components including LLMs, Knowledge store, Cache, Conversational Logic, and APIs.</p>



<p><strong>Also: </strong></p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/" target="_blank" rel="noreferrer noopener">9 Business Use Cases of OpenAI’s ChatGPT</a></li>



<li><a href="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/" target="_blank" rel="noreferrer noopener">Using LLMs (OpenAI’s ChatGPT) to Streamline Digital Experiences</a></li>



<li><a href="https://www.relataly.com/mastering-prompt-engineering-for-chatgpt-a-practical-guide-for-businesses/13134/" target="_blank" rel="noreferrer noopener">ChatGPT Prompt Engineering Guide: Practical Advice for Business Use Cases</a></li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="1016" height="924" data-attachment-id="13898" data-permalink="https://www.relataly.com/?attachment_id=13898#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png" data-orig-size="1016,924" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png" src="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png" alt="Image of human pilots standing in front of an airplane, symbolizing the role of AI Copilots in shaping our interaction with software and its design." class="wp-image-13898" srcset="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png 1016w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png 768w" sizes="(max-width: 1016px) 100vw, 1016px" /><figcaption class="wp-element-caption">The new generation of virtual ai assistants inspires a profound change in the way we interact with software and digital services.</figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Virtual AI Assistants at the Example of Microsoft M365 Copilot</h2>



<p>Advances in virtual AI assistants are closely linked to ChatGPT and other LLMs from US-based startup OpenAI. Microsoft has forged a partnership with OpenAI to bring the latest advances in AI to their products and services. Microsoft has announced these &#8220;Copilots&#8221; across major applications, including M365 and the Power Platform. </p>



<p>Here are some capabilities of these Copilots within M365:</p>



<ul class="wp-block-list">
<li>In <strong>PowerPoint</strong>, Copilot allows users to create presentations based on a given context, such as a Word document, for example by stating &#8220;<em>Create a 10-slide product presentation based on the following product documentation.</em>&#8220;</li>



<li>In <strong>Word</strong>, Copilot can adjust the tone of writing a text or transform a few keywords into a complete paragraph. Simply type something like &#8220;<em>Create a proposal for a 3-month contract for customer XYZ based on doc ADF</em>.&#8221;</li>



<li>In <strong>Excel</strong>, Copilot helps users with analyzing datasets, as well as with creating or modifying them. For example, it can summarize a dataset in natural langue and describe trends. </li>



<li>Let&#8217;s not forget <strong>Outlook</strong>! Your new AI Copilot helps you organize your emails and calendar. It assists you in crafting email responses, scheduling meetings, and even provides summaries of key points from the ones you missed.</li>
</ul>



<p>If you want to learn more about Copilot in M365, this youtube video provides an excellent overview. However, these are merely a handful of examples: <a href="https://www.youtube.com/watch?v=VlM9a469LE0" target="_blank" rel="noreferrer noopener">Microsoft 365 Copilot Explained: How Microsoft Just Changed the Future of Work</a>. The potential of AI copilots extends far beyond the scope of Office applications and can elevate any software or service to a new level. No wonder, large software companies like <a href="https://www.reuters.com/technology/sap-ceo-huge-growth-potential-generative-ai-2023-06-28/" target="_blank" rel="noreferrer noopener">SAP</a>, and Adobe, have announced plans to upgrade their products with copilot features.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="982" height="848" data-attachment-id="13892" data-permalink="https://www.relataly.com/?attachment_id=13892#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/06/image-7.png" data-orig-size="982,848" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-7" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/06/image-7.png" src="https://www.relataly.com/wp-content/uploads/2023/06/image-7.png" alt="Microsoft has announced a whole series of copilots for its products, ranging from digital assistants in M365 office apps to its Azure cloud platform." class="wp-image-13892" srcset="https://www.relataly.com/wp-content/uploads/2023/06/image-7.png 982w, https://www.relataly.com/wp-content/uploads/2023/06/image-7.png 300w, https://www.relataly.com/wp-content/uploads/2023/06/image-7.png 512w, https://www.relataly.com/wp-content/uploads/2023/06/image-7.png 768w" sizes="(max-width: 982px) 100vw, 982px" /><figcaption class="wp-element-caption">Microsoft has <a href="https://blogs.microsoft.com/blog/2023/03/16/introducing-microsoft-365-copilot-your-copilot-for-work/" target="_blank" rel="noreferrer noopener">announced a whole fleet of virtual AI assistants</a> for its products. These range from copilots in M365 office apps to services of its Azure cloud platform.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading" id="h-how-llms-enable-a-new-generation-of-virtual-ai-assistants">How LLMs Enable a New Generation of Virtual AI Assistants</h2>



<p>Virtual AI assistants are nothing but new. Indeed, their roots can be traced back to innovative ventures such as the paperclip assistant, <a href="https://en.wikipedia.org/wiki/Office_Assistant" target="_blank" rel="noreferrer noopener">Clippy, from Microsoft Word</a> &#8211; a pioneering attempt at enhancing user experience. Later on, this was followed by the introduction of conventional chatbots.</p>



<p>Nonetheless, these early iterations had their shortcomings. Their limited capacity to comprehend and assist users with tasks outside of their defined parameters hampered their success on a larger scale. The inability to adapt to a wider range of user queries and requests kept these virtual ai assistants confined within their initial scope, restricting their growth and wider acceptance. So if we talk about this next generation of virtual ai assistants, what has truly revolutionized the scene? In essence, the true innovation lies in the emergence of LLMs such as OpenAI&#8217;s GPT4.</p>



<h3 class="wp-block-heading">LLMs &#8211; A Game Changer for Conversational User Interface Design</h3>



<p>Over time, advancements in machine learning, natural language processing, and vast data analytics transformed the capabilities of AI assistants. Modern AI models, like GPT-4, can understand context, engage in more human-like conversations, and offer solutions to a broad spectrum of queries. Furthermore, the integration of AI assistants into various devices and platforms, along with the increase in cloud computing, expanded their reach and functionality. These technological shifts have reshaped the scene, making AI assistants more adaptable, versatile, and user-friendly than ever before.</p>



<p>Take, for example, an AI model like GPT. A user might instruct, &#8220;Could you draft an email to John about the meeting tomorrow?&#8221; Not only would the AI grasp the essence of this instruction, but it could also produce a draft email seamlessly.</p>



<p>Yet, it&#8217;s not solely their adeptness at discerning user intent that sets LLMs apart. They also exhibit unparalleled proficiency in generating programmatic code to interface with various software functions. Imagine directing your software with, &#8220;Generate a pie chart that visualizes this year&#8217;s sales data by region,&#8221; and witnessing the software promptly fulfilling your command.</p>



<h3 class="wp-block-heading">A Revolution in Software Design and User Experience</h3>



<p>The advanced language understanding offered by LLMs unburdens developers from the painstaking task of constructing every possible dialog or function an assistant might perform. Rather, developers can harness the generative capabilities of LLMs and integrate them with their application&#8217;s API. This integration facilitates a myriad of user options without the necessity of explicitly designing them.</p>



<p>The outcome of this is far-reaching, extending beyond the immediate relief for developers. It sets the stage for a massive transformation in the software industry and the broader job market, affecting how developers are trained and what skills are prioritized. Furthermore, it alters our everyday interaction with technology, making it more intuitive and efficient. </p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Components of a Modern Virtual AI Assistant áka AI Copilot</h2>



<p>By now you should have some idea of what modern virtual AI assistants are. Next, let&#8217;s look at the technical components that need to come together. </p>



<p>The illustration below displays the main components of an LLM-powered virtual AI assistant:</p>



<ul class="wp-block-list">
<li>A &#8211; Conversational UI for providing the user with a chat experience</li>



<li>B &#8211; LLMs such as GPT-3.5 or GPT-4 </li>



<li>C &#8211; Knowledge store for grounding your bot in enterprise data and dynamically providing few-shot examples. </li>



<li>D &#8211; Conversation logic for intent recognition and tracking conversations. </li>



<li>E &#8211; Application API as an interface to trigger and perform application functionality. </li>



<li>F &#8211; Cache for maintaining an instant mapping between often encountered user intents and structured LLM responses. </li>
</ul>



<p>Let&#8217;s look at these components in more detail.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="3531" height="2753" data-attachment-id="14173" data-permalink="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/virtual-assistant-architecture-components-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png" data-orig-size="3531,2753" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="virtual-assistant-architecture-components-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png" src="https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png" alt="" class="wp-image-14173" srcset="https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 3531w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 300w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 512w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 768w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 1536w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 2048w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 2475w" sizes="(max-width: 1237px) 100vw, 1237px" /></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h3 class="wp-block-heading">A) Conversational Application Frontend</h3>



<p>Incorporating virtual AI assistants into a software application or digital service often involves the use of a conversational user interface, typically embodied in a chat window that showcases previous interactions. The seamless integration of this interface as an intrinsic part of the application is vital.</p>



<p>A lot of applications employ a standard chatbot methodology, where the virtual AI assistant provides feedback to users in natural language or other forms of content within the chat window. Yet, a more dynamic and efficacious approach is to merge natural language feedback with alterations in the traditional user interface (UI). This dual approach not only enhances user engagement but also improves the overall user experience.</p>



<p>Microsoft&#8217;s M365 Copilot is a prime example of this approach. Instead of simply feeding responses back to the user in the chat window, the virtual assistant also manipulates elements in the traditional UI based on user input. It may highlight options, auto-fill data, or direct the user&#8217;s attention to certain parts of the screen. This combination of dynamic UI manipulation and natural language processing creates a more interactive and intuitive user experience, guiding the user toward their goal in a more efficient and engaging way.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="926" height="292" data-attachment-id="13999" data-permalink="https://www.relataly.com/?attachment_id=13999#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/07/image-5.png" data-orig-size="926,292" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-5" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/07/image-5.png" src="https://www.relataly.com/wp-content/uploads/2023/07/image-5.png" alt="Sample Copilot chat window in M365 Office" class="wp-image-13999" srcset="https://www.relataly.com/wp-content/uploads/2023/07/image-5.png 926w, https://www.relataly.com/wp-content/uploads/2023/07/image-5.png 300w, https://www.relataly.com/wp-content/uploads/2023/07/image-5.png 512w, https://www.relataly.com/wp-content/uploads/2023/07/image-5.png 768w" sizes="(max-width: 926px) 100vw, 926px" /><figcaption class="wp-element-caption">M365 Copilot chat window in M365 Office </figcaption></figure>



<p>When designing the UI for a virtual AI assistant, there are several key considerations. Firstly, the interface should be intuitive, ensuring users can easily navigate and understand how to interact with the AI. Secondly, the AI should provide feedback in a timely manner, so the user isn&#8217;t left waiting for a response. Thirdly, the system should be designed to handle errors gracefully, providing helpful error messages and suggestions when things don&#8217;t go as planned. Finally, the AI should keep the human in the loop and assist him in using AI in a safe way. </p>



<p>Also: <a href="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/" target="_blank" rel="noreferrer noopener">Building “Chat with your Data” Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore</a></p>



<h3 class="wp-block-heading">B) Large Language Model</h3>



<p>At the interface between users and assistant sits the large language mode. It translates users&#8217; requests and questions into code, actions, and responses that are shown to the user. Here, we are talking about foundational models like GPT-3.5-Turbo or GPT-4. In addition, if you are working with extensive content, you may use an embedding LLM that converts text or images into mathematical vectors as part of your knowledge store. An example, of such an embedding model, is ada-text-embeddings-002.</p>



<p>It&#8217;s important to understand that the user is not directly interacting with the LLM. Instead, you may want to put some control logic between the user and the LLM that steers the conversation. This logic can enrich prompts with additional data from the knowledge store or an online search API such as Google or Bing. This process of injecting data into a prompt depending on the user input is known as <a href="https://arxiv.org/abs/2005.11401" target="_blank" rel="noreferrer noopener">Retrieval Augmented Generation</a>. </p>



<p>Typical tasks performed by the LLM: </p>



<ul class="wp-block-list">
<li>Generating natural language responses based on the user’s query and the retrieved data from the knowledge store.</li>



<li>Recognizing and classifying user intent.</li>



<li>Generating code snippets (or API requests) that can be executed by the application or the user to achieve a desired outcome in your application.</li>



<li>Converting content into embeddings to retrieve relevant information from a vector-based knowledge store.</li>



<li>Generating summaries, paraphrases, translations, or explanations of the retrieved data or the generated responses.</li>



<li>Generating suggestions, recommendations, or feedback for the user to improve their experience or achieve their goals.</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h3 class="wp-block-heading">C) Knowledge Store</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Let&#8217;s dive into the &#8220;Knowledge Store&#8221; and why it&#8217;s vital. You might think feeding a huge prompt explaining app logic to your LLM, like ChatGPT, would work, but that&#8217;s not the case. As of June 2023, LLMs have context limits. For instance, GPT-3 can handle up to 4k tokens, roughly three pages of text. This limitation isn&#8217;t just for input, but output too. Hence, cramming everything into one prompt isn&#8217;t efficient or quick.</p>



<p>Instead, pair your LLM with a knowledge store, like a vector database (more on this in our article on <a href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/" target="_blank" rel="noreferrer noopener">Vector Databases</a>). Essentially, this is your system&#8217;s information storage, which efficiently retrieves data. Whichever storage you use, a search algorithm is crucial to fetch items based on user input. For vector databases, the typical way of doing this is by using similarity search.</p>



<p><strong>Token Limitations</strong></p>



<p>Curious about GPT models&#8217; token limits? Here&#8217;s a quick breakdown:</p>



<ul class="wp-block-list">
<li><strong>GPT-3.5-Turbo Model (4,000 tokens):</strong> About 7-8 DIN A4 pages</li>



<li><strong>GPT-4 Standard Model (8,000 tokens):</strong> Around 14-16 DIN A4 pages</li>



<li><strong>GPT-3.5-Turbo-16K Model (16,000 tokens):</strong> Approximately 28-32 DIN A4 pages</li>



<li><strong>GPT-4-32K Model (32,000 tokens):</strong> Estimated at 56-64 DIN A4 pages</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<p></p>
</div>
</div>



<h3 class="wp-block-heading">D) Conversation Control Logic</h3>



<p>Finally, the conversation needs a conductor to ensure it stays in harmony and doesn&#8217;t veer off the rails. This is the role of the conversation logic. An integral part of your app&#8217;s core software, the conversation logic bridges all the elements to deliver a seamless user experience. It includes several subcomponents. Meta prompts, for instance, help guide the conversation in the desired direction and provide some boundaries to the activities of the assistant. For example, the meta prompt may include a list of basic categories for intents that help the LLM with understanding what the user wants to do. </p>



<p>Another subcomponent is the connection to the knowledge store that allows the assistant to draw from a vast array of data to augment prompts handed over to the large language model. Moreover, the logic incorporates checks on the assistant&#8217;s activities and its generated content. These checks act like safety nets, mitigating risks and preventing unwanted outcomes. It&#8217;s akin to a quality control mechanism, keeping the assistant&#8217;s output in check and safeguarding against responses that might derail the user&#8217;s experience or even break the application.</p>



<h3 class="wp-block-heading">E) Application API</h3>



<p>Users expect their commands to initiate actions within your application. To fulfill these expectations, the application needs an API that can interact with various app functions. Consider the API as the nerve center of your app, facilitating access to its features and user journey. This API enables the AI assistant to guide users to specific pages, fill in forms, execute tasks, display information, and more. Tools like Microsoft Office even have their own language for this, while Python code, SQL statements, or generic REST requests usually suffice for most applications. </p>



<p>Applications based on a microservice architecture have an edge in this regard, as APIs are inherent to their design. If your application misses some APIs, remember, there&#8217;s no rush to provide access to all functions from the outset. You can start by supporting basic functionalities via chat and gradually expand over time. This allows you to learn from user interactions, continuously refine your offering, and ensure your AI assistant remains a useful and efficient tool for your users.</p>



<p>So, now that we&#8217;ve laid down the foundation, let&#8217;s buckle up and take a journey through the workflow of a modern virtual assistant. Trust me, it&#8217;s a fascinating trip ahead!</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h3 class="wp-block-heading">F) Cache</h3>



<p>Implementing a cache into your virtual AI assistant can significantly boost performance and decrease response times. Particularly useful for frequently recurring user intents, caching stores the outcomes of these intents for quicker access in future instances. However, a well-designed cache shouldn&#8217;t directly store specific inputs as there is too much variety in the human language. Instead, caching could be woven into the application&#8217;s logic in the mid-layers of your OpenAI prompt flow. </p>



<p>This strategy ensures frequently repeated intents are handled more swiftly, enhancing user experience. It&#8217;s critical to remember that cache integration is application-specific, and thoughtful design is vital to avoid unintentionally inducing inefficiencies.</p>



<p>While a well-implemented cache can speed up responses, it also introduces additional complexity. Effective cache management is crucial for avoiding resource drains, requiring strategies for data storage duration, updates, and purging.</p>



<p>The exact impact and efficiency of this caching strategy will depend on your application specifics, including the distribution and repetition of user intents. In the upcoming articles, we&#8217;ll explore this topic further, discussing efficient cache integration in AI assistant systems.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="467" height="156" data-attachment-id="14076" data-permalink="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/image-11-14/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/07/image-11.png" data-orig-size="467,156" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-11" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/07/image-11.png" src="https://www.relataly.com/wp-content/uploads/2023/07/image-11.png" alt="" class="wp-image-14076" srcset="https://www.relataly.com/wp-content/uploads/2023/07/image-11.png 467w, https://www.relataly.com/wp-content/uploads/2023/07/image-11.png 300w" sizes="(max-width: 467px) 100vw, 467px" /><figcaption class="wp-element-caption">An example of a caching technology would be <a href="https://redis.com/docs/caching-at-scale-with-redis/?utm_source=google&amp;utm_medium=cpc&amp;utm_term=cache&amp;utm_campaign=why_re-land_caching-cacheonly-emea-20125229738&amp;utm_content=why_re-eb-caching_at_scale_with_redis&amp;gclid=CjwKCAjwqZSlBhBwEiwAfoZUIIR30kfBaYLKfRO1ab0cxKcUB2og6UbR22oyogPcrj087B0CSp3TZRoC11gQAvD_BwE" target="_blank" rel="noreferrer noopener">Redis</a>.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Considerations on the Architecture of Virtual AI Assistants</h2>



<p>Designing an virtual AI assistant is an intricate process that blends cutting-edge technology with a keen understanding of user behavior. It&#8217;s about creating an efficient tool that not only simplifies tasks and optimizes workflows but also respects and preserves user autonomy. This section of our article will delve into the key considerations that guide the architecture of a virtual AI assistant. We&#8217;ll discuss the importance of user control, the strategic selection and use of GPT models, the benefits of starting simple, and the potential expansion as you gain confidence in your system&#8217;s stability and efficiency. As we journey through these considerations, remember the ultimate goal: creating a virtual AI assistant that augments user capabilities, enhances user experience, and breathes new life into software applications.</p>



<h3 class="wp-block-heading">Keep the User in Control</h3>



<p>At the heart of any virtual AI assistant should be the principle of user control. While automation can optimize tasks and streamline workflows, it is crucial to remember that your assistant is there to assist, not usurp. Balancing AI automation with user control is essential to crafting a successful user experience.</p>



<p>Take, for instance, the scenario of a user wanting to open a support ticket within your application. In this situation, your assistant could guide the user to the correct page, auto-fill known details like the user&#8217;s name and contact information, and even suggest possible problem categories based on the user&#8217;s descriptions. By doing so, the virtual AI assistant has significantly simplified the process for the user, making it quicker and less burdensome.</p>



<p>However, the user retains control throughout the process, making the final decisions. They can edit the pre-filled details, choose the problem category, and write the issue description in their own words. They&#8217;re in command, and the virtual AI assistant is there to assist, helping to avoid errors, speed up the process, and generally make the experience smoother and more efficient.</p>



<p>This balance between user control and AI assistance is not only about maintaining a sense of user agency; it is also about trust. Users need to trust that the AI is there to help them, not to take control away from them. If the AI seems too controlling or makes decisions that the user disagrees with, this can erode trust and hinder user acceptance.</p>



<h3 class="wp-block-heading">Mix and Match Models</h3>



<p>Another crucial consideration is the use of different GPT models. Each model comes with its own set of strengths, weaknesses, response times, costs, and token limits. It&#8217;s not just about capabilities. Sometimes, it&#8217;s unnecessary to deploy a complex GPT-4 model for simpler tasks in your workflow. Alternatives like ADA or GPT 3.5 Turbo might be more suitable and cost-effective for functions like intent recognition.</p>



<p>Reserve the heavy-duty models for tasks requiring an extended token limit or dealing with complex operations. One such task is the final-augmented prompt that creates the API call. If you&#8217;re working with a vector database, you&#8217;ll also need an embedding model. Be mindful that these models come with different vector sizes, and once you start building your database with a specific size, it can be challenging to switch without migrating your entire vector content.</p>



<h3 class="wp-block-heading">Think Big but Start Simple </h3>



<p>It&#8217;s always a good idea to start simple &#8211; maybe with a few intents to kick things off. As you gain experience and confidence in building virtual assistant apps, you can gradually integrate additional intents and API calls. And don&#8217;t forget to keep your users involved! Consider incorporating a feedback mechanism, allowing users to report any issues and suggest improvements. This will enable you to fine-tune your prompts and database content effectively.</p>



<p>As your application becomes more comprehensive, you might want to explore model fine-tuning for specific tasks. However, this step should be considered only when your virtual AI assistant functionality has achieved a certain level of stability. Fine-tuning a model can be quite costly, especially if you decide to change the intent categories after training.</p>



<h2 class="wp-block-heading">Digital LLM-based Assistants &#8211; A Major Business Opportunity</h2>



<p>From a business standpoint, upgrading software products and services with LLM-powered virtual AI assistants presents a significant opportunity to differentiate in the market and even innovate their business model. Many organizations are already contemplating the inclusion of virtual assistants as part of subscription packages or premium offerings. As the market evolves, software lacking a natural language interface may be perceived as outdated and struggle to compete.</p>



<p>AI-powered virtual assistants are likely to inspire a whole new generation of software applications and enable a new wave of digital innovations. By enhancing convenience and efficiency in user inputs, virtual assistants unlock untapped potential and boost productivity. Moreover, they empower users to fully leverage the diverse range of features offered by software applications, which often remain underutilized.</p>



<p>I strongly believe that LLM-driven virtual AI assistants are the next milestone in software design and will revolutionize software applications across industries. And remember, this is just the first generation of virtual assistants. The future possibilities are virtually endless and we can&#8217;t wait to see what&#8217;s next! Indeed, the emergence of natural language interfaces is expected to trigger a ripple effect of subsequent innovations, for example, in areas such as standardization, workflow automation, and user experience design.</p>



<h2 class="wp-block-heading">Summary</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>In this article, we delved into the fascinating world of virtual AI assistants, powered by LLMs. We started by exploring how the advanced language understanding of LLMs is revolutionizing software design, easing the workload of developers, and reshaping user experiences with technology.</p>



<p>Next, we provided an overview of the key architectural components of a modern virtual AI assistant: the <strong>Conversational Application Frontend</strong>, <strong>Large Language Model</strong>, <strong>Knowledge Store</strong>, and <strong>Conversation Control Logic</strong>. We also introduced the concept of an <strong>Application API </strong>and the novel idea of a <strong>Cache </strong>for storing and quickly retrieving common user intents. Each component was discussed in the context of their roles and how they work together to create a seamless, interactive, and efficient user experience.</p>



<p>We then discussed architecture considerations, emphasizing the necessity of maintaining user control while leveraging the power of AI automation. We talked about the judicious use of different GPT models based on task requirements, the advantages of starting with simple implementations and progressively scaling up, and the benefits of user feedback in continuously refining the system.</p>



<p>This journey of &#8216;AI in Software Applications&#8217;, from concept to reality, isn&#8217;t just about innovation. It&#8217;s about unlocking &#8216;Innovative Business Models with AI&#8217; and boosting user engagement and productivity. As we continue to ride the wave of &#8216;Natural Language Processing for Software Automation&#8217;, the opportunities for harnessing the power of virtual AI assistants are endless. Stay tuned as we explore the workflows further in the next article.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="289" data-attachment-id="14071" data-permalink="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png" data-orig-size="1426,806" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png" src="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1-512x289.png" alt="A mechanic working on an airplace engine" class="wp-image-14071" srcset="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png 512w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png 300w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png 768w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png 1426w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">In this article, we have gone through the components of an LLM-powered virtual assistant aka &#8220;AI copilot&#8221;. In the next article, we will dive deeper into the processing logic and follow a prompt into the engine of an intelligent assistant. </figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<ul class="wp-block-list">
<li><a href="https://arxiv.org/pdf/2306.03460.pdf" target="_blank" rel="noreferrer noopener">Natural Language Commanding via Program Synthesis</a></li>



<li><a href="https://en.wikipedia.org/wiki/Office_assistant" target="_blank" rel="noreferrer noopener">Wikipedia.org/Office Assistant</a></li>



<li><a href="https://blogs.microsoft.com/blog/2023/03/16/introducing-microsoft-365-copilot-your-copilot-for-work/" target="_blank" rel="noreferrer noopener">Microsoft Blogs &#8211; Introducing Microsoft 365 Copilot</a></li>



<li><a href="https://www.reuters.com/technology/sap-ceo-huge-growth-potential-generative-ai-2023-06-28/" target="_blank" rel="noreferrer noopener">Reuters &#8211; Sap CEO Huge Growth Potential in Generative AI</a></li>



<li><a href="https://news.microsoft.com/source/features/ai/microsoft-outlines-framework-for-building-ai-apps-and-copilots-expands-ai-plugin-ecosystem/" target="_blank" rel="noreferrer noopener">Microsoft Outlines Framework for Building AI Apps and Copilots, Expands AI Plugin Ecosystem</a></li>



<li><a href="https://workspace.google.com/blog/product-announcements/generative-ai?hl=en" target="_blank" rel="noreferrer noopener">Google Announces Digital Assistants in their Worksuite</a></li>



<li><a href="https://www.youtube.com/watch?v=B2-8wrF9Okc" target="_blank" rel="noreferrer noopener">Youtube, Microsoft Mechanics &#8211; How Microsoft 365 Copilot works</a></li>



<li><a href="https://www.youtube.com/watch?v=VlM9a469LE0" target="_blank" rel="noreferrer noopener">Youtube, Lisa Crosby &#8211; Microsoft 365 Copilot Explained: How Microsoft Just Changed the Future of Work</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/">Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">14056</post-id>	</item>
		<item>
		<title>Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore</title>
		<link>https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/</link>
					<comments>https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sat, 27 May 2023 13:25:08 +0000</pubDate>
				<category><![CDATA[ChatBots]]></category>
		<category><![CDATA[Clustering]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Generative AI]]></category>
		<category><![CDATA[Healthcare]]></category>
		<category><![CDATA[Insurance]]></category>
		<category><![CDATA[Language Generation]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Marketing Automation]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Prompt Engineering]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Sentiment Analysis]]></category>
		<category><![CDATA[Use Cases]]></category>
		<category><![CDATA[Vector Databases]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=13687</guid>

					<description><![CDATA[<p>Artificial Intelligence (AI), in particular, the advent of OpenAI&#8217;s ChatGPT, has revolutionized how we interact with technology. Chatbots powered by this advanced language model can engage users in intricate, natural language conversations, marking a significant shift in AI capabilities. However, one thing that ChatGPT isn&#8217;t designed for is integrating personalized or proprietary knowledge – it&#8217;s ... <a title="Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore" class="read-more" href="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/" aria-label="Read more about Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore">Read more</a></p>
<p>The post <a href="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/">Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Artificial Intelligence (AI), in particular, the advent of OpenAI&#8217;s ChatGPT, has revolutionized how we interact with technology. Chatbots powered by this advanced language model can engage users in intricate, natural language conversations, marking a significant shift in AI capabilities. However, one thing that ChatGPT isn&#8217;t designed for is integrating personalized or proprietary knowledge – it&#8217;s built to draw upon general knowledge, not specifics about you or your organization. That&#8217;s where the concept of Retrieval Augmented Generation (RAG) comes into play. This article explores the exciting prospect of building your own ChatGPT that lets users ask questions on a custom knowledge base.</p>



<p>In this tutorial, we&#8217;ll unveil the mystery behind enterprise ChatGPT, guiding you through the process of creating your very own custom ChatGPT &#8211; an AI-powered chatbot based on OpenAI&#8217;s powerful Generative Pretrained Transformers (GPT) technology. We&#8217;ll use Python and delve into the world of <a href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/" target="_blank" rel="noreferrer noopener">vector databases</a>, specifically, <a href="https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/introduction" target="_blank" rel="noreferrer noopener">Mongo API for Azure Cosmos DB</a>, to show you how you can make a large knowledgebase available to ChatGPT that can go way beyond the <a href="https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them" target="_blank" rel="noreferrer noopener">typical token limitation of GPT models</a>.</p>



<p>For experts, AI fans, or tech newbies, this guide simplifies building your ChatGPT. With clear instructions, useful examples, and tips, we aim to make it informative and empowering.</p>



<p>We&#8217;ll explore AI, showing you how to customize your chatbot. We&#8217;ll simplify complex concepts and show you how to start your AI adventure from home or office. Ready to start this exciting journey? Keep reading!</p>



<p>Also: </p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/how-to-build-a-twitter-news-bot-with-openai-and-newsapi/13581/" target="_blank" rel="noreferrer noopener">How to Build a Twitter News Bot with OpenAI ChatGPT and NewsAPI in Python</a></li>



<li><a href="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/" target="_blank" rel="noreferrer noopener">From Pirates to Nobleman: Simulating Conversations between Various Characters using OpenAI’s ChatGPT and Python</a></li>
</ul>



<h2 class="wp-block-heading">Note on the use of Vector DBs and Costs.</h2>



<p>Please note that this tutorial describes a business use case that utilizes a Cosmos DB for Mongo DB vCore hosted on the Azure cloud. </p>



<p>Alternatively, you can set up an open-source vector database on your local machine, such as Milvus. Be aware that certain code adjustments will be necessary to proceed with the open-source alternative. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading" id="h-why-custom-chatgpt-is-so-powerful-and-versatile">Why Custom ChatGPT is so Powerful and Versatile</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>I believe we have all tested ChatGPT, and probably like me, you have been impressed by its remarkable capabilities. However, ChatGPT has a significant limitation: it can only answer questions and perform tasks based on the public knowledge base it was trained on. </p>



<p>Imagine having a chatbot based on ChatGPT that communicates effectively and truly understands the nuances of your business, sector, or even a particular topic of interest. That&#8217;s the power of a custom ChatGPT. A tailor-made chatbot allows for specialized conversations, providing the needed information and drawing from a unique database you&#8217;ve developed. </p>



<p>This becomes particularly beneficial in industries with specific terminologies or when you have a large database of knowledge that you want to make easily accessible and interactive. A custom ChatGPT, with its personalized and relevant responses, ensures a better user experience, effectively saving time and increasing productivity. </p>



<p>Let&#8217;s delve into how to build such a solution. Spoiler it does not work by putting all the content into the prompt. But there is a great alternative. </p>



<h2 class="wp-block-heading">Understanding the Building Blocks of Custom ChatGPT with Retrieval Augmented Generation</h2>



<p>The foundational technology behind ChatGPT is OpenAI&#8217;s Generative Pre-trained Transformer models (GPT). These models understand language by predicting the next word in a sentence and are trained on a diverse range of internet text. However, the GPT models, such as the GPT-3.5, have a limitation of processing 4096 tokens at a time. A token in this context is a chunk of text which can be as small as one character or as long as one word. For example, the phrase &#8220;ChatGPT is great&#8221; is four tokens long.</p>



<p>Another challenge with Foundation Models such as ChatGPT is that they are trained on large-scale datasets that were available at the time of their training. This means they are not aware of any data created after their training period. Also, because they&#8217;re trained on broad, general-domain datasets, they may be less effective for tasks requiring domain-specific knowledge.</p>



<h3 class="wp-block-heading">How Retrieval Augmented Generation (RAG) Helps </h3>



<p>Retrieval-Augmented Generation (RAG) is a method that combines the strength of transformer models with external knowledge to augment their understanding and applicability. Here&#8217;s a brief explanation:</p>



<p>To address this, RAG retrieves relevant information from an external data source and uses this information to augment the input to the foundation model. This can make the model&#8217;s responses more informed and relevant.</p>



<h3 class="wp-block-heading">Data Sources</h3>



<p>The external data can come from various sources like databases, document repositories, or APIs. To make this data compatible with the RAG approach, both the data and user queries are converted into numerical representations (embeddings) using language models.</p>



<h3 class="wp-block-heading">Data Preparation as Embeddings</h3>



<p>The embeddings, which are essentially vectors, need to be stored in a database that&#8217;s efficient at storing and searching through these high-dimensional data. This is where Azure&#8217;s Cosmos Mongo DB comes into play. It&#8217;s a vector search database specifically designed for this task.</p>



<p>To circumvent the token limitation and make your extensive data available to ChatGPT, we turn the data into embeddings. These are mathematical representations of your data, converting words, sentences, or documents into vectors. The advantage of using embeddings is that they capture the semantic meaning of the text, going beyond keywords to understand the context. In essence, similar information will have similar vectors, allowing us to cluster related information together and separate them from a semantically different text.</p>



<h3 class="wp-block-heading">Storing the Data in Vector Databases</h3>



<p>The embeddings, which are essentially vectors, need to be stored in a database that&#8217;s efficient at storing and searching through these high-dimensional data. This is where Azure&#8217;s Cosmos Mongo DB comes into play. It&#8217;s a vector search database specifically designed for this task.</p>



<h3 class="wp-block-heading">Matching Queries to Knowledge</h3>



<p>The RAG model compares the embeddings of user queries with those in the knowledge base to identify relevant information. The user&#8217;s original query is then augmented with context from similar documents in the knowledge base.</p>



<h3 class="wp-block-heading">Input to the Foundation Model</h3>



<p>This augmented input is sent to the foundation model, enhancing its understanding and response quality.</p>



<h3 class="wp-block-heading">Updates</h3>



<p>Importantly, the knowledge base and associated embeddings can be updated asynchronously, ensuring that the model remains up-to-date even as new information is added to the data sources.</p>



<p>In sum, RAG extends the utility of foundation models by incorporating external, up-to-date, domain-specific knowledge into their understanding and output.</p>



<p>By incorporating these components, you&#8217;ll be creating a robust custom ChatGPT that not only understands the user&#8217;s queries but also has access to your own information, giving it the ability to respond with precision and relevance. </p>



<p>Ready to dive into the technicalities? Stay tuned!</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="277" data-attachment-id="13775" data-permalink="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/flo7up_a_vector_database_colorful_popart_with_an_ai_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-copy-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png" data-orig-size="1432,776" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png" src="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min-512x277.png" alt="A tailor-made chatbot allows for specialized conversations, providing the exact information needed, drawing from a unique database that you've developed. " class="wp-image-13775" srcset="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png 1432w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">A tailor-made chatbot allows for specialized conversations, providing the exact information needed, drawing from a unique database that you&#8217;ve developed. </figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Building the Custom &#8220;Chat with Your Data&#8221; App in Python</h2>



<p>Now that we&#8217;ve discussed the theory behind building a custom ChatGPT and seen some exciting real-world applications, it&#8217;s time to put our knowledge into action! In this practical segment of our guide, we&#8217;re going to demonstrate how you can build a custom ChatGPT solution using Python.</p>



<p>Our project will involve storing a sample PDF document in Cosmos Mongo DB and developing a chatbot capable of answering questions based on the content of this document. This practical exercise will guide you through the entire process, including turning your PDF content into embeddings, storing these embeddings in the Cosmos Mongo DB, and finally integrating it all with ChatGPT to build an interactive chatbot.</p>



<p>If you&#8217;re new to Python, don&#8217;t worry, we&#8217;ll be breaking down the code and explaining each step in a straightforward manner. Let&#8217;s roll up our sleeves, fire up our Python environments, and get coding! Stay tuned as we embark on this exciting hands-on journey into the world of custom chatbots.</p>



<p>The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_c8e02b-b1"><a class="kb-button kt-button button kb-btn_022d60-c9 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/300%20Distributed%20Computing%20-%20Analyzing%20Zurich%20Weather%20Data%20using%20PySpark.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_8db802-ce kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">How to Set Up Vector Search in Cosmos DB</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>First, you must understand that you will need a database to store the embeddings. It does not necessarily have to be a vector database. Still, this type of database will make your solution more performant and robust, particularly when you want to store large amounts of data.</p>



<p><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/vcore/" target="_blank" rel="noreferrer noopener">Azure Cosmos DB for MongoDB vCore</a> is the first MongoDB-compatible offering to feature Vector Search. With this feature, you can store, index, and query high-dimensional vector data directly in Azure Cosmos DB for MongoDB vCore, eliminating the need for data transfer to alternative platforms for vector similarity search capabilities. Here are the steps to set it up:</p>



<ol class="wp-block-list">
<li><strong>Choose Your Azure Cosmos DB Architecture:</strong> Azure Cosmos DB for MongoDB provides two types of architectures, RU-based and vCore-based. Each has its strengths and is best suited for certain types of applications. Choose the one that best fits your needs. If you&#8217;re looking to lift and shift existing MongoDB apps and run them as-is on a fully supported managed service, the vCore-based option could be the perfect fit.</li>



<li><strong>Configure Your Vector Search:</strong> Once your database architecture is set up, you can integrate your AI-based applications, including those using OpenAI embeddings, with your data already stored in Cosmos DB.</li>



<li><strong>Build and Deploy Your AI Application:</strong> With the Vector Search set up, you can now build your AI application that takes advantage of this feature. You can create a Go app using Azure Cosmos DB for MongoDB or deploy Azure Cosmos DB for MongoDB vCore using a Bicep template as suggested next steps.</li>
</ol>



<p>Azure Cosmos DB for MongoDB vCore&#8217;s Vector Search feature is a game-changer for AI application development. It enables you to unlock new insights from your data, leading to more accurate and powerful applications.</p>



<h2 class="wp-block-heading">Cosmos DB for Mongo DB Usage Models</h2>



<p>Regarding <a href="https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/choose-model" target="_blank" rel="noreferrer noopener">Cosmos DB for Mongo DB</a>, there are two options to choose from: Request Unit (RU) Database Account and vCore Cluster. Each option follows a different pricing model to suit diverse needs.</p>



<p>The Request Unit (RU) Database Account operates on a pay-per-use basis. With this model, you are billed based on the number of requests and the level of provisioned throughput consumed by your workload.</p>



<p>As of 27th Mai 2023, <a href="https://devblogs.microsoft.com/cosmosdb/introducing-vector-search-in-azure-cosmos-db-for-mongodb-vcore/" target="_blank" rel="noreferrer noopener">the brand new vector search function is only available for the vCore Cluster option</a>, which is why we will use this setup for this tutorial. The vCore Cluster offers a reserved managed instance. Under this option, you are charged a fixed amount on a monthly basis, providing more predictable costs for your usage.</p>



<p>Once you have created your vCore instance, you must collect your connection string and make it available to your Python script. You can do this either by storing it in <a href="https://azure.microsoft.com/en-us/products/key-vault/">Azure Key Vault</a> (which I would recommend) or by storing it locally on your computer or in the code (which I would not recommend for obvious security reasons).</p>



<figure class="wp-block-image size-full"><img decoding="async" width="1536" height="588" data-attachment-id="13774" data-permalink="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/image-7-6/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/image-7.png" data-orig-size="1536,588" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-7" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/image-7.png" src="https://www.relataly.com/wp-content/uploads/2023/05/image-7.png" alt="" class="wp-image-13774" srcset="https://www.relataly.com/wp-content/uploads/2023/05/image-7.png 1536w, https://www.relataly.com/wp-content/uploads/2023/05/image-7.png 300w, https://www.relataly.com/wp-content/uploads/2023/05/image-7.png 512w, https://www.relataly.com/wp-content/uploads/2023/05/image-7.png 768w" sizes="(max-width: 1237px) 100vw, 1237px" /><figcaption class="wp-element-caption">When it comes to Cosmos DB for Mongo DB, there are two options to choose from: Request Unit (RU) Database Account and vCore Cluster. </figcaption></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="334" height="512" data-attachment-id="13772" data-permalink="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/image-5-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/image-5.png" data-orig-size="606,929" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-5" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/image-5.png" src="https://www.relataly.com/wp-content/uploads/2023/05/image-5-334x512.png" alt="Azure Cosmos DB for Mongo DB is a new offering that is specifically designed for vector use cases (incl. embeddings)" class="wp-image-13772" srcset="https://www.relataly.com/wp-content/uploads/2023/05/image-5.png 334w, https://www.relataly.com/wp-content/uploads/2023/05/image-5.png 196w, https://www.relataly.com/wp-content/uploads/2023/05/image-5.png 606w" sizes="(max-width: 334px) 100vw, 334px" /><figcaption class="wp-element-caption">Azure Cosmos DB for Mongo DB is a new offering that is designed explicitly for vector use cases (incl. embeddings)</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Using other Vector Databases</h2>



<p>While Cosmos DB is a popular choice for vector databases, I would like to note that other options are available in the market. You can still benefit from this tutorial if you decide to utilize a different vector database, such as Pinncecone or Chroma. However, it is necessary to make code adjustments tailored to the APIs and functionalities of the specific vector database you choose.</p>



<p>Specifically, you will need to modify the &#8220;insert embedding functions&#8221; and &#8220;similarity search functions&#8221; to align with the requirements and capabilities of your chosen vector database. These functions typically have variations that are specific to each vector database.</p>



<p>By customizing the code according to your selected vector database&#8217;s API, you can successfully adapt the tutorial to suit your specific database choice. This allows you to leverage the principles and concepts this tutorial covers, regardless of the vector database you opt for.</p>



<p>Also: <a href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/" target="_blank" rel="noreferrer noopener">Vector Databases: The Rising Star in Generative AI Infrastructure</a></p>



<h3 class="wp-block-heading">Prerequisites</h3>



<p>Before diving into the code, it’s essential to ensure that you have the proper setup for your Python 3 environment and have installed all the necessary packages. If you do not have a Python environment, follow the instructions in&nbsp;<a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a>&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda Python environment</a>. This will provide you with a robust and versatile environment well-suited for machine learning and data science tasks.</p>



<p>In this tutorial, we will be working with several libraries:</p>



<ul class="wp-block-list">
<li>openai</li>



<li>pymongo</li>



<li>PyPDF2</li>



<li>dotenv</li>
</ul>



<p>Should you decide to use <a href="https://azure.microsoft.com/en-us/products/key-vault/" target="_blank" rel="noreferrer noopener">Azure Key Vault</a>, then you also need the following Python libraries:</p>



<ul class="wp-block-list">
<li>azure-identity</li>



<li>azure-key-vault</li>
</ul>



<p>You can install the OpenAI Python library using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install&nbsp;</em>openai</li>



<li><em>conda install&nbsp;</em>openai&nbsp;(if you are using the Anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading">Step #1 Authentification and DB Setup</h3>



<p>Let&#8217;s start with the authentification and setup of the API keys. After making necessary imports, the code gets things read to connect to essential services &#8211; OpenAI and Cosmos DB &#8211; and makes sure it can access these services properly.</p>



<ol class="wp-block-list">
<li><strong>Fetching Credentials:</strong> The script starts by setting up a connection to a service called Azure Key Vault to retrieve some crucial credentials securely. These are like &#8220;passwords&#8221; that the script needs to access various resources.</li>



<li><strong>Setting Up AI Services:</strong> Then, it prepares to connect to two different AI services. One is a version that&#8217;s hosted by Azure, and the other is the standard, public version.</li>



<li><strong>Establishing Database Connection:</strong> Lastly, the script sets up a connection to a database service, specifically to a certain collection within the Cosmos DB database. The script also checks if the connection to the database was successful by sending a &#8220;ping&#8221; &#8211; if it receives a response, it knows the connection is good.</li>
</ol>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">from azure.identity import AzureCliCredential
from azure.keyvault.secrets import SecretClient
import openai
import logging
import tiktoken
import pandas as pd
import pymongo
from dotenv import load_dotenv
load_dotenv()
# Set up the Azure Key Vault client and retrieve the Blob Storage account credentials
keyvault_name = ''
openaiservicename = ''
client = SecretClient(f&quot;https://{keyvault_name}.vault.azure.net/&quot;, AzureCliCredential())
print('keyvault service ready')
# AzureOpenAI Service
def setup_azureopenai():
    openai.api_key = client.get_secret('openai-api-key').value
    openai.api_type = &quot;azure&quot;
    openai.api_base = f'https://{openaiservicename}.openai.azure.com'
    openai.api_version = '2023-05-15'
    print('azure openai service ready')
# public openai service
def setup_public_openai():
    openai.api_key = client.get_secret('openai-api-key-public').value
    print('public openai service ready')
DB_NAME = &quot;hephaestus&quot;
COLLECTION_NAME = 'isocodes'
def setup_cosmos_connection():
    COSMOS_CLUSTER_CONNECTION_STRING = client.get_secret('cosmos-cluster-string').value
    cosmosclient = pymongo.MongoClient(COSMOS_CLUSTER_CONNECTION_STRING)
    db = cosmosclient[DB_NAME]
    collection = cosmosclient[DB_NAME][COLLECTION_NAME]
    # Send a ping to confirm a successful connection
    try:
        cosmosclient.admin.command('ping')
        print(&quot;Pinged your deployment. You successfully connected to MongoDB!&quot;)
    except Exception as e:
        print(e)
    return collection, db
setup_public_openai()
collection, db = setup_cosmos_connection()</pre></div>



<p>Now we have set things up to interact with our Cosmos DB Mong DB vCore instance.</p>



<h3 class="wp-block-heading">Step #2 Functions for Populating the Vector DB</h3>



<p>Next, we prepare and insert data into the database as embeddings. First, we prepare the content. The preparation process involves turning the text content into embeddings. Each embedding is a list of flats representing the meaning of a specific part of the text in a way the AI system can understand.</p>



<p>We create the embeddings by sending text (for example, a paragraph of a document) to an OpenAI embedding model that returns the embedding. There are two options for using OpenAI: You can use the Azure OpenAI engine and deploy your own Ada embedding model. Alternatively, you can use the public OpenAI Ada embedding model. </p>



<p>We&#8217;ll use the public OpenAI&#8217;s <a href="https://platform.openai.com/docs/guides/embeddings" target="_blank" rel="noreferrer noopener">text-embedding-ada-002</a>. Remember that the model is designed to return embeddings, not text. Model inference may incur costs based on the data processed. Refer to <a href="https://openai.com/pricing" target="_blank" rel="noreferrer noopener">OpenAI </a>or Azure OpenAI service for pricing details. </p>



<p>Finally, the code inserts the prepared requests (which now include both the original text and the corresponding embeddings) into the database. The function returns the unique IDs assigned to these newly inserted items in the database. In this way, the code processes and stores the necessary information in the database for later use.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># prepare content for insertion into cosmos db
def prepare_content(text_content):
  embeddings = create_embeddings_with_openai(text_content)
  request = [
    {
    &quot;textContent&quot;: text_content, 
    &quot;vectorContent&quot;: embeddings}
  ]
  return request
# create embeddings
def create_embeddings_with_openai(input):
    #print('Generating response from OpenAI...')
    ###### uncomment for AzureOpenAI model usage and comment code below
    # embeddings = openai.Embedding.create( 
    #     engine='&lt;name of the embedding deployment &gt;', 
    #     input=input)[&quot;data&quot;][0][&quot;embedding&quot;]
    ###### public openai model usage and comment code above
    embeddings = openai.Embedding.create(
        model='text-embedding-ada-002', 
        input=input)[&quot;data&quot;][0][&quot;embedding&quot;]
    
    # Number of embeddings    
    # print(len(embeddings))
    return embeddings
# insert the requests
def insert_requests(text_input):
    request = prepare_content(text_input)
    return collection.insert_many(request).inserted_ids
# Creates a searchable index for the vector content
def create_index():
  
  # delete and recreate the index. This might only be necessary once.
  collection.drop_indexes()
  embedding_len = 1536
  print(f'creating index with embedding length: {embedding_len}')
  db.command({
    'createIndexes': COLLECTION_NAME,
    'indexes': [
      {
        'name': 'vectorSearchIndex',
        'key': {
          &quot;vectorContent&quot;: &quot;cosmosSearch&quot;
        },
        'cosmosSearchOptions': {
          'kind': 'vector-ivf',
          'numLists': 100,
          'similarity': 'COS',
          'dimensions': embedding_len
        }
      }
    ]
  })
# Resets the DB and deletes all values from the collection to avoid dublicates
#collection.delete_many({})</pre></div>



<h3 class="wp-block-heading">Step #3 Document Cracing and Populating the DB</h3>



<p>The next step is to break down the PDF document into smaller chunks of text (in this case, &#8216;records&#8217;) and then process these records for future use. You can repeat this process for any document that you want to make available to OpenAI. </p>



<p>You can use any PDF that you like as long as you it contains readable text (use OCR). For demo purposes, I will use a <a href="https://www.zh.ch/content/dam/zhweb/bilder-dokumente/themen/steuern-finanzen/steuern/quellensteuer/infobl%C3%A4tter/div_q_informationsblatt_qs_2021_EN.pdf" target="_blank" rel="noreferrer noopener">tax document from Zurich</a>. Put the document in the folder data/vector_db_data/ in your root folder and provide the name to the Python script. </p>



<p>Want to read in many documents at once? If you want to insert many documents, read the pdf documents from the folder and use the names to populate a list. You can then surround the insert function with a for loop that iterates through the list of document names </p>



<h4 class="wp-block-heading">#3.1 Document Slicing Considerations </h4>



<p>To convert a PDF into embeddings, the first step is to divide it into smaller content slices. The slicing process plays a crucial role as it affects the information provided to the OpenAI GPT model when answering user questions. If the slices are too large, the model may encounter token limitations. Conversely, if they are too small, the model may not receive sufficient content to answer the question effectively. It is important to strike a balance between the number of slices and their length to optimize the results, considering that the search process may yield multiple outcomes.</p>



<p>There are several approaches to handle the slicing process. One option is to define the slices based on a specific number of sentences or paragraphs. Alternatively, you can iteratively slice the document, allowing for some overlap between the data in the vector database. This approach has the advantage of providing more precise information to answer questions, but it also increases the data volume in the vector database, which can impact speed and cost considerations.</p>



<h4 class="wp-block-heading">#3.2 Running the code below to crack a document and insert embeddings into the vector DB</h4>



<p>Running the code below will first define a function that breaks text into separate paragraphs based on line breaks. Another function slices the PDF into records. Each record contains a certain number of sentences (the maximum is defined by the &#8216;max_sentences&#8217; value). We use a Python library called PyPDF2 to extract text from each page of the PDF and Python&#8217;s built-in regular expressions to split the text into sentences and paragraphs. Note that if you want to achieve better results, you could also use a professional document content extraction tool such as Azure form recognizer.</p>



<p>The code then opens a specific PDF file (&#8216;zurich_tax_info_2023.pdf&#8217;) and slices it into records, each containing no more than a certain number of sentences (as defined by&#8217;max_sentences&#8217;). After that, the function inserts these records into the vector database. Finally, we print the count of documents in the database collection. This shows how many pieces of data are already stored in this specific part of the database.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># document cracking function to insert data from the excel sheet
def split_text_into_paragraphs(text):
    paragraphs = re.split(r'\n{2,}', text)
    return paragraphs
def slice_pdf_into_records(pdf_path, max_sentences):
    records = []
    
    with open(pdf_path, 'rb') as file:
        reader = PyPDF2.PdfReader(file)
        
        for page in reader.pages:
            text = page.extract_text()
            paragraphs = split_text_into_paragraphs(text)
            
            current_record = ''
            sentence_count = 0
            
            for paragraph in paragraphs:
                sentences = re.split(r'(?&lt;=[.!?])\s+', paragraph)
                
                for sentence in sentences:
                    current_record += sentence
                    
                    sentence_count += 1
                    
                    if sentence_count &gt;= max_sentences:
                        records.append(current_record)
                        current_record = ''
                        sentence_count = 0
                
                if sentence_count &lt; max_sentences:
                    current_record += ' '  # Add space between paragraphs
            
            # If there is remaining text after the loop, add it as a record
            if current_record:
                records.append(current_record)
    
    return records
# get file from root/data folder
pdf_path = '../data/vector_db_data/zurich_tax_info_2023.pdf'
max_sentences = 20  # Adjust the slice size as per your requirement
result = slice_pdf_into_records(pdf_path, max_sentences)
# print the length of result
print(f'{len(result)} vectors created with maximum {max_sentences} sentences each.')
# Print the sliced records
for i, record in enumerate(result):
    insert_requests(record)
    if i &lt; 5:
        print(record[0:100])
        print('-------------------')
create_index()
print(f'number of records in the vector DB: {collection.count_documents({})}')</pre></div>



<p>After slicing the document and inserting the embeddings into the vector database, we can proceed with functions for similarity search and prompting. </p>



<h3 class="wp-block-heading">Step #4 Functions for Similarity Search and Prompts to ChatGPT</h3>



<p>This section of code provides a set of functions to perform a vector search in the Cosmos DB, make a request to the ChatGPT 3.5 Turbo model for generating responses, and create prompts for the OpenAI model to use in generating those responses.</p>



<h4 class="wp-block-heading">#4.1 How the Search Part Works </h4>



<p><br>Allow me to provide a concise explanation of how the search process operates. We have now reached the stage where a user poses a question, and we utilize the OpenAI model to supply an answer, drawing from our vector database. Here, it&#8217;s vital to understand that the model transforms the question into embeddings and subsequently scours the knowledge base for similar embeddings that align with the information requested in the user&#8217;s prompt. </p>



<p>The vector database yields the most suitable results and inserts them into another prompt tailored for ChatGPT. This model, distinct from the embedding model, generates text. Thus, the final interaction with the ChatGPT model incorporates both the user&#8217;s question and the results from the vector database, which are the most fitting responses to the question. This combination should ideally aid the model in providing the appropriate answer. Now, let&#8217;s turn our attention to the corresponding code.</p>



<h4 class="wp-block-heading">#4.2 Setting up the Functions for Vector Search</h4>



<p>The vector_search function takes as input a query vector (representing a user&#8217;s question in vector form) and an optional parameter to limit the number of results. It then conducts a search in the Cosmos DB, looking for entries whose vector content is most similar to the query vector.</p>



<p>Next, the openai_request function makes a request to OpenAI&#8217;s ChatGPT 3.5 Turbo model to generate a response. This function takes a formatted conversation history (or &#8216;prompt&#8217;) and sends it to the model, which then generates a response. The content of the generated response is then returned.</p>



<p>The create_tweet_prompt function constructs the conversation history for the OpenAI model. This function takes the user&#8217;s question and a JSON object containing results from a database search and constructs a list of system and user messages. This list will then serve as the prompt for the ChatGPT model, instructing it to generate a response that answers the user&#8217;s question about tax, with the added guideline that the response should be in the same language as the question. The constructed prompt is then returned by the function.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Cosmos DB Vector Search API Command
def vector_search(vector_query, max_number_of_results=2):
  results = collection.aggregate([
    {
      '$search': {
        &quot;cosmosSearch&quot;: {
          &quot;vector&quot;: vector_query,
          &quot;path&quot;: &quot;vectorContent&quot;,
          &quot;k&quot;: max_number_of_results
        },
      &quot;returnStoredSource&quot;: True
      }
    }
  ])
  return results
# openAI request - ChatGPT 3.5 Turbo Model
def openai_request(prompt, model_engine='gpt-3.5-turbo'):
    completion = openai.ChatCompletion.create(model=model_engine, messages=prompt, temperature=0.2, max_tokens=500)
    return completion.choices[0].message.content
# define OpenAI Prompt for News Tweet
def create_prompt(user_question, result_json):
    instructions = f'You are an assistant that answers questions based on sources provided. \
    If the information is not in the provided source, you answer with &quot;I don\'t know&quot;. '
    task = f&quot;{user_question} Translate the response to english /n \
    source: {result_json}&quot;
    
    prompt = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: instructions }, 
              {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: task }]
    return prompt</pre></div>



<p>You can easily change the voice and tone in which the ChatGPT answers questions by including the respective instructions in the create_prompt function. </p>



<p>Also: <a href="https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/">ChatGPT Style Guide: Understanding Voice and Tone Prompt Options for Engaging Conversations</a></p>



<h3 class="wp-block-heading">Step #5 Testing the Custom ChatGPT Solution</h3>



<p>This part of the code works with the previous functions to facilitate a complete question-answering cycle with Cosmos DB and OpenAI&#8217;s ChatGPT 3.5 Turbo model.</p>



<p>Now comes the most exciting part. Testing the solution, you can define a question and then execute the code below to run the search process. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># define OpenAI Prompt 
users_question = &quot;When do I have to submit my tax return?&quot;
# generate embeddings for the question
user_question_embeddings = create_embeddings_with_openai(user_question)
# search for the question in the cosmos db
search_results = vector_search(user_question_embeddings, 1)
print(search_results)
# prepare the results for the openai prompt
result_json = []
# print each document in the result
# remove all empty values from the results json
search_results = [x for x in search_results if x]
for doc in search_results:
    display(doc.get('_id'), doc.get('textContent'), doc.get('vectorContent')[0:5])
    result_json.append(doc.get('textContent'))
# create the prompt
prompt = create_prompt(user_question, result_json)
display(prompt)
# generate the response
response = openai_request(prompt)
display(f'User question: {users_question}')
display(f'OpenAI response: {response}')</pre></div>



<p>&#8216;User question: When do I have to submit my tax return?&#8217;</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;disableCopy&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">'OpenAI response: When do I have to submit my tax return? \n\nAll natural persons who had their residence in the canton of Zurich on December 31, 2022, or who owned properties or business premises (or business operations) in the canton of Zurich, must submit a tax return for 2022 in the calendar year 2023. Taxpayers with a residence in another canton also have to submit a tax return for 2022 in the calendar year 2023 if they ended their tax liability in the canton of Zurich by giving up a property or business premises during the calendar year 2022. If you turned 18 in the tax period 2022 (persons born in 2004), you must submit your own tax return (for the tax period 2022) for the first time in the calendar year 2023.'</pre></div>



<p>As of Mai 2023, the knowledge base of ChatGPT 3.5 is limited to the timeframe before September 2021. So it&#8217;s evident that the response of our custom ChatGPT solution is based on the individual information provided in the vector database. Remember that we did not fine-tune the GPT model, so the model itself does not inherently know anything about your private data and instead uses the data that was dynamically provided to it as part of the prompt. </p>



<h2 class="wp-block-heading">Real-world Applications of Chat with your data</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Custom ChatGPT boosts efficiency, personalizes services, and improves experiences across industries. Here are some examples:</p>



<ul class="wp-block-list">
<li><strong>Customer Support:</strong> Companies can use ChatGPT for 24/7 customer service. With data from manuals, FAQs, and support docs, it delivers fast, accurate answers, enhancing customer satisfaction and lessening staff workload.</li>



<li><strong>Healthcare</strong>: ChatGPT can respond to patient questions using medical texts and care guidelines. It offers data on symptoms, treatments, side effects, and preventive care, helping both healthcare providers and patients.</li>



<li><strong>Legal Sector</strong>: Law firms can use ChatGPT with legal texts, court decisions, and case studies for answering legal questions, offering case references, or explaining legal terms.</li>



<li><strong>Financial Services:</strong> Banks can use ChatGPT to extend their customer service and give customers advice based on their individual financial situation.</li>



<li><strong>E-Learning:</strong> Schools and e-learning platforms can use ChatGPT to tutor students. Using textbooks, notes, and research papers, it helps students understand complex topics, solve problems, or guide them through a course.</li>
</ul>



<p>In short, any sector needing a large information database for queries or services can use custom ChatGPT. It enhances engagement and efficiency by offering personalized experiences.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">Summary</h2>



<p>In this comprehensive guide, we&#8217;ve journeyed through the fascinating process of creating a customized ChatGPT that lets users chat with your business data. We started with understanding the immense value a tailored ChatGPT brings to the table and dove into its ability to produce specialized responses sourced from a custom knowledge base. This tailored approach enhances user experiences, saves time, and bolsters productivity.</p>



<p>We went behind the scenes to reveal the vital elements of crafting a custom ChatGPT: OpenAI&#8217;s GPT models, data embeddings, and vector databases like Cosmos DB for Mongo DB vCore. We clarified how these components synergize to transcend the token limitations inherent to GPT models. By integrating the components in Python, we broadened ChatGPT&#8217;s ability to answer queries based on your private knowledgebase, thereby offering contextually appropriate responses.</p>



<p>I hope this tutorial was able to illustrate the business value of ChatGPT and its versatile utility across a variety of sectors, including customer service, healthcare, legal services, finance, e-learning, and CRM data analytics. Each instance emphasized the transformative potential of a personalized ChatGPT in delivering efficient, targeted solutions.</p>



<p>I hope you found this helpful article. If you have any questions or remarks, please drop them in the comment section.</p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<ul class="wp-block-list">
<li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/introduction" target="_blank" rel="noreferrer noopener">Azure Cosmos DB</a></li>



<li><a href="https://openai.com/pricing" target="_blank" rel="noreferrer noopener">OpenAI pricing</a></li>



<li><a href="https://learn.microsoft.com/en-us/azure/cognitive-services/openai/">Azure OpenAI</a></li>



<li><a href="https://azure.microsoft.com/en-au/products/cognitive-services/openai-service" target="_blank" rel="noreferrer noopener">Semantic search</a></li>



<li><a href="https://platform.openai.com/docs/guides/embeddings" target="_blank" rel="noreferrer noopener">What are embeddings?</a></li>



<li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/vcore/vector-search" target="_blank" rel="noreferrer noopener">Using vector search on embeddings in Azure Cosmos DB for MongoDB vCore</a></li>



<li>OpenAI ChatGPT helped to revise this article</li>



<li>Images created with <a href="https://www.midjourney.com/home/?callbackUrl=%2Fapp%2F" target="_blank" rel="noreferrer noopener">Midjourney</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/">Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">13687</post-id>	</item>
		<item>
		<title>Vector Databases: The Rising Star in Generative AI Infrastructure</title>
		<link>https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/</link>
					<comments>https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sat, 06 May 2023 22:43:36 +0000</pubDate>
				<category><![CDATA[ChatBots]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=13599</guid>

					<description><![CDATA[<p>Artificial intelligence (AI) continues its rapid evolution, with new advancements and innovations emerging on a frequent basis. A key enabler of these advancements is the robust infrastructure needed to store, process, and analyze colossal amounts of data. One critical part of this infrastructure is the vector database, a powerful solution for managing unstructured data types ... <a title="Vector Databases: The Rising Star in Generative AI Infrastructure" class="read-more" href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/" aria-label="Read more about Vector Databases: The Rising Star in Generative AI Infrastructure">Read more</a></p>
<p>The post <a href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/">Vector Databases: The Rising Star in Generative AI Infrastructure</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Artificial intelligence (AI) continues its rapid evolution, with new advancements and innovations emerging on a frequent basis. A key enabler of these advancements is the robust infrastructure needed to store, process, and analyze colossal amounts of data. One critical part of this infrastructure is the vector database, a powerful solution for managing unstructured data types including text, audio, images, and videos in numerical form.</p>



<p>Vector databases have gained traction in the AI sphere due to their ability to efficiently manage similarity searches across thousands of columns. They play a crucial role in powering large language models and other advanced AI applications. In this article, we will delve into the fundamentals of vector databases, their significance in AI infrastructure, and their transformative potential in managing and analyzing unstructured data.</p>



<p>Also: </p>



<p><a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/" target="_blank" rel="noreferrer noopener">9 Business Use Cases of OpenAI’s ChatGPT</a><br><a href="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/">Using LLMs (OpenAI’s ChatGPT) to Streamline Digital Experiences</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Why are Vector Databases Integral to AI Infrastructure? </h2>



<p>The rise of vector databases is closely tied to the growing importance of embeddings in advanced generative AI applications. Embeddings are high-dimensional vectors that represent unstructured data, such as text, images, and audio, in a continuous numerical space. These vectors are essential for advanced generative AI applications such as natural language processing, computer vision, and speech recognition, where they are used to represent and analyze complex data.</p>



<h3 class="wp-block-heading">The Role of Embeddings in Generative AI</h3>



<p>Embeddings play a vital role in advanced generative AI applications such as natural language processing (NLP), where they are used to represent and analyze complex data. An embedding is a high-dimensional vector that represents unstructured data, such as text, images, and audio, in a continuous numerical space. In the context of NLP, an embedding represents a semantic and syntactic meaning of words or sentences in a vector format that can be fed as input into deep learning models.</p>



<p>An example of an embedding for text could be representing the sentence &#8220;I love pizza&#8221; as a 300-dimensional vector, where each dimension represents a specific feature or attribute of the sentence. For instance, word count, the presence of certain keywords, or sentiment. The process of generating embeddings for natural language is typically done using pre-trained language models like OpenAI&#8217;s GPT or <a href="https://www.relataly.com/category/machine-learning-algorithms/bidirectional-encoder-representations-from-transformers-bert/">BERT</a>.</p>



<p>The length of an embedding vector is arbitrary and can vary depending on the specific use case and the model used to generate the embeddings. The quality of the embeddings can significantly affect the performance of NLP tasks such as language modeling, sentiment analysis, machine translation, and question-answering systems.</p>



<p>Large language models (LLMs) are one of the most advanced AI applications that heavily rely on embeddings. These models have billions of parameters, and embeddings play a crucial role in training and fine-tuning these models to perform a wide range of NLP tasks.</p>



<h3 class="wp-block-heading">SQL Databases and Their Limitations in Handling High-Dimensional Embeddings</h3>



<p>SQL databases are designed to work with structured data that has a fixed schema and is typically stored in tables with rows and columns. In contrast, embeddings are high-dimensional vectors that represent unstructured data such as text, images, and audio in a continuous numerical space. Embeddings can have hundreds or even thousands of dimensions, making them unsuitable for storage in traditional SQL databases, which are optimized for working with smaller, fixed-dimensional datasets.</p>



<h3 class="wp-block-heading">Benefits of Vector Databases</h3>



<p>Vector databases are natively designed to handle high-dimensional vectors, such as embeddings. They can therefore provide a more scalable and efficient solution for storing, querying, and analyzing large amounts of unstructured data. With their ability to efficiently handle similarity searches across thousands of columns, vector databases have become an essential component of AI infrastructure, powering large language models and other advanced AI applications.</p>



<p>There are several reasons why vector databases are well-suited to handle embeddings:</p>



<ol class="wp-block-list">
<li><strong>Efficient storage</strong>: Vector databases are designed to store high-dimensional vectors efficiently, allowing them to handle large quantities of data while using minimal storage space. This is important for embeddings, which can have hundreds or thousands of dimensions.</li>



<li><strong>High-performance similarity search</strong>: Vector databases use specialized algorithms and data structures to perform high-performance similarity searches on embeddings. This allows users to quickly find the closest embeddings to a given query, making them well-suited for tasks such as image or text similarity search.</li>



<li><strong>Scalability</strong>: Vector databases are highly scalable, allowing them to easily handle large datasets. This is important for embeddings, which are often used in large language models and other AI applications that require vast amounts of data.</li>



<li><strong>Flexibility</strong>: Vector databases can handle various data types, including text, images, audio, and video. This makes them well-suited for a wide range of AI applications.</li>
</ol>



<p>Overall, the specialized design of vector databases makes them well-suited for handling high-dimensional vectors such as embeddings, making them a crucial component of modern AI infrastructure.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="503" data-attachment-id="13605" data-permalink="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min.png" data-orig-size="1012,994" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min.png" src="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min-512x503.png" alt="An embedding is a high-dimensional vector that represents unstructured data, such as text, images, and audio, in a continuous numerical space." class="wp-image-13605" srcset="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_multiple_points_in_a_high-dimensional_space_connected_by_8963e82a-1393-4173-b080-9149fc046c49-min.png 1012w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">An embedding is a high-dimensional vector that represents unstructured data, such as text, images, and audio, in a continuous numerical space.</figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Semantic Search as a Way to Create Custom ChatGPT </h2>



<p>OpenAI&#8217;s approach to embeddings is an unsupervised learning method known as &#8220;representation learning.&#8221; The model learns to represent the data in a useful way for downstream tasks like natural language processing without being explicitly told what features to extract or how to represent the data. This approach has been highly effective in training LLMs, which can generate human-like text with remarkable accuracy.</p>



<p>However, one of the limitations of OpenAI models is their ability to handle only a limited amount of input data. For example, ChatGPT 3.5 has a token limit of 4096, which means that it cannot search larger databases without additional techniques. This is where embeddings come into play.</p>



<p>Vector databases are becoming increasingly popular for their ability to find meaning in unstructured data, which is a vital feature for advanced AI applications such as semantic search. Semantic search is similar to ChatGPT, but it operates on a custom knowledge base. The knowledge can be anything from customer relationship management (CRM) data to technical manuals and research and development (R&amp;D) information. The data needs to be stored somewhere and support querying at low latency, and vector databases are perfectly suited for this task due to their previously mentioned advantages. The growing popularity of vector databases is, therefore also to be seen as a result of the growing interest of companies in creating custom ChatGPT applications based on their internal knowledge. </p>



<h2 class="wp-block-heading">Increasing Investments in Vector Database Startups</h2>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="288" data-attachment-id="13601" data-permalink="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min.png" data-orig-size="1452,816" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min" data-image-description="&lt;p&gt;vector database&lt;/p&gt;
" data-image-caption="&lt;p&gt;vector database&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min.png" src="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min-512x288.png" alt="OpenAI's approach to embeddings is an unsupervised learning method known as &quot;representation learning.&quot; The model learns to represent the data in a useful way for downstream tasks like natural language processing without being explicitly told what features to extract or how to represent the data. " class="wp-image-13601" srcset="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_vector_database_colorful_popart_b6b52134-5a54-4622-85bc-ed93d715501f-min.png 1452w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">OpenAI&#8217;s approach to embeddings is an unsupervised learning method known as &#8220;representation learning.&#8221; The model learns to represent the data in a useful way for downstream tasks like natural language processing without being explicitly told what features to extract or how to represent the data.  </figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Given the recent hype around AI, it&#8217;s no wonder that companies are investing heavily in vector databases to improve the accuracy and efficiency of their algorithms. This trend is reflected in the recent<a href="https://www.calcalistech.com/ctechnews/article/sjveg7ux2" target="_blank" rel="noreferrer noopener"> funding rounds of vector database startups</a> such as Pinecone, Chroma, and Weviate. However, established players in the field, such as Microsoft, also offer solutions that can be used to build AI applications on top of custom knowledge bases. For example, <a href="https://learn.microsoft.com/en-us/azure/search/semantic-search-overview" target="_blank" rel="noreferrer noopener">Azure Cognitive Search</a> is a powerful solution that businesses can use to build and deploy AI applications that leverage the capabilities of vector databases. <a href="https://cloud.google.com/blog/topics/developers-practitioners/find-anything-blazingly-fast-googles-vector-search-technology?hl=en" target="_blank" rel="noreferrer noopener">Matchlt </a>is another solution for vector search developed by Google. Despite the challenges posed by new startups, established players like Microsoft remain competitive and continue to offer valuable solutions for businesses seeking to implement vector databases in their AI workflows.</p>



<h2 class="wp-block-heading">A Close Look at Popular Vector Databases: Pinecone, Chroma, and Weaviate</h2>



<p>Finally, let&#8217;s take a look at three different dedicated vector databases that are optimized for working with vectors: Pinecone, Chroma, and Weaviate.</p>



<h3 class="wp-block-heading">Pinecone</h3>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="510" height="512" data-attachment-id="13651" data-permalink="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min.png" data-orig-size="904,908" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min.png" src="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min-510x512.png" alt="Given the recent hype around AI, it's no wonder that companies are investing heavily in vector databases to improve the accuracy and efficiency of their algorithms." class="wp-image-13651" srcset="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min.png 510w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min.png 140w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_tech_investors_throwing_money_on_ai_startups_colorful_po_9d334af2-b3d8-40ba-891e-479f2a48c2e3-min.png 904w" sizes="(max-width: 510px) 100vw, 510px" /><figcaption class="wp-element-caption">Given the recent hype around AI, it&#8217;s no wonder that companies are investing heavily in vector databases to improve the accuracy and efficiency of their algorithms. </figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p><a href="https://www.pinecone.io/" target="_blank" rel="noreferrer noopener">Pinecone</a> is a cloud-native vector database designed for high-performance, low-latency, and scalable vector similarity search. It can handle both dense and sparse vectors, making it a versatile choice for a wide range of use cases. Pinecone provides an easy-to-use API that allows users to add, search, and retrieve vectors with just a few lines of code. It also offers hybrid search functionality, which enables users to mix traditional text-based search with vector search.</p>



<p>One of the key advantages of Pinecone is its scalability. It can handle billions of vectors and provides automatic sharding and load balancing to ensure that search requests are distributed evenly across the available resources. Pinecone also offers real-time indexing and search. This means that new vectors are available for search immediately after they are added.</p>



<h3 class="wp-block-heading">Chroma</h3>



<p><a href="https://www.trychroma.com/" target="_blank" rel="noreferrer noopener">Chroma </a>is a simple, lightweight vector search database that can be used to build an in-memory document-vector store. It is built on top of <a href="https://cassandra.apache.org/" target="_blank" rel="noreferrer noopener">Apache Cassandra</a> and provides an easy-to-use API. It is an excellent choice for users who want a quick and simple solution for vector similarity search. Chroma uses the Hugging Face transformers library to vectorize documents by default, but it can also be configured to use custom vectorization models.</p>



<p>One of the key advantages of Chroma is its simplicity. It can be set up and configured quickly and easily and doesn&#8217;t require any special hardware or software. Chroma is also highly customizable, supporting custom vectorization models, custom similarity functions, and more. If you are looking for the Chroma Python library, <a href="https://pypi.org/project/chromadb/#:~:text=Embeddings%20databases%20(also%20known%20as,)%20embeddings%2C%20or%20your%20own." target="_blank" rel="noreferrer noopener">here</a> it is.</p>



<h3 class="wp-block-heading">Weaviate</h3>



<p>Weaviate is a feature-rich vector database designed for complex data modeling and search use cases. It provides a GraphQL API with support for vector similarity search and a range of other advanced search and filtering features. Weaviate can store and search various data types, including structured data, unstructured data, and images.</p>



<p>One of the key advantages of Weaviate is its flexibility. It can be used to build highly customized search applications with complex data models and search requirements. Weaviate also provides advanced search and filtering features, including geospatial search, range search, and fuzzy search. It also supports data federation, which enables users to search across multiple data sources.</p>



<h2 class="wp-block-heading">Other Noteworthy Vector Databases</h2>



<p>The vector databases above are just some examples. Several other vector databases may be worth a look too: </p>



<ul class="wp-block-list">
<li><a href="https://github.com/facebookresearch/faiss" target="_blank" rel="noreferrer noopener">Faiss</a>: Developed by Facebook&#8217;s AI Research team, Faiss provides efficient similarity search and clustering of dense vectors.</li>



<li><a href="https://github.com/nmslib/hnswlib" target="_blank" rel="noreferrer noopener">Hnswlib</a>: An open-source library for Approximate Nearest Neighbor Search, Hnswlib offers excellent speed and accuracy with minimal resource usage.</li>



<li><a href="https://milvus.io/" target="_blank" rel="noreferrer noopener">Milvus</a>: An open-source vector database designed for AI and analytics, Milvus offers scalable, reliable, and customizable solutions.</li>



<li><a href="https://qdrant.tech/" target="_blank" rel="noreferrer noopener">qdrant</a>: Qdrant is a vector similarity search engine with extended filtering capabilities, designed for organizing and searching large-scale vector data.</li>
</ul>



<p>Additionally, some databases, while not specifically designed for vectors, can handle vectors more efficiently than traditional SQL databases. Examples include Azure Cosmos DB, Elasticsearch, and Redis DB. Examples include <a href="https://azure.microsoft.com/en-us/free/cosmos-db/search/?ef_id=_k_Cj0KCQjw9deiBhC1ARIsAHLjR2AqM7_4aJksJcFeNuOFAJChAsJUZSifGrvRlkgBTPg049kcYzsh4B4aAi8ZEALw_wcB_k_&amp;OCID=AIDcmmtg9dwtad_SEM__k_Cj0KCQjw9deiBhC1ARIsAHLjR2AqM7_4aJksJcFeNuOFAJChAsJUZSifGrvRlkgBTPg049kcYzsh4B4aAi8ZEALw_wcB_k_&amp;gclid=Cj0KCQjw9deiBhC1ARIsAHLjR2AqM7_4aJksJcFeNuOFAJChAsJUZSifGrvRlkgBTPg049kcYzsh4B4aAi8ZEALw_wcB" target="_blank" rel="noreferrer noopener">Azure Cosmos Db</a>, <a href="https://www.elastic.co/?ultron=B-Stack-Trials-EMEA-C-Exact&amp;gambit=Stack-Core&amp;blade=adwords-s&amp;hulk=paid&amp;Device=c&amp;thor=elastic%20search%20engine&amp;gclid=Cj0KCQjw9deiBhC1ARIsAHLjR2ALCdy5sjOysA2IzYynQqizjlRUE1gTnpG9LWo_Wv9c_39vbBaBh0MaAi8PEALw_wcB" target="_blank" rel="noreferrer noopener">Elastic Search</a>, and <a href="https://redis.com/docs/9-essential-database-capabilities/?utm_source=google&amp;utm_medium=cpc&amp;utm_term=redis%20db&amp;utm_campaign=redis360-brand-emea-19645427181&amp;utm_content=eb-nine_essential_database_capabilities&amp;gclid=Cj0KCQjw9deiBhC1ARIsAHLjR2CF-28k17pDOoZ3G_7hEwAgw5fzeItCa0mST9pU8z5XhRvjawQlKmIaArKjEALw_wcB" target="_blank" rel="noreferrer noopener">Redis db</a>.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>OpenAI&#8217;s advancements may have fueled the initial hype around AI, but the infrastructure demand to support AI applications is now on the rise. Vector databases are increasingly in the spotlight due to their proficiency in managing unstructured data and their efficiency in conducting similarity searches across vast columns of data. With the escalating demand for AI infrastructure, vector databases are anticipated to continue gaining momentum. As businesses and organizations strive to leverage the power of AI, the reliance on vector databases will only grow, making them a cornerstone of future AI infrastructure.</p>



<p>I hope this article was helpful. If you have any remarks or comments, please let me know in the comments. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading" id="h-sources-and-further-reading">Sources and Further Reading</h2>



<ul class="wp-block-list">
<li><a href="https://en.wikipedia.org/wiki/Distributional%E2%80%93relational_database" target="_blank" rel="noreferrer noopener">https://en.wikipedia.org/wiki/Distributional%E2%80%93relational_database</a></li>



<li><a href="https://www.pinecone.io/" target="_blank" rel="noreferrer noopener">https://www.pinecone.io/</a></li>



<li><a href="https://www.trychroma.com/" target="_blank" rel="noreferrer noopener">https://www.trychroma.com/</a></li>



<li><a href="https://www.calcalistech.com/ctechnews/article/sjveg7ux2" target="_blank" rel="noreferrer noopener">https://www.calcalistech.com/ctechnews/article/sjveg7ux2</a></li>



<li><a href="https://weaviate.io/" target="_blank" rel="noreferrer noopener">https://weaviate.io/</a></li>



<li><a href="https://analyticsindiamag.com/why-are-investors-flocking-to-vector-databases/" target="_blank" rel="noreferrer noopener">https://analyticsindiamag.com/why-are-investors-flocking-to-vector-databases/</a></li>



<li>ChatGPT helped to revise this article.</li>



<li>Images generated with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/">Vector Databases: The Rising Star in Generative AI Infrastructure</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">13599</post-id>	</item>
		<item>
		<title>From Pirates to Nobleman: Simulating Multi-Agent Conversations using OpenAI&#8217;s ChatGPT and Python</title>
		<link>https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/</link>
					<comments>https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Mon, 24 Apr 2023 22:44:52 +0000</pubDate>
				<category><![CDATA[ChatBots]]></category>
		<category><![CDATA[Generative AI]]></category>
		<category><![CDATA[Language Generation]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=13525</guid>

					<description><![CDATA[<p>Many people use ChatGPT for its text-generation capability and have included it in their day-to-day workflows. However, few people may know that you can use it to create multi-agent conversations between fictional and nonfictional characters. Ever wondered if AI could take you on a time-traveling journey to eavesdrop on a chat between an 18th-century Pirate ... <a title="From Pirates to Nobleman: Simulating Multi-Agent Conversations using OpenAI&#8217;s ChatGPT and Python" class="read-more" href="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/" aria-label="Read more about From Pirates to Nobleman: Simulating Multi-Agent Conversations using OpenAI&#8217;s ChatGPT and Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/">From Pirates to Nobleman: Simulating Multi-Agent Conversations using OpenAI&#8217;s ChatGPT and Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Many people use ChatGPT for its text-generation capability and have included it in their day-to-day workflows. However, few people may know that you can use it to create multi-agent conversations between fictional and nonfictional characters. Ever wondered if AI could take you on a time-traveling journey to eavesdrop on a chat between an 18th-century Pirate and Nobleman? Say no more! In this blog post, we&#8217;re diving deep into the captivating universe of ChatGPT. We use a Python script and OpenAI ChatGPT to simulate a multi-agent conversation about life&#8217;s big questions. Plus, we&#8217;ll give you the lowdown on how to bring your characters to life to make the convo even more riveting.</p>



<p>So, buckle up and get ready for a time-warping chat that&#8217;ll not only tickle your curiosity but also get you thinking about the meaning of life itself!</p>



<p>Also: <a href="https://www.relataly.com/mastering-prompt-engineering-for-chatgpt-a-practical-guide-for-businesses/13134/">ChatGPT Prompt Engineering: A Practical Guide for Businesses</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Multi-Agent Conversations between Two instances of ChatGPT of itself &#8211; How does it work?</h2>



<p>GPT, part of the name ChatGPT, stands for &#8220;Generative Pretrained Transformer&#8221;. It&#8217;s a fancy name for a groundbreaking innovation we&#8217;ve seen in the last ten years. One cool thing about ChatGPT is that it can have a conversation with itself. How? By using the answer from one version of itself as the next question for another version.</p>



<p>Imagine this: You let ChatGPT-1 talk, take its answer, and give it to ChatGPT-2 as a new question. You keep doing this, and before you know it, you&#8217;ve got an ongoing chat between the two!</p>



<p>This unique feature can be super handy for many things. For instance, you could build more lifelike chatbots or create authentic and varied dialogues for characters in a story.</p>



<p>But there&#8217;s a catch. Sometimes, they can get stuck in loops or spit out gibberish. That&#8217;s why it&#8217;s crucial to keep an eye on these chats to make sure they make sense and stay on topic.</p>



<p> </p>



<figure class="wp-block-image size-full"><img decoding="async" width="1064" height="1046" data-attachment-id="13565" data-permalink="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/image-2-12/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/04/image-2.png" data-orig-size="1064,1046" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/04/image-2.png" src="https://www.relataly.com/wp-content/uploads/2023/04/image-2.png" alt="The illustration shows the first three steps in a conversation between ChatGPT and itself - In the sample, the prompt includes information that makes ChatGPT alternate between the roles of a pirate and an aristocrat. " class="wp-image-13565" srcset="https://www.relataly.com/wp-content/uploads/2023/04/image-2.png 1064w, https://www.relataly.com/wp-content/uploads/2023/04/image-2.png 300w, https://www.relataly.com/wp-content/uploads/2023/04/image-2.png 512w, https://www.relataly.com/wp-content/uploads/2023/04/image-2.png 768w" sizes="(max-width: 1064px) 100vw, 1064px" /><figcaption class="wp-element-caption">The illustration shows the first three steps in a conversation between ChatGPT and itself. In the sample, the prompt includes information that makes ChatGPT alternate between the roles of a pirate and an aristocrat. </figcaption></figure>



<p>Also: <a href="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/" target="_blank" rel="noreferrer noopener">Eliminating Friction: How LLMs such as OpenAI’s ChatGPT Streamline Digital Experiences and Reduce the Need for Search</a></p>



<h2 class="wp-block-heading">How to Manage a Conversation Context with ChatGPT</h2>



<p>When using ChatGPT models, there are three different roles available: system, user, and assistant. Understanding these roles is critical when designing a conversation because it allows us to manage the context and information provided to the model.</p>



<ul class="wp-block-list">
<li><strong>The system role </strong>indicates that a message comes from the system or the model itself. While it is not required to include system messages in a conversation, doing so can help set up the conversation&#8217;s context and provide information that can be used to guide the model&#8217;s subsequent responses.</li>



<li><strong>The user role </strong>indicates that a message comes from an end-user or an application. This role represents prompts that trigger a response from the model. When designing a conversation, it is essential to carefully craft these prompts to provide the model with the necessary context and information to provide a useful response.</li>



<li><strong>The assistant role</strong> indicates that a message is coming from the assistant, which is the model itself. This role helps maintain continuity between the user and the model during a conversation. Using the assistant role, previous conversations can be saved and sent again in subsequent requests to help guide the model&#8217;s responses.</li>
</ul>



<p>The code below shows how to use these roles when requesting the ChatGPT model. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">prompt = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: general_instructions}, 
          {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: task},
         {&quot;role&quot;: &quot;assistant&quot;: previous_responses}] 

#print('Generating response from OpenAI...') 
completion = openai.ChatCompletion.create(
  model=model_engine, 
  messages=prompt, 
  temperature=0.5, 
  max_tokens=100)</pre></div>



<p>Understanding the different roles available when using ChatGPT models is critical for designing effective conversations. By carefully crafting messages with the appropriate role, we can provide the model with the necessary context and information it needs to provide useful and relevant responses.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading" id="h-simulating-a-multi-agent-conversation-between-a-pirate-and-a-nobleman">Simulating a Multi-Agent Conversation between a Pirate and a Nobleman</h2>



<p>Now that you have a broad understanding of multi-agent conversations, we will focus on the practical part. In the following, we will use ChatGPT to simulate a discussion between a pirate and a nobleman on the sense of life. The characters have distinct personalities and goals, which will be reflected in their responses and the unique style of how they converse. </p>



<p>The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_1d10d7-41"><a class="kb-button kt-button button kb-btn_b66beb-d9 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/07%20OpenAI/603%20Conversation%20between%20OpenAI%20ChatGPT%20and%20Itself%20in%20Python.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_fb6ebb-59 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="508" height="512" data-attachment-id="13534" data-permalink="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-copy-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/04/Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min.png" data-orig-size="1012,1020" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/04/Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min.png" src="https://www.relataly.com/wp-content/uploads/2023/04/Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min-508x512.png" alt="" class="wp-image-13534" srcset="https://www.relataly.com/wp-content/uploads/2023/04/Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min.png 508w, https://www.relataly.com/wp-content/uploads/2023/04/Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min.png 298w, https://www.relataly.com/wp-content/uploads/2023/04/Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min.png 140w, https://www.relataly.com/wp-content/uploads/2023/04/Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/04/Flo7up_a_conversation_between_to_robots_colorful_popart_a589d3e7-14d2-4383-b0e4-a8491aa9ebe1-Copy-min.png 1012w" sizes="(max-width: 508px) 100vw, 508px" /><figcaption class="wp-element-caption">OpenAI ChatGPT has various use cases. Among others, it can be used to simulate multi-agent conversations between fictional and non-fictional characters. </figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Some Words on the OpenAI API Key and Inference Costs</h2>



<p>To run the code below, you will need an OpenAI API that you can obtain from <a href="http://www.openai.com/" target="_blank" rel="noreferrer noopener">OpenAI</a> or from <a href="https://azure.microsoft.com/en-us/products/cognitive-services/openai-service" target="_blank" rel="noreferrer noopener">Azure OpenAI</a>. Yes, you will have to sign up. </p>



<p>How about the cost of inferring the model? We will be utilizing the ChatGPT Turbo model for every conversation, which will require using the completion endpoint of the model several times, leading to some costs. The cost of using GPT models varies depending on the model type and the number of processed tokens. In the use case discussed in this article, each code execution will involve 20 API calls to the ChatGPT Turbo model (3.5). Since this model is highly cost-effective and we will not be generating an excessive amount of text, executing the code will only incur a few cents in costs.</p>



<h3 class="wp-block-heading">Step #1 Setting up Imports and OpenAI Key</h3>



<p>Let&#8217;s begin by importing a few libraries such as openai, datetime, and Azure. We will also set up an API key for OpenAI. You can for example store and retrieve the API key from an environment variable or from an Azure Key Vault. Storing the key directly in the code is not advised, as you might accidentally commit your code to a public repository and expose the key. </p>



<p>The code below will also create a folder to store conversations. Each conversation will get stored in HTML format. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import openai
import datetime as dt
from azure.identity import AzureCliCredential
from azure.keyvault.secrets import SecretClient
import time
import os

# use environment variables for API key
timestamp = dt.datetime.now().strftime(&quot;%Y%m%d_%H%M%S&quot;)

# set your OpenAI API key here
API_KEY = os.environ.get(&quot;OPENAI_API_KEY&quot;)
if API_KEY is None:
    print('trying to get API key from azure keyvault')
    keyvault_name = 'your-keyvault-name'
    client = SecretClient(f&quot;https://{keyvault_name}.vault.azure.net/&quot;, AzureCliCredential())
    API_KEY = client.get_secret('openai-api-key').value
openai.api_key = API_KEY

# create a folder to store the conversations if it does not exist
path = 'ChatGPT_conversations'
if not os.path.exists(path):
    os.makedirs(path)</pre></div>



<h3 class="wp-block-heading">Step #2 Functions for Prompts and OpenAI Completion</h3>



<p>We begin by defining three essential functions used to create and maintain a conversation using the OpenAI ChatGPT completion endpoint.</p>



<ul class="wp-block-list">
<li>The first function, initialize_conversation, sets up the conversation by creating an initial prompt for the user to start the conversation with a given topic and character description. For instance, the code below sets the initial prompt as &#8220;Good day, Sir. Wonderful day isn&#8217;t it?&#8221; and waits for ChatGPT to respond with an appropriate reply.</li>



<li>The second function, respond_prompt, generates a response to the previous response and creates a prompt for the user to continue the conversation. This function is called multiple times as the conversation progresses.</li>



<li>Finally, the openai_request function utilizes the OpenAI chat engine to generate a response to the prompt created by the previous two functions. The response generated by the chat engine is then returned to the calling function.</li>
</ul>



<p>By using these functions, we can establish a fully functional and engaging conversation system that utilizes the power of OpenAI&#8217;s ChatGPT model. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># This function creates a prompt that initializes the conversation 
def initialize_conversation(topic='', character=''):
    instructions = f' You have a conversation on {topic}. You can bring up any topic that comes to your mind'
    instructions = character['description'] + instructions
    task = f'Good day, Sir.'
    if topic != '':
        task = task + f' Wonderful day isn t it?'
    return instructions, task

# This function creates a prompt that responds to the previous response
def respond_prompt(response, topic='', character=''):    
    instructions = f'You have a conversation with someone on {topic}. \
    Reply to questions and bring up any topic that comes to your mind.\
    Dont say more than 2 sentences at a time.'
    instructions = character['description'] + instructions
    task = f'{response}' 
    return instructions, task

# OpenAI Engine using the turbo model
def openai_request(instructions, task, model_engine='gpt-3.5-turbo'):
    prompt = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: instructions }, 
              {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: task }]

    #print('Generating response from OpenAI...')
    completion = openai.ChatCompletion.create(
    model=model_engine, 
    messages=prompt,
    temperature=1.0, # this will lead to create responses that are more creative
    max_tokens=100)

    response = completion.choices[0].message.content

    return response</pre></div>



<h3 class="wp-block-heading">Step #3 Defining Characters </h3>



<p>After defining the functions, the next step is to create the conversation by specifying the topic and the characters that will participate in the debate. In the following example, the topic is &#8220;the sense of life,&#8221; and the two characters are James, an Aristocrat, and Blackbeard, a Pirate. These characters are described with unique personalities and behaviors that will be utilized in the conversation simulation.</p>



<p>With this framework, it is simple to modify the behaviors, voice, and tone of the characters by adjusting their descriptions. This flexibility allows for the creation of intriguing conversations on any topic between different characters. The possibilities are endless; one could simulate a debate between Darth Vader and Harry Potter, or even describe the behavior and background of the characters in more detail.</p>



<p>In short, this framework provides a flexible and adaptable platform for generating engaging conversations, allowing for the exploration of various perspectives and topics.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># initialize conversation on the following topic
topic = 'The sense of life'
conversation_rounds = 20

# description of character 1
color_1 = 'darkblue' 
character_1 = {
&quot;name&quot;: 'James (Aristocrat)',
&quot;description&quot;: 'You are a French nobleman from the 18th century. \
    Your knowledge and wordlview corresponds to that of a common aristocrate from that time. \
    You speak in a distinguished manner. \
    You response in one or two sentences. \
    You are afraid of pirates but also curious to meet one.'}

# description of character 2 
color_2 = 'brown'
character_2 = {
&quot;name&quot;: 'Blackbeard (Pirate)',
&quot;description&quot;: 'You are a devious pirate from the 18th century who tends to swear. \
    Your knowledge and wordlview corresponds to that of a common pirate from that time. \
    You response in one or two sentences. \
    You are looking for a valuable treasure and trying to find where it is hidden. \
    You try to steer the conversation back to the treasure no matter what.'}</pre></div>



<h3 class="wp-block-heading">Step #4 Start the Conversation</h3>



<p>Now that we have our characters defined, it&#8217;s time to start the conversation. The next section of the code invokes the conversation between the two characters by initializing it with a greeting from one of the characters. In the code below, James starts the conversation with a prompt: &#8220;Good day, Sir. Wonderful day, isn&#8217;t it?&#8221;.</p>



<p>The conversation then proceeds with each character taking turns responding to the previous prompt. The response from each character is generated by calling the openai_request() function, which sends a prompt to OpenAI&#8217;s GPT-3.5 model and returns a response generated by the model.</p>



<p>The conversation continues for a specified number of rounds, which can be set by changing the value of the &#8220;num_rounds&#8221; variable. Each round consists of a response from one character followed by a response from the other character.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">conversation = ''
for i in range(conversation_rounds):
        # initialize conversation
        if i == 0:
            print('Initializing conversation...')
            text_color = color_1
            name = character_1['name']
            instructions, task = initialize_conversation(topic, character_1)
            response = openai_request(instructions, task)
            print(f'{name}: {task}')
            conversation = f'&lt;p style=&quot;color: {text_color};&quot;&gt;&lt;b&gt;{name}&lt;/b&gt;: {task}&lt;/p&gt; \n'
        # alternate between character_1 and character_2
        else:
            if i % 2 == 0:
                text_color = color_1
                name = character_1['name']
                instructions, task = respond_prompt(response, topic, character_1)
            else:
                text_color = color_2
                name = character_2['name']
                instructions, task = respond_prompt(response, topic, character_2)

            # OpenAI request
            response = openai_request(instructions, task)

            # wait some seconds 
            time.sleep(15)

            # add response to conversation after linebreak
            print(f'{name}: {response}')
            conversation += ' ' + f'&lt;p style=&quot;color: {text_color};&quot;&gt;&lt;b&gt;{name}&lt;/b&gt;: {response}&lt;/p&gt; \n'

        #print('storing conversation')
        # store conversation with timestamp
        
        filename = f'{path}/GPTconversation_{timestamp}.html'
        with open(filename, 'w') as f:
            f.write(conversation)</pre></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1910" height="774" data-attachment-id="13533" data-permalink="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/image-21/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/04/image.png" data-orig-size="1910,774" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/04/image.png" src="https://www.relataly.com/wp-content/uploads/2023/04/image.png" alt="" class="wp-image-13533" srcset="https://www.relataly.com/wp-content/uploads/2023/04/image.png 1910w, https://www.relataly.com/wp-content/uploads/2023/04/image.png 300w, https://www.relataly.com/wp-content/uploads/2023/04/image.png 512w, https://www.relataly.com/wp-content/uploads/2023/04/image.png 768w, https://www.relataly.com/wp-content/uploads/2023/04/image.png 1536w" sizes="(max-width: 1237px) 100vw, 1237px" /></figure>



<p>As you can see, the conversation is quite entertaining and even touches upon some aspects of an interesting philosophical question. But foremost it&#8217;s an amusing example of an exotic use case for ChatGPT.</p>



<p>By modifying the character descriptions and prompts, you can create interesting conversations on any topic between various characters. For example, you can create a conversation between Albert Einstein and Marie Curie on the topic of physics, or between Abraham Lincoln and Martin Luther King Jr. on the topic of civil rights. The possibilities are endless!</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Summary</h2>



<p>Arrr sailor, you have reached the end of this post! So let&#8217;s do a quick recap. This article has presented a Python script that allowed for the simulation of a multi-agent ChatGPT conversation between a pirate and a nobleman. The script used the ChatGPT language model to generate responses for the characters based on a given topic. We have provided instructions for running the script and customizing the personalities and behaviors of the characters. In addition, we have discussed how the script works by generating a response from OpenAI that is then used as a prompt for another ChatGPT instance. In this way, ChatGPT can be used to simulate a conversation on any topic. </p>



<p>Overall, I hope this article was able to demonstrate the potential of using GenerativeAI and natural language processing to create engaging and entertaining dialogues between virtual characters. </p>



<p>If you have any questions or want to share your experiences with what you could achieve with the script, please let me and everyone else know in the comment.</p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<p><a href="https://en.wikipedia.org/wiki/Blackbeard">https://en.wikipedia.org/wiki/Blackbeard</a><br><a href="https://beta.openai.com/docs/models" target="_blank" rel="noreferrer noopener">OpenAI.com/models</a><br><a href="https://azure.microsoft.com/en-us/products/cognitive-services/openai-service" target="_blank" rel="noreferrer noopener">Azure OpenAI Service</a><br>ChatGPT helped to revise this article, but the thoughts are human-made. <br>Images generated with <a href="http://www.midjourney.com/" target="_blank" rel="noreferrer noopener">Midjourney.com</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>
<p>The post <a href="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/">From Pirates to Nobleman: Simulating Multi-Agent Conversations using OpenAI&#8217;s ChatGPT and Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">13525</post-id>	</item>
	</channel>
</rss>
