Open AI

Using OpenAi’s API calls and prompt engineering

load_dotenv(find_dotenv())

openai.api_key = os.getenv('OPENAI_API_KEY')
def get_complet(prompt, model='gpt-3.5-turbo', temperature=0):
    messages = [{'role':'user', 'content':prompt}]
    resp = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature)
    
    return resp.choices[0].message['content']
prompt = '''
Cite the 5 more relevant sentiments related to the following text surrounded by ```

```I think this is not going to be quite what you expect```
'''
response = get_complet(prompt)
print(response)
1. Disappointment
2. Uncertainty
3. Skepticism
4. Pessimism
5. Apprehension
prompt = '''
Present in a technical and objective manner the steps for calculating the Population Stability Index.
'''
response = get_complet(prompt)
print(response)
The Population Stability Index (PSI) is a statistical measure used to assess the stability of a population over time. It is commonly used in the field of credit risk management to monitor changes in the creditworthiness of a portfolio of borrowers. The PSI is calculated by following these steps:

1. Divide the population into two groups: the reference group and the comparison group. The reference group is typically the population at a specific point in time, such as the current year, while the comparison group is the population at a previous point in time, such as the previous year.

2. Calculate the percentage of each group in each of several predefined score ranges. For example, if the score range is 0-100, the percentage of borrowers in each range would be calculated for both the reference and comparison groups.

3. Calculate the expected percentage of borrowers in each score range for the reference group. This can be done by multiplying the total number of borrowers in the reference group by the percentage of borrowers in each score range.

4. Calculate the actual percentage of borrowers in each score range for the comparison group. This can be done by multiplying the total number of borrowers in the comparison group by the percentage of borrowers in each score range.

5. Calculate the PSI for each score range by using the following formula: PSI = (Actual Percentage - Expected Percentage) * ln(Actual Percentage / Expected Percentage)

6. Sum the PSI values for all score ranges to obtain the overall PSI for the population.

A PSI value of less than 0.1 is generally considered to indicate a stable population, while a value greater than 0.25 indicates significant changes in the population. The PSI can be used to identify areas of the population that are experiencing significant changes, which can help lenders to adjust their risk management strategies accordingly.
prompt = '''
Give pros and cons of using ks-test, t-test, jensen-shannon, wasserstein distance or psi \
for data drift detection as a table.
The response should be organized as an HTML table.
'''
response = get_complet(prompt)
print(response)
<table>
  <tr>
    <th>Method</th>
    <th>Pros</th>
    <th>Cons</th>
  </tr>
  <tr>
    <td>KS-test</td>
    <td>Easy to implement, widely used, suitable for continuous data</td>
    <td>Assumes normal distribution, may not work well for small sample sizes</td>
  </tr>
  <tr>
    <td>t-test</td>
    <td>Easy to implement, widely used, suitable for continuous data</td>
    <td>Assumes normal distribution, may not work well for small sample sizes, requires equal variances</td>
  </tr>
  <tr>
    <td>Jensen-Shannon</td>
    <td>Works well for both continuous and discrete data, does not assume normal distribution</td>
    <td>May be computationally expensive for large datasets, may not work well for high-dimensional data</td>
  </tr>
  <tr>
    <td>Wasserstein distance</td>
    <td>Works well for both continuous and discrete data, does not assume normal distribution</td>
    <td>May be computationally expensive for large datasets, may not work well for high-dimensional data</td>
  </tr>
  <tr>
    <td>PSI</td>
    <td>Can detect both magnitude and direction of drift, suitable for both continuous and categorical data</td>
    <td>May be sensitive to small changes, may require a large reference dataset</td>
  </tr>
</table>
displayplay(HTML(response))
Method Pros Cons
KS-test Easy to implement, widely used, suitable for continuous data Assumes normal distribution, may not work well for small sample sizes
t-test Easy to implement, widely used, suitable for continuous data Assumes normal distribution, may not work well for small sample sizes, requires equal variances
Jensen-Shannon Works well for both continuous and discrete data, does not assume normal distribution May be computationally expensive for large datasets, may not work well for high-dimensional data
Wasserstein distance Works well for both continuous and discrete data, does not assume normal distribution May be computationally expensive for large datasets, may not work well for high-dimensional data
PSI Can detect both magnitude and direction of drift, suitable for both continuous and categorical data May be sensitive to small changes, may require a large reference dataset
prompt = '''
Write code in python or C/C++ to capture voice commands
'''
response = get_complet(prompt)
print(response)
Python code:

import speech_recognition as sr

# initialize the recognizer
r = sr.Recognizer()

# use the microphone as source
with sr.Microphone() as source:
    print("Speak something...")
    audio = r.listen(source)

# recognize speech using Google Speech Recognition
try:
    print("You said: " + r.recognize_google(audio))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))

C/C++ code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sphinxbase/ad.h>
#include <pocketsphinx.h>

int main(int argc, char *argv[]) {
    ps_decoder_t *ps;
    cmd_ln_t *config;
    FILE *fh;
    char const *hyp, *uttid;
    int16 buf[512];
    int rv;
    int32 score;

    config = cmd_ln_init(NULL, ps_args(), TRUE,
                 "-hmm", MODELDIR "/en-us/en-us",
                 "-lm", MODELDIR "/en-us/en-us.lm.bin",
                 "-dict", MODELDIR "/en-us/cmudict-en-us.dict",
                 NULL);

    if (config == NULL) {
        fprintf(stderr, "Failed to create config object, see log for details\n");
        return -1;
    }

    ps = ps_init(config);
    if (ps == NULL) {
        fprintf(stderr, "Failed to create recognizer, see log for details\n");
        return -1;
    }

    fh = fopen("test.wav", "rb");
    if (fh == NULL) {
        fprintf(stderr, "Unable to open input file\n");
        return -1;
    }

    rv = ps_decode_raw(ps, fh, "test", -1);
    if (rv < 0) {
        fprintf(stderr, "Failed to decode audio file, see log for details\n");
        return -1;
    }

    hyp = ps_get_hyp(ps, &score);
    printf("Recognized: %s\n", hyp);

    fclose(fh);
    ps_free(ps);
    cmd_ln_free_r(config);

    return 0;
}

back to top

Expanding

# given the sentiment from the lesson on "inferring",
# and the original customer message, customize the email
sentiment = "negative"

# review for a blender
review = f"""
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \ 
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \ 
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \ 
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""
prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service. 
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_complet(prompt)
print(response)
Dear valued customer,

Thank you for taking the time to leave a review about our product. We are sorry to hear that you experienced a price increase and that the quality of the product did not meet your expectations. We apologize for any inconvenience this may have caused you.

If you have any further concerns or questions, please do not hesitate to reach out to our customer service team. They will be more than happy to assist you in any way they can.

Thank you again for your feedback. We appreciate your business and hope to have the opportunity to serve you better in the future.

Best regards,

AI customer agent
prompt2 = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service. 
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_complet(prompt2, temperature=0.7)
print(response)
Dear Customer,

Thank you for taking the time to leave a review. We apologize for any inconvenience you experienced with the pricing of our products. We strive to provide the best value possible to our customers, and we're sorry we fell short in this instance. We appreciate your feedback on the quality of our products and will take it into consideration as we continue to improve.

We understand your frustration with the motor issue you experienced, and we apologize for any inconvenience this may have caused. If you have any further concerns, please do not hesitate to reach out to our customer service team for assistance. They will be more than happy to help you resolve any issues you may have.

Thank you again for your feedback, and we hope to have the opportunity to serve you better in the future.

Best regards,
AI customer agent

back to top

ChatBot

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
#     print(str(response.choices[0].message))
    return response.choices[0].message["content"]
def collect_messages(_):
    prompt = inp.value_input
    inp.value = ''
    context.append({'role':'user', 'content':f"{prompt}"})
    response = get_completion_from_messages(context) 
    context.append({'role':'assistant', 'content':f"{response}"})
    panels.append(
        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))
    panels.append(
        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))
 
    return pn.Column(*panels)
pn.extension()

panels = [] # collect display 

context = [ {'role':'system', 'content':"""
You are OrderBot, an automated service to collect orders for a pizza restaurant. \
You first greet the customer, then collects the order, \
and then asks if it's a pickup or delivery. \
You wait to collect the entire order, then summarize it and check for a final \
time if the customer wants to add anything else. \
If it's a delivery, you ask for an address. \
Finally you collect the payment.\
Make sure to clarify all options, extras and sizes to uniquely \
identify the item from the menu.\
You respond in a short, very conversational friendly style. \
The menu includes \
pepperoni pizza  12.95, 10.00, 7.00 \
cheese pizza   10.95, 9.25, 6.50 \
eggplant pizza   11.95, 9.75, 6.75 \
fries 4.50, 3.50 \
greek salad 7.25 \
Toppings: \
extra cheese 2.00, \
mushrooms 1.50 \
sausage 3.00 \
canadian bacon 3.50 \
AI sauce 1.50 \
peppers 1.00 \
Drinks: \
coke 3.00, 2.00, 1.00 \
sprite 3.00, 2.00, 1.00 \
bottled water 5.00 \
"""} ]  # accumulate messages


inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Chat!")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

dashboard
messages =  context.copy()
messages.append(
{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\
 The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},    
)
 #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},    

response = get_completion_from_messages(messages, temperature=0)
print(response)

back to top