<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.3.4">Jekyll</generator><link href="https://vyhaophan.github.io/feed.xml" rel="self" type="application/atom+xml"/><link href="https://vyhaophan.github.io/" rel="alternate" type="text/html" hreflang="en"/><updated>2024-11-17T12:49:46+00:00</updated><id>https://vyhaophan.github.io/feed.xml</id><title type="html">VyHao Space</title><subtitle>A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design. </subtitle><entry><title type="html">How to create a multi-function OpenAI Assistant</title><link href="https://vyhaophan.github.io/blog/2024/how-to-create-a-multi-function-openai-assistant/" rel="alternate" type="text/html" title="How to create a multi-function OpenAI Assistant"/><published>2024-11-05T15:24:06+00:00</published><updated>2024-11-05T15:24:06+00:00</updated><id>https://vyhaophan.github.io/blog/2024/how-to-create-a-multi-function-openai-assistant</id><content type="html" xml:base="https://vyhaophan.github.io/blog/2024/how-to-create-a-multi-function-openai-assistant/"><![CDATA[]]></content><author><name></name></author></entry><entry><title type="html">How to set up your multi-function Assistant</title><link href="https://vyhaophan.github.io/blog/2024/assistant-function-call/" rel="alternate" type="text/html" title="How to set up your multi-function Assistant"/><published>2024-11-02T14:45:00+00:00</published><updated>2024-11-02T14:45:00+00:00</updated><id>https://vyhaophan.github.io/blog/2024/assistant-function-call</id><content type="html" xml:base="https://vyhaophan.github.io/blog/2024/assistant-function-call/"><![CDATA[<h2 id="overview">Overview</h2> <p>Let’s imaging you want to have a continuous private secretary with you all the time. She may help you to schedule your meetings, send emails, book a cab, etc. She even can take notes for you and remember the things you told her, she would never bring you more tasks because she always handle every single task immediately with the highest quality.</p> <p>I have dreamt of owning such a secretary for a long time, but I never found one. However, I found a way to build my own multi-function assistant with OpenAI API. As an Data Scientist with an intense load of work, I am always busy and I need an assistant which can do the following things:</p> <ul> <li>Take notes by listening to me and my meetings</li> <li>Send or schedule emails</li> <li>Remind me of important meetings or events</li> <li>Help me enjoy my personal life (tell me a joke, play music, instruct me to do gym properly, etc.)</li> <li>Update me the latest news about my interests (e.g., sports, stocks, etc.) while I am driving</li> <li>…</li> </ul> <p>Another scenario when I have my own online shop of coffee, I really need an assistant to help me manage my online shop. For example, at the end of the day, I need her to:</p> <ul> <li>Check my inventory and tell me to restock the items which are running out of stock</li> <li>Send me the total revenue and profit of the day</li> <li>Tell me the number of orders I have received during the day/ week/ month…</li> <li>Give me some analysis on those figures and maybe some suggestions to improve my business</li> <li>…</li> </ul> <div class="row"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/2024-11-02-assistant-function-call/assistant_img1_1102-480.webp 480w,/assets/img/2024-11-02-assistant-function-call/assistant_img1_1102-800.webp 800w,/assets/img/2024-11-02-assistant-function-call/assistant_img1_1102-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/2024-11-02-assistant-function-call/assistant_img1_1102.jpg" class="img-fluid rounded z-depth-1" width="100%" height="auto" title="generated with DALL·E 3" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/2024-11-02-assistant-function-call/assistant_coffee_shop_seller-480.webp 480w,/assets/img/2024-11-02-assistant-function-call/assistant_coffee_shop_seller-800.webp 800w,/assets/img/2024-11-02-assistant-function-call/assistant_coffee_shop_seller-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/2024-11-02-assistant-function-call/assistant_coffee_shop_seller.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" title="generated with DALL·E 3" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> An AI Assistant help analysing the business performance. </div> <p>Have you ever thought about how this kind of assistant works? In this post, I will guide you to set up a multi-function assistant with OpenAI API.</p> <p>To be more related to a real-world scenario, in this post, I will make a guidance on a <strong>multi-function coffee shop assistant</strong>.</p> <h2 id="introduction-to-openai-assistants-functions">Introduction to OpenAI Assistant’s Functions</h2> <p>Okay, before we actually build an assistant, I need to introduce you to the concept of <strong>Functions</strong> in OpenAI Assistant. After you grasp the whole picture of how the assistant works, the rest of the steps will be easy for you.</p> <p>The diagram below shows how the assistant works.</p> <ul> <li>Imagine you already have a multi-function assistant, and an application to interact and give commands to the assistant.</li> <li>When you give a question or a request to the application, the application will send the request to the assistant.</li> <li>The assistant will understand your request and decide whether to call the functions you defined or not.</li> <li>If the assistant decides to call the functions, it wisely choose a function that is most likely to answer your request. Moreover, it will also extract the argument values in your request for the corresponding functions.</li> <li>The application will receive the function call and execute the functions with the arguments you provided.</li> <li>Finally, the assistant will generate a response based on the results from the functions and send it back to the application.</li> <li>The application will then display the response to you.</li> </ul> <pre><code class="language-typograms">    +---------------------------+                       +---------------------------+
    |         Your code         |                       |         OpenAI LLM        |
    +---------------------------+                       +---------------------------+
    |   +-------------------------------------------------------+                   |
    |   |    You give a question (request) to the application   |                   |
    |   +-------------------------------------------------------+                   |
    |                              |                                                |
    |                              V                                                |
    |   +--------------------------------------------------------+                  |
    |   |     OpenAI API triggered with your defined prompt      |                  |
    |   |                and function definitions                |----------------&gt; |
    |   +--------------------------------------------------------+                  |
    |                      +--------------------------------------------------------+
    |                      |    API decides whether to respond with functions call  |
    |                      |          or just a response to your question           |
    |                      +--------------------------------------------------------+
    |                                                   |                           |
    |                                                   V                           |
    |                      +--------------------------------------------------------+
    |                      |  API identifies the argument values in prompt provided |
    |                      |            for the corresponding functions             |
    |                      +--------------------------------------------------------+
    |                                                   |                           |
    |                                                   V                           |
    |                      +--------------------------------------------------------+
    |&lt;---------------------| Functions are called from API and arguments are passed |
    |                      |        to the application to generate results          |
    |                      +--------------------------------------------------------+
    |   +-------------------------------------------------------+                   |
    |--&gt;|Application uses the arguments to execute the functions|------------------&gt;|
    |   +-------------------------------------------------------+                   |
    |                      +--------------------------------------------------------+
    |&lt;---------------------|    OpenAI uses the results to generate a response      |
    |                      +--------------------------------------------------------+
</code></pre> <p>Is there anything vague here? If yes, please share with me. If you are not sure about the details, don’t worry, we will go through each step in the following sections.</p> <h3 id="i-have-understood-the-concept-what-should-i-do-next">I have understood the concept, what should I do next?</h3> <p>Here is a quick summary of what you have to do to take advantage of the assistant’s functions:</p> <ul> <li>Create an assistant with the <strong>system prompt</strong> which is the overall instruction for the assistant and not related to any specific function. When the assistant decides to answer without using functions, its behavior will follow this prompt.</li> <li>Define your <strong>functions that are tailored for your specific use case</strong>. These functions have their own <strong>prompt instructions</strong> and their <strong>arguments</strong> schema that it needs to extract from the user’s request.</li> <li>Please note that your <strong>function prompt</strong> should be clear and concise because the Assistant will use these prompt to decide which function to call, and the <strong>arguments</strong> schema should be designed in a way that it is easy to understand and extract values from the user’s request.</li> <li>Create an <strong>application</strong> to interact with the assistant.</li> </ul> <h2 id="assistant-setup">Assistant Setup</h2> <h3 id="function-design">Function Design</h3> <p>In this section, I’ll tell you how I design 2 functions for the assistant.</p> <p>Let’s say I have established this <strong>database</strong> for my coffee shop.</p> <ul> <li>The table <code class="language-plaintext highlighter-rouge">CUSTOMER</code> contains information about customers (name, age, address, and their rank based on their purchase history) with the primary key <code class="language-plaintext highlighter-rouge">customer_id</code>.</li> <li>The table <code class="language-plaintext highlighter-rouge">PRODUCT</code> contains information about products (the name of that unit product, unit weight, base price of one unit, and quantity in stock) with the primary key <code class="language-plaintext highlighter-rouge">product_id</code>.</li> <li>The table <code class="language-plaintext highlighter-rouge">SALES</code> contains information about sales (purchasing customer, revenue of the bill, datetime, and any note) with the primary key <code class="language-plaintext highlighter-rouge">sale_id</code>.</li> <li>The table <code class="language-plaintext highlighter-rouge">SALES_DETAIL</code> contains detailed information about each sale (sale id, product id, quantity, discount, datetime), this table is the <code class="language-plaintext highlighter-rouge">fact</code> table that links to all the other tables.</li> </ul> <pre><code class="language-typograms">    +--------------+            +-------------+
    |   CUSTOMER   |            |   PRODUCT   |
    |--------------|            |-------------|
    | customer_id  |---         | product_id  |
    | customer_name|  |         | product_name|
    | age          |  |         | weight      |
    | address      |  |         | base_price  |
    | rank         |  |         | qty_in_stock|
    +--------------+  |         +-------------+
          |           |             ^
          |           |             |
          |           |             |
          |           |             |
          |           |       +---------------+
    +-------------+   |       | SALES_DETAIL  |
    |    SALES    |   |       |---------------|
    |-------------|   |       | sale_detail_id|
    | sale_id     |---------&gt; | sale_id       |
    | customer_id |   |       | product_id    |
    | revenue     |   -------&gt;| customer_id   |
    | datetime    |           | quantity      |
    +-------------+           | note          |
                              | discount      |
                              | datetime      |
                              +---------------+
</code></pre> <p>If I didn’t have an assistant, I would have to manually write the SQL queries to extract the information I need from the database. For the tasks that I mentioned in the introduction, I would have to write the following SQL queries:</p> <ul> <li>To check the inventory of each product and see which products are running out of stock and need to be restocked: <code class="language-plaintext highlighter-rouge">SELECT * FROM PRODUCT WHERE qty_in_stock &lt; 10;</code></li> <li>To check the total revenue and profit of today, or yesterday, or last week, or last month, etc.: <code class="language-plaintext highlighter-rouge">SELECT s.revenue AS total_revenue, SUM(sd.quantity * p.base_price * (1 - sd.discount)) AS total_profit FROM SALES s JOIN SALES_DETAIL sd ON s.sale_id = sd.sale_id JOIN PRODUCT p ON sd.product_id = p.product_id WHERE DATE(s.datetime) = CURDATE();</code></li> </ul> <p>However, I don’t want to do this mind-numbing work, I want my assistant to do this for me. Therefore, I now define these two functions as follows:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">connect_to_database</span><span class="p">():</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">connection</span> <span class="o">=</span> <span class="n">mysql</span><span class="p">.</span><span class="n">connector</span><span class="p">.</span><span class="nf">connect</span><span class="p">(</span>
            <span class="n">host</span><span class="o">=</span><span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="sh">"</span><span class="s">DB_HOST</span><span class="sh">"</span><span class="p">),</span>
            <span class="n">user</span><span class="o">=</span><span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="sh">"</span><span class="s">DB_USER</span><span class="sh">"</span><span class="p">),</span> 
            <span class="n">password</span><span class="o">=</span><span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="sh">"</span><span class="s">DB_PASSWORD</span><span class="sh">"</span><span class="p">),</span>
            <span class="n">database</span><span class="o">=</span><span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="sh">"</span><span class="s">DB_NAME</span><span class="sh">"</span><span class="p">)</span>
        <span class="p">)</span>
        
        <span class="n">cursor</span> <span class="o">=</span> <span class="n">connection</span><span class="p">.</span><span class="nf">cursor</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">cursor</span>
    <span class="k">except</span> <span class="n">mysql</span><span class="p">.</span><span class="n">connector</span><span class="p">.</span><span class="n">Error</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
        <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Error connecting to MySQL database: </span><span class="si">{</span><span class="n">err</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">None</span>

<span class="k">def</span> <span class="nf">check_out_of_stock</span><span class="p">(</span><span class="n">token</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span>
    <span class="k">assert</span> <span class="nf">check_valid_token</span><span class="p">(</span><span class="n">token</span><span class="p">),</span> <span class="sh">"</span><span class="s">Invalid token</span><span class="sh">"</span>
    <span class="c1"># Connect to MySQL database
</span>    <span class="n">cursor</span> <span class="o">=</span> <span class="nf">connect_to_database</span><span class="p">()</span>
    <span class="c1"># check the inventory of each product and see which products are running out of stock and need to be restocked
</span>    <span class="n">query</span> <span class="o">=</span> <span class="sh">"""</span><span class="s">
        SELECT * FROM PRODUCT 
        WHERE qty_in_stock &lt; 10;
    </span><span class="sh">"""</span>
    <span class="k">if</span> <span class="n">cursor</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">cursor</span><span class="p">.</span><span class="nf">execute</span><span class="p">(</span><span class="n">query</span><span class="p">)</span>
        <span class="n">results</span> <span class="o">=</span> <span class="n">cursor</span><span class="p">.</span><span class="nf">fetchall</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">results</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="sh">"</span><span class="s">An error occurred while connecting to the database.</span><span class="sh">"</span>

<span class="k">def</span> <span class="nf">check_daily_revenue</span><span class="p">(</span><span class="n">date</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span>
    <span class="k">assert</span> <span class="nf">check_valid_token</span><span class="p">(</span><span class="n">token</span><span class="p">),</span> <span class="sh">"</span><span class="s">Invalid token</span><span class="sh">"</span>
    <span class="c1"># Connect to MySQL database
</span>    <span class="n">cursor</span> <span class="o">=</span> <span class="nf">connect_to_database</span><span class="p">()</span>
    <span class="c1"># check the total revenue and profit of today, or yesterday, or last week, or last month, etc.
</span>    <span class="n">query</span> <span class="o">=</span> <span class="sa">f</span><span class="sh">"""</span><span class="s">
        SELECT 
            s.revenue AS total_revenue,
            SUM(sd.quantity * p.base_price * (1 - sd.discount)) AS total_profit 
        FROM SALES s
        JOIN SALES_DETAIL sd ON s.sale_id = sd.sale_id 
        JOIN PRODUCT p ON sd.product_id = p.product_id
        WHERE DATE(s.datetime) = </span><span class="sh">'</span><span class="si">{</span><span class="n">date</span><span class="si">}</span><span class="sh">'</span><span class="s">;
    </span><span class="sh">"""</span>
    <span class="k">if</span> <span class="n">cursor</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">cursor</span><span class="p">.</span><span class="nf">execute</span><span class="p">(</span><span class="n">query</span><span class="p">)</span>
        <span class="n">results</span> <span class="o">=</span> <span class="n">cursor</span><span class="p">.</span><span class="nf">fetchall</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">results</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="sh">"</span><span class="s">An error occurred while connecting to the database.</span><span class="sh">"</span>
</code></pre></div></div> <p>In short, I now have 2 functions:</p> <ul> <li><code class="language-plaintext highlighter-rouge">check_out_of_stock</code>: to check the inventory to see which products need to be restocked (their quantity in stock is less than 10). <ul> <li>Arguments: <code class="language-plaintext highlighter-rouge">None</code>.</li> </ul> </li> <li><code class="language-plaintext highlighter-rouge">check_daily_revenue</code>: to check the total revenue and profit of the date specified by the user. <ul> <li>Arguments: <code class="language-plaintext highlighter-rouge">date</code> (str): the date to check the revenue and profit.</li> </ul> </li> </ul> <p>These functions will be used by the assistant to answer the user’s request. In the next section, I will tell you how to create an assistant with the above functions.</p> <h3 id="account-creation">Account Creation</h3> <p>First, you need to create an account on OpenAI and get the API key. You can refer to <a href="https://platform.openai.com/api-keys">this link</a> to get the API key. Then, run the following code to set up the environment variables:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">os</span> 
<span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">[</span><span class="sh">"</span><span class="s">OPENAI_API_KEY</span><span class="sh">"</span><span class="p">]</span> <span class="o">=</span> <span class="sh">"</span><span class="s">your_api_key</span><span class="sh">"</span>
</code></pre></div></div> <h3 id="assistant-creation">Assistant Creation</h3> <p>First, you need to think about writing your assistant’s <strong>system prompt</strong>. This prompt should be context-specific to tell the assistant how to behave as the powerful assistant for the coffee shop. Below is my system prompt which</p> <ul> <li>Tell the assistant about its name, working place, and its business vision.</li> <li>Tell the assistant the scope of its responsibilities.</li> <li>Tell the assistant only use the functions that are provided to it and do not do any other tasks.</li> <li>Tell the assistant to format the results clearly using bullet points.</li> <li>Tell the assistant to maintain a friendly, concise, and human-like tone.</li> </ul> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">system_prompt</span> <span class="o">=</span> <span class="sh">"""</span><span class="s">
Your name is Coffee Assistant working at the Xi Pho Coffee shop which focuses on delivering the forest farmed organic coffee to all the customers living in Vietnam. 
Your primary focus is to assist with report generation, provide insights from data analysis, support the business operations and improve the management.
Remember to stay within the scope of business and financial management, use the provided functions to retrieve data, format results clearly using bullet points, and maintain a friendly, concise, and human-like tone. Refrain from addressing tasks outside the scope.
</span><span class="sh">"""</span>
</code></pre></div></div> <p>You have your right to creatively create a system prompt, but please keep it follow my instructions above which I think is the most important core of the assistant. However, you can add other things that I may miss mentioning. If you have any more ideas on a better system prompt, please share.</p> <p>Secondly, you should consider which model the assistant would use. At the time of writing this post, the most powerful models are the <code class="language-plaintext highlighter-rouge">GPT-4o</code> family. I recommend using <code class="language-plaintext highlighter-rouge">GPT-4o-mini</code> or <code class="language-plaintext highlighter-rouge">GPT-4o</code> for their outstanding reasoning, problem-solving capabilities, and their speed. If budget is your concern, you can use <code class="language-plaintext highlighter-rouge">GPT-4o-mini</code> which is cheaper.</p> <p>Thirdly, this is optional, you can set up the parameters for the assistant performance. You should adjust the <code class="language-plaintext highlighter-rouge">temperature</code> or <code class="language-plaintext highlighter-rouge">top_p</code> (but not both at the same time) to control the assistant’s creativity. The parameters will keep their own default values except when you change them.</p> <p>For now, you can create the assistant by running the following code:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">openai</span> <span class="kn">import</span> <span class="n">OpenAI</span>
<span class="n">client</span> <span class="o">=</span> <span class="nc">OpenAI</span><span class="p">()</span>
<span class="n">my_assistant</span> <span class="o">=</span> <span class="n">client</span><span class="p">.</span><span class="n">beta</span><span class="p">.</span><span class="n">assistants</span><span class="p">.</span><span class="nf">create</span><span class="p">(</span>
    <span class="n">instructions</span><span class="o">=</span><span class="n">system_prompt</span><span class="p">,</span> <span class="c1"># we already defined the system prompt
</span>    <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">Coffee Assistant</span><span class="sh">"</span><span class="p">,</span> <span class="c1"># I name my assistant as Coffee Assistant
</span>    <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">gpt-4o</span><span class="sh">"</span><span class="p">,</span> <span class="c1"># or "gpt-4o-mini" or other model you prefer
</span>    <span class="n">temperature</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="c1"># default value
</span>    <span class="n">top_p</span><span class="o">=</span><span class="mi">1</span> <span class="c1"># default value
</span><span class="p">)</span>
</code></pre></div></div> <p>If it created successfully, you will see the assistant id in the response.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Assistant(id='asst_HTv8wO9TKLvL00HSdd******', created_at=1730647004, description=None, instructions='\nYour name is Coffee Assistant working at the Xi Pho Coffee shop which focuses on delivering the forest farmed organic coffee to all the customers living in Vietnam. \nYour primary focus is to assist with report generation, provide insights from data analysis, support the business operations and improve the management.\nRemember to stay within the scope of business and financial management, use the provided functions to retrieve data, format results clearly using bullet points, and maintain a friendly, concise, and human-like tone. Refrain from addressing tasks outside the scope.\n', metadata={}, model='gpt-4o', name='Coffee Assistant', object='assistant', tools=[], response_format='auto', temperature=1.0, tool_resources=ToolResources(code_interpreter=None, file_search=None), top_p=1.0)
</code></pre></div></div> <details> <summary>Wait, you forgot something?</summary> Right, the functions are not defined yet. 😅 Don't worry, we will do that in the next section. </details> <h3 id="tools-creation">Tools Creation</h3> <p>Okay, in the previous section, we have already defined two functions to manage our coffe store, now we need to tell the assistant to use these functions by updating the assistant.</p> <p>The Assistant understands your functions if your function definitions are as follows:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span>
  <span class="p">{</span>
    <span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">function</span><span class="sh">'</span><span class="p">,</span>
    <span class="sh">'</span><span class="s">function</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span>
      <span class="sh">'</span><span class="s">name</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">Your Function Name</span><span class="sh">'</span><span class="p">,</span> 
      <span class="sh">'</span><span class="s">description</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">The prompt for this function</span><span class="sh">'</span><span class="p">,</span>
      <span class="sh">'</span><span class="s">parameters</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span>
        <span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">object</span><span class="sh">'</span><span class="p">,</span>
        <span class="sh">'</span><span class="s">properties</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span>
          <span class="sh">'</span><span class="s">param1</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span><span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">string</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">description</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">Parameter 1 description (prompt)</span><span class="sh">'</span><span class="p">},</span>
          <span class="sh">'</span><span class="s">param2</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span><span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">integer</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">description</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">Parameter 2 description (prompt)</span><span class="sh">'</span><span class="p">}</span>
        <span class="p">},</span>
        <span class="sh">'</span><span class="s">required</span><span class="sh">'</span><span class="p">:</span> <span class="p">[</span><span class="sh">'</span><span class="s">param1</span><span class="sh">'</span><span class="p">]</span>
      <span class="p">}</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">]</span>
</code></pre></div></div> <p>You need to create:</p> <ul> <li>The function <strong>name</strong>.</li> <li>The <strong>prompt</strong> for that function (can be called <strong>function description</strong>). This prompt should clearly describe what the function does and how it is designed differently from other functions. This is important because when the assistant decides to call a function, it will use this prompt to decide which function to call. Unless the prompt clearly tells the difference between functions, the assistant may call the wrong function.</li> <li>The <strong>parameters</strong> for each function. Each parameter has a <strong>type</strong> (string, integer, etc.), a <strong>description</strong> (a prompt clearly tells assistant how to extract the value of that parameter from the user’s request), and it must be defined if this parameter is <strong>required</strong>.</li> </ul> <p>Come back to our example, the function definitions should be:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">function_definitions</span> <span class="o">=</span> <span class="p">[</span>
  <span class="p">{</span>
    <span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">function</span><span class="sh">'</span><span class="p">,</span>
    <span class="sh">'</span><span class="s">function</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span>
      <span class="sh">'</span><span class="s">name</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">CheckOutOfStock</span><span class="sh">'</span><span class="p">,</span> 
      <span class="sh">'</span><span class="s">description</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">Use this function to check the inventory of each product and see which products are running out of stock and need to be restocked</span><span class="sh">'</span><span class="p">,</span>
      <span class="sh">'</span><span class="s">parameters</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span>
        <span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">object</span><span class="sh">'</span><span class="p">,</span>
        <span class="sh">'</span><span class="s">properties</span><span class="sh">'</span><span class="p">:</span> <span class="p">{}</span>
      <span class="p">}</span>
    <span class="p">}</span>
  <span class="p">},</span>
  <span class="p">{</span>
    <span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">function</span><span class="sh">'</span><span class="p">,</span>
    <span class="sh">'</span><span class="s">function</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span>
      <span class="sh">'</span><span class="s">name</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">CheckDailyRevenue</span><span class="sh">'</span><span class="p">,</span>
      <span class="sh">'</span><span class="s">description</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">Use this function to check the total revenue and profit of the date specified by the user</span><span class="sh">'</span><span class="p">,</span>
      <span class="sh">'</span><span class="s">parameters</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span>
        <span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">object</span><span class="sh">'</span><span class="p">,</span>
        <span class="sh">'</span><span class="s">properties</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span>
          <span class="sh">'</span><span class="s">date</span><span class="sh">'</span><span class="p">:</span> <span class="p">{</span><span class="sh">'</span><span class="s">type</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">string</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">description</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">The date to check the revenue and profit</span><span class="sh">'</span><span class="p">}</span>
        <span class="p">},</span>
        <span class="sh">'</span><span class="s">required</span><span class="sh">'</span><span class="p">:</span> <span class="p">[</span><span class="sh">'</span><span class="s">date</span><span class="sh">'</span><span class="p">]</span>
      <span class="p">}</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">]</span>
</code></pre></div></div> <p>What have we done here?</p> <ul> <li>We have defined the <strong>function name</strong> for each function: <code class="language-plaintext highlighter-rouge">CheckOutOfStock</code> and <code class="language-plaintext highlighter-rouge">CheckDailyRevenue</code>.</li> <li>We have defined the <strong>function description</strong> for each function: <ul> <li><strong>CheckOutOfStock</strong>: <code class="language-plaintext highlighter-rouge">Use this function to check the inventory of each product and see which products are running out of stock and need to be restocked</code></li> <li><strong>CheckDailyRevenue</strong>: <code class="language-plaintext highlighter-rouge">Use this function to check the total revenue and profit of the date specified by the user</code></li> </ul> </li> <li>We have defined the <strong>parameters</strong> for each function: <ul> <li><strong>CheckOutOfStock</strong>: <code class="language-plaintext highlighter-rouge">None</code> (this function does not require any parameters)</li> <li><strong>CheckDailyRevenue</strong>: <code class="language-plaintext highlighter-rouge">date</code> (this function requires a <code class="language-plaintext highlighter-rouge">date</code> parameter)</li> </ul> </li> </ul> <p>Okay here we go, let’s update the assistant with the function definitions:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">assistant_updated</span> <span class="o">=</span> <span class="n">client</span><span class="p">.</span><span class="n">beta</span><span class="p">.</span><span class="n">assistants</span><span class="p">.</span><span class="nf">update</span><span class="p">(</span>
    <span class="n">assistant_id</span><span class="o">=</span><span class="n">my_assistant</span><span class="p">.</span><span class="nb">id</span><span class="p">,</span> 
    <span class="n">tools</span><span class="o">=</span><span class="n">function_definitions</span>
<span class="p">)</span>
</code></pre></div></div> <p>Congratulations! You have created your assistant with the functions. If you navigate to the assistant page in the OpenAI platform at <a href="https://platform.openai.com/assistants/{assistant_id}">https://platform.openai.com/assistants/{assistant_id}</a>, you will see the assistant with the functions you just defined.</p> <div class="row"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/2024-11-02-assistant-function-call/openai_assistant_coffee-480.webp 480w,/assets/img/2024-11-02-assistant-function-call/openai_assistant_coffee-800.webp 800w,/assets/img/2024-11-02-assistant-function-call/openai_assistant_coffee-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/2024-11-02-assistant-function-call/openai_assistant_coffee.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" title="My first Coffee Assistant" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> Coffee Assistant </div> <h2 id="your-first-chat-with-the-assistant">Your first chat with the Assistant</h2> <p>Navigate to your assistant page and click on the icon <strong>Playground ↗</strong> to interact with the assistant.</p> <div class="row"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/2024-11-02-assistant-function-call/playground_click-480.webp 480w,/assets/img/2024-11-02-assistant-function-call/playground_click-800.webp 800w,/assets/img/2024-11-02-assistant-function-call/playground_click-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/2024-11-02-assistant-function-call/playground_click.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" title="My first Coffee Assistant" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> Click on the Playground icon </div> <p>Now I have just tried to ask the assistant to give me the total revenue of Nov 1st, 2024.</p> <div class="row"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/2024-11-02-assistant-function-call/playground_first_chat-480.webp 480w,/assets/img/2024-11-02-assistant-function-call/playground_first_chat-800.webp 800w,/assets/img/2024-11-02-assistant-function-call/playground_first_chat-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/2024-11-02-assistant-function-call/playground_first_chat.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" title="My first Coffee Assistant" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> First chat with Assistant </div> <p>As seen in the screenshot, the assistant has called the <code class="language-plaintext highlighter-rouge">CheckDailyRevenue</code> function with the date <code class="language-plaintext highlighter-rouge">2024-11-01</code> as the argument. Therefore, you know the assistant has understood the function call and the argument. You have successfully set up your first multi-function assistant.</p> <h2 id="whats-next">What’s next?</h2> <p>In the next post, I will guide you to build <strong>a simple chatting application</strong> to interact with the assistant. Currently, the assistant is only available on the OpenAI platform. In the real world, no one go there to chat with the assistant, so an application is necessary for the assistant to be useful.</p> <p>Stay tuned!</p>]]></content><author><name></name></author><category term="assistant"/><category term="openai"/><category term="functioncall"/><summary type="html"><![CDATA[In this post, I will guide you to create a multi-function assistant with OpenAI]]></summary></entry><entry><title type="html">How I quickly developed a custom ChatGPT in a few hours</title><link href="https://vyhaophan.github.io/blog/2023/how-i-quickly-developed-a-custom-chatgpt-in-a-few-hours/" rel="alternate" type="text/html" title="How I quickly developed a custom ChatGPT in a few hours"/><published>2023-12-02T15:50:32+00:00</published><updated>2023-12-02T15:50:32+00:00</updated><id>https://vyhaophan.github.io/blog/2023/how-i-quickly-developed-a-custom-chatgpt-in-a-few-hours</id><content type="html" xml:base="https://vyhaophan.github.io/blog/2023/how-i-quickly-developed-a-custom-chatgpt-in-a-few-hours/"><![CDATA[]]></content><author><name></name></author></entry><entry><title type="html">A Brief History of Masked Image Modeling Family</title><link href="https://vyhaophan.github.io/blog/2023/a-brief-history-of-masked-image-modeling-family/" rel="alternate" type="text/html" title="A Brief History of Masked Image Modeling Family"/><published>2023-10-15T04:22:27+00:00</published><updated>2023-10-15T04:22:27+00:00</updated><id>https://vyhaophan.github.io/blog/2023/a-brief-history-of-masked-image-modeling-family</id><content type="html" xml:base="https://vyhaophan.github.io/blog/2023/a-brief-history-of-masked-image-modeling-family/"><![CDATA[]]></content><author><name></name></author></entry></feed>