Remembering the previous conversation of a chatbot - python

I have created a basic ChatBot using OpenAI with the following code:
import openai
openai.api_key = "sk-xxx"
while True:
prompt = input("User:")
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
max_tokens=50,
temperature=0,
)
print(response.choices[0].text)
This is the input and output:
And in text form:
User:What is python
Python is a high-level, interpreted, general-purpose programming language. It is a powerful and versatile language that is used for a wide range of applications, from web development and software development to data science and machine learning.`
User:What is the Latest Version of it?
The latest version of Microsoft Office is Microsoft Office 2019.
As you can see i am asking questions related to python and asking version of it gives answer related to Microsoft Office, whereas when asking the same question to ChatGpt it remembers the previous conservation and acts according to it.
Is there any solution for remembering the conversation?

One possibility would be to store the inputs and outputs somewhere, and then include them in subsequent inputs. This is very rudimentary but you could do something like the following:
inputs, outputs = [], []
while True:
prompt = input("Enter input (or 'quit' to exit):")
if prompt == 'quit':
break
if len(inputs) > 0:
inputs.append(prompt)
last_input, last_output = inputs[-1], outputs[-1]
prompt = f"{prompt} (based on my previous question: {last_input}, and your previous answer {last_output}"
else:
inputs.append(prompt)
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
max_tokens=200,
temperature=0,
)
output = response.choices[0].text
outputs.append(output)
print(output)
This program would be able to recall the last input and output, and provide that information along with the current prompt. You could include more lines of input and output depending on how much "memory" you want your program to have, and there is also a text limit (max_tokens), so you may need to adjust the wording so that the entire prompt makes sense.
And to avoid an infinite loop, we can have a condition to exit the while loop.

Related

Python + Open AI/GPT3 question: Why is part of my prompt spilling into the responses I receive?

This happens to probably 10% of responses I get. For whatever reason, the last bits of my prompt somehow spill into it, at the start of it. Like there will be a period, or a question mark, or sometimes a few of the last letters from the prompt, that get removed from the prompt, and somehow find their way into BOTH the response that gets printed inside of the Visual Studio Code terminal, AND in the outputted version that gets written to a corresponding Excel spreadsheet.
Any reason why this might happen?
Some example responses:
.
Most apples are colored red.
Also
?
Most rocks are colored gray.
Another example:
for it.
Most oceans are colored blue.
The period, the question mark, " for it" somehow get transposed FROM the end of the prompt, and tacked onto the response. And they even get removed from the prompt that was originally in the Excel spreadsheet to begin with.
Could this be a bug with xlsxwriter? open ai? Some combo of both?
Code here:
import xlsxwriter
import openpyxl
import os
import openai
filename = f'testing-openai-gpt3-requests-v1.xlsx'
wb = openpyxl.load_workbook(filename, read_only=False)
sheet = wb.active
# print("starting number of ideas is:")
# print(sheet.max_row)
for x in range(sheet.max_row):
c = sheet.cell(row = x+1, column = 1)
# print(c.value)
myCurrentText = c.value
myCurrentPrompt = "What is the color of most of the following objects: " + myCurrentBusinessIdea
openai.api_key = [none of your business]
response = openai.Completion.create(
model = "text-davinci-003",
prompt = myCurrentPrompt,
max_tokens = 1000,
)
TheOutputtedSummary = response['choices'][0]['text']
print(TheOutputtedSummary)
sheet.cell(row = x+1, column = 6).value = TheOutputtedSummary
wb.save(str(filename))
print('All finished!')
GPT-3 is a powerful language model capable of generating human-like text based on the input provided. However, it is important to ensure that the input text is clear and well-formatted in order to get the desired output.
One way to avoid issues with incomplete sentences is to ensure that your input text always ends with a full stop or other appropriate punctuation. This can help GPT-3 understand that the input text is complete, and prevent it from generating text that appears to be part of the input.
Here's how I solved the issue on a project I worked on. The project is a website featuring Amazon products, and it includes descriptions of the products based on reviews from purchasers.
It is important to be as clear as possible when generating a prompt for GPT-3, as this can help ensure that the model produces the desired output. Here's an example of a clear and well-formatted prompt:
"I will ask you a question and provide you with a list of objects.
Please tell me the colour of most of the following objects:
[dynamic text]
END OF THE LIST."

Creating a personal accounting program

I am new to python and may have been overly optimistic about the first project I want to tackle. I want to create a program that will help me allocate my checks(I have a banking app this is just for fun lol). I also want this to be a continuous program so it will check to see if there is a 'SavedData.txt' file and if there is it will present all the starting balances in 3 accounts from the last time it was used. Then continue to ask questions to allocate into said accounts from the new check. However, if the file doesn't exist I want it to create it, ask questions and then save the inputs to be called upon the next time it is run.
Here's what I have:
'If the file does not exist ask this prompt'
month = input("Please enter month: ")
day = input("Please enter the day: ")
year = input("Please enter the year: ")
initial_checking = int((input("What is your initial checking account balance?: ")))
initial_savings = int((input("What is your initial savings account balance?: ")))
initial_fun = int((input("What is your initial fun account balance?: ")))
current_check = int((input("What is your check amount?: ")))
save_cont = int(input("How much would you like to contribute to savings?: "))
fun_cont = int(input("How much would you like to contribute to fun account?: "))
current_check = int((current_check - save_cont) - fun_cont)
print("Remaining check balance is " + str(current_check) + ".")
def main():
while True:
q = input("Would you like to put the rest in checking?(Type Y/N): ")
if q in "yY":
global initial_checking
global initial_savings
global initial_fun
global current_check
initial_checking = int(initial_checking + current_check)
print("Your new checking balance is " + str(initial_checking))
return
elif q in "nN":
print("Error! You must contribute your entire check!")
else:
print("You must enter (y/n).")
return
main()
After this is where I start to have issues. If the file does exist, or if the program has been run before, I want it to read the last input and display "This is your current checking account balance: $" and so on and so forth. I then want the same contribution questions to be asked and added to the current balance amount for each respective account. Doing research I have seen when doing something like 'file1 = open("SavedData.txt", "a+") ' will open and append the file. My issue is figuring out how to set up running the check for the file, opening, reading it, adding to it, or creating it then writing, and saving it.
My apologies if there is redundant information or if it looks extremely sloppy as I said I am very very new and may have been overly optimistic about doing this project. I appreciate your time and responses.
As it is your first project I would suggest learning good design from the start. So try to plan out what you have to do first, what components will be needed and how will they interact (you can use sticky notes or whatever you like but have a plan before you start coding), as it will help you define classes/functions when you will be actually writing code.
So for now you nicely define the things you need to do, so do them one by one testing each step.
As of your question about file manipulation first start by writing function that opens a file and read it, as of now using with statement is good practice instead of manually opening and closing files, you can read more here and here.
Then try to write part of your code that defines what should be added to file (I'm not really sure how checks work so I can't help you here).
And when you know what you want to add create a function that will write to the file, it will be similar to reading so you can again refer to previously mentions links.
Finally if everything above is done you can try to enclose it in a loop that will constantly monitor the file. Probably the best approach would be to use already created library like watchdog but if you want to learn how filesystem works it is fine to create custom solution.
Last tip, try to avoid global variables ;P

Basics of connecting python to the web and validating user input

I'm relatively new, and I'm just at a loss as to where to start. I don't expect detailed step-by-step responses (though, of course, those are more than welcome), but any nudges in the right direction would be greatly appreciated.
I want to use the Gutenberg python library to select a text based on a user's input.
Right now I have the code:
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
text = strip_headers(load_etext(11)).strip()
where the number represents the text (in this case 11 = Alice in Wonderland).
Then I have a bunch of code about what to do with the text, but I don't think that's relevant here. (If it is let me know and I can add it).
Basically, instead of just selecting a text, I want to let the user do that. I want to ask the user for their choice of author, and if Project Gutenberg (PG) has pieces by that author, have them then select from the list of book titles (if PG doesn't have anything by that author, return some response along the lines of "sorry, don't have anything by $author_name, pick someone else." And then once the user has decided on a book, have the number corresponding to that book be entered into the code.
I just have no idea where to start in this process. I know how to handle user input, but I don't know how to take that input and search for something online using it.
Ideally, I'd be able to handle things like spelling mistakes too, but that may be down the line.
I really appreciate any help anyone has the time to give. Thanks!
The gutenberg module includes facilities for searching for a text by metadata, such as author. The example from the docs is:
from gutenberg.query import get_etexts
from gutenberg.query import get_metadata
print(get_metadata('title', 2701)) # prints frozenset([u'Moby Dick; Or, The Whale'])
print(get_metadata('author', 2701)) # prints frozenset([u'Melville, Hermann'])
print(get_etexts('title', 'Moby Dick; Or, The Whale')) # prints frozenset([2701, ...])
print(get_etexts('author', 'Melville, Hermann')) # prints frozenset([2701, ...])
It sounds as if you already know how to read a value from the user into a variable, and replacing the literal author in the above would be as simple as doing something like:
author_name = my_get_input_from_user_function()
texts = get_etexts('author', author_name)
Note the following note from the same section:
Before you use one of the gutenberg.query functions you must populate the local metadata cache. This one-off process will take quite a while to complete (18 hours on my machine) but once it is done, any subsequent calls to get_etexts or get_metadata will be very fast. If you fail to populate the cache, the calls will raise an exception.
With that in mind, I haven't tried the code I've presented in this answer because I'm still waiting for my local cache to populate.

Why is a part of my Python code interpreted diffently when I add a seemingly unrelated part?

Some background: I'm implementing a GUI to interact with equipment via GPIB. The issue arises in this method:
from tkinter import *
from tkinter import ttk
import visa #PyVisa Package. pyvisa.readthedocs.io
from time import sleep
import numpy as np #NumPy Package. Scipy.org
def oneDSweep():
Voltage =[]
Current =[]
Source = []
try:
#Gate = parseGate(Gate1Input.get()) #Not implemented yet.
Min = float(Gate1MinInput.get()) #Add a check for valid input
#if Min < .001:
#Throw exception
Max = float(Gate1MaxInput.get()) #Add a check for valid input
VoltageInterval = .02 #Prompt user for interval?
rm = visa.ResourceManager()
SIM900 = rm.open_resource("GPIB0::1::INSTR") #Add a check that session is open.
x = 0
Volt = Min
while Volt <= Max:
SIM900.write("SNDT 1, 'VOLT " + str(Volt) + "'") #Set voltage.
SIM900.write("SNDT 7, 'VOLT? 1'") #Ask a port for voltage.
Vnow = SIM900.query("GETN? 7, 50") #Retrieve data from previous port.
Vnow = Vnow[6:15]
Vnow = float(Vnow) ############Error location
Voltage = np.append(Voltage, Vnow)
SIM900.write("SNDT 1, 'VOLT?'") #Ask a different port for voltage.
Snow = SIM900.query("GETN? 1, 50") #Retrieve data.
print(Snow) #Debugging method. Probably not problematic.
Snow = Snow[4:]
Snow = float(Snow)
sleep(1) #Add a delay for science reasons.
#The code below helps the while loop act like a for loop.
x = x+1
Volt = Min + VoltageInterval*x
Volt = float(truncate(Volt, 7))
finally:
print(Voltage)
print(Source)
Voltage.tofile("output.txt.",sep=",")
SIM900.write("FLSH")#Flush the ports' memories to ensure no bad data stays there.
I get a simple ValueError at the marked location during the first pass of the while loop; Python says it cannot convert the string to a float(more on this later). However, simply remove these five lines of code:
SIM900.write("SNDT 1, 'VOLT?'")
Snow = SIM900.query("GETN? 1, 50")
print(Snow)
Snow = Snow[4:]
Snow = float(Snow)
and the program runs perfectly. I understand the source of the error. With those lines added, when I send these two lines to my instrument:
SIM900.write("SNDT 7, 'VOLT? 1'")
Vnow = SIM900.query("GETN? 7, 50")
I get essentially a null error. #3000 is returned, which is a blank message the machine sends when it is asked to output data and it has none to output. However, these same two lines produce something like #3006 00.003 when the four lines I mentioned are excluded from the program. In other words, simply adding those four lines to my program has changed the message sent to the instrument at the beginning of the while loop, despite adding them near the end.
I am convinced that Python's interpreter is at fault here. Earlier, I was cleaning up my code and discovered that one particular set of quotes, when changed from ' to ", produced this same error, despite no other quote pair exhibiting this behavior, even within the same line. My question is, why does the execution of my code change dependent upon unrelated alterations to the code(would also appreciate a fix)? I understand this problem is difficult to replicate given my somewhat specific application, so if there is more information that would be helpful that I can provide, please let me know.
EDIT: Functionality has improved after moving from the command prompt to IDLE. I'm still baffled by what happened, but due to my meager command prompt skills, I can't provide any proof. Please close this question.
Python is telling you exactly what is wrong with your code -- a ValueError. It even gives you the exact line number and the value that is causing the problem.
'#3006 00.003'
That is the value of SNOW that is being printed out. Then you do this
SNOW = SNOW[4:]
Now SNOW is
'6 00.003'
You then try to call float() on this string. 6 00.003 can't be converted to a float because it's a nonsensical number.
I am convinced that Python's interpreter is at fault here. Earlier, I was cleaning up my code and discovered that one particular set of quotes, when changed from ' to ", produced this same error, despite no other quote pair exhibiting this behavior, even within the same line.
Python generates exactly the same bytecode for single and double quoted strings (unless embedded quotes are involved, of course). So either the environment you're running your script in is seriously broken (I'm counting the python interpreter as part of the "environment"), or your diagnosis is incorrect. I'd put my money on the second.
Here's an alternative explanation. For whatever reason, the hardware you hooked up is returning inconsistent results. So one time you get what you expect, the next time you get an error-- you think your changes to the code account for the differences, but there's no relationship between cause and effect and you end up pulling your hair out. When you run the same code several times in a row, do you get consistent results? I.e. do you consistently get the odd behavior? Even if you do, the problem must be with the hardware or the hookup, not with Python.

Writing and Editing Files (Python)

First of all i would like to apologize since i am a beginner to Python. Anyway I have a Python Program where I can create text files with the general form:
Recipe Name:
Item
Weight
Number of people recipe serves
And what I'm trying to do is to allow the program to be able to retrieve the recipe and have the ingredients recalculated for a different number of people. The program should output the the recipe name, the new number of people and the revised quantities for the new number of people. I am able to retrieve the recipe and output the recipe however i am not sure how to have the ingredients recaculated for a different number of people. This is part of my code:
def modify_recipe():
Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
Exist_Recipe = open(Choice_Exist, "r+")
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like "))
I would recommend splitting your effort into multiple steps, and working on each step (doing research, trying to write the code, asking specific questions) in succession.
1) Look up python's file I/O. 1.a) Try to recreate the examples you find to make sure you understand what each piece of the code does. 1.b) Write your own script that accomplishes just this piece of your desired program, i.e. opens an exist recipe text file or creates a new one.
2) Really use you're own functions in Python particularly with passing your own arguments. What you're trying to make is a perfect example of good "modular programming", were you would right a function that reads an input file, another that writes an output file, another that prompts users for they number they'd like to multiple, and so on.
3) Add a try/except block for user input. If a user enters a non-numeric value, this will allow you to catch that and prompt the user again for a corrected value. Something like:
while True:
servings = raw_input('Please enter the number of servings desired: ')
try:
svgs = int(servings)
break
except ValueError:
print('Please check to make sure you entered a numeric value, with no'
+' letters or words, and a whole integer (no decimals or fractions).')
Or if you want to allow decimals, you could use float() instead of int().
4) [Semi-Advanced] Basic regular expressions (aka "regex") will be very helpful in building out what you're making. It sounds like your input files will have a strict, predictable format, so regex probably isn't necessary. But if you're looking to accept non-standard recipe input files, regex would be a great tool. While it can be a bit hard or confusing skill to learn, but there are a lot of good tutorials and guides. A few I bookmarked in the past are Python Course, Google Developers, and Dive Into Python. And a fantastic tool I strongly recommend while learning to build your own regular expression patterns is RegExr (or one of many similar, like PythonRegex), which show you what parts of your pattern are working or not working and why.
Here's an outline to help get you started:
def read_recipe_default(filename):
# open the file that contains the default ingredients
def parse_recipe(recipe):
# Use your regex to search for amounts here. Some useful basics include
# '\d' for numbers, and looking for keywords like 'cups', 'tbsp', etc.
def get_multiplier():
# prompt user for their multiplier here
def main():
# Call these methods as needed here. This will be the first part
# of your program that runs.
filename = ...
file_contents = read_recipe_file(filename)
# ...
# This last piece is what tells Python to start with the main() function above.
if __name__ == '__main__':
main()
Starting out can be tough, but it's very worth it in the end! Good luck!
I had to edit it a couple times because I use Python 2.7.5, but this should work:
import time
def modify_recipe():
Choice_Exist = input("\nOkay it looks like you want to modify a recipe. Please enter the name of this recipe: ")
with open(Choice_Exist + ".txt", "r+") as f:
content = f.readlines()
data_list = [word.replace("\n","") for word in content]
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like: "))
print data_list[0]
print data_list[1]
print int(data_list[2])*ServRequire #provided the Weight is in line 3 of txt file
print ServRequire
modify_recipe()

Categories