Maintaining Conversation Dialogue with OpenAI Python API

When trying to use Chat Completions through the OpenAI API, I run into difficulties with the model maintaining a memory of this conversation. I use a Python script to run a series of questions about a series of deals. I want to initialize the conversation for each new deal, but I want to make sure that the same conversation is maintained for all questions referencing the same deal.

Currently, I receive output like this when referencing an acquisition deal that the API already responded to:

As an AI, I don’t have the ability to recall previous interactions. However, …

  1. Company A:…”

I apologize for this, I am new to Python. I was under the impression that I could use previous_context and/or conversation_context to maintain this type of conversation.

`def ask_gpt(prompt, client, previous_context=””, max_retries=3, retry_delay=5, initialize=False):
retries = 0

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>while retries < max_retries:
messages = []
if initialize:
messages.append({
"role": "system",
"content": ()
})
# Include previous context
if previous_context:
messages.append({
"role": "user",
"content": previous_context
})
# Add the main user query
messages.append({
"role": "user",
"content": prompt
})
print(messages) # Print messages for diagnosis
try:
response = client.chat.completions.create(
model="gpt-4-0613",
messages=messages,
max_tokens=3200,
n=1,
stop=None,
top_p=0.0,
temperature=0.0,
frequency_penalty=1,
presence_penalty=1
)
answer = response.choices[0].message.content # Corrected path
return answer
# Handle any exception that may occur
except openai.RateLimitError as e:
print("Rate limit exceeded. Please try again later.")
print(e) # Print the error for diagnosis
time.sleep(retry_delay) # Sleep before retrying
retry_delay *= 2 # Exponential backoff
retries += 1
except Exception as e:
print(f"An unexpected error occurred: {e}")
retries += 1
if retries >= max_retries:
raise
time.sleep(retry_delay)
retry_delay *= 2 # double the delay for the next retry
</code>
<code>while retries < max_retries: messages = [] if initialize: messages.append({ "role": "system", "content": () }) # Include previous context if previous_context: messages.append({ "role": "user", "content": previous_context }) # Add the main user query messages.append({ "role": "user", "content": prompt }) print(messages) # Print messages for diagnosis try: response = client.chat.completions.create( model="gpt-4-0613", messages=messages, max_tokens=3200, n=1, stop=None, top_p=0.0, temperature=0.0, frequency_penalty=1, presence_penalty=1 ) answer = response.choices[0].message.content # Corrected path return answer # Handle any exception that may occur except openai.RateLimitError as e: print("Rate limit exceeded. Please try again later.") print(e) # Print the error for diagnosis time.sleep(retry_delay) # Sleep before retrying retry_delay *= 2 # Exponential backoff retries += 1 except Exception as e: print(f"An unexpected error occurred: {e}") retries += 1 if retries >= max_retries: raise time.sleep(retry_delay) retry_delay *= 2 # double the delay for the next retry </code>
while retries < max_retries:
    messages = []

    if initialize:
        messages.append({
            "role": "system",
            "content": ()
        })

    # Include previous context
    if previous_context:
        messages.append({
            "role": "user",
            "content": previous_context
        })

    # Add the main user query
    messages.append({
        "role": "user",
        "content": prompt
    })

    print(messages)  # Print messages for diagnosis

    try:
        response = client.chat.completions.create(
            model="gpt-4-0613",
            messages=messages,
            max_tokens=3200,
            n=1,
            stop=None,
            top_p=0.0,
            temperature=0.0,
            frequency_penalty=1,
            presence_penalty=1
        )
        answer = response.choices[0].message.content  # Corrected path
        return answer

    # Handle any exception that may occur
    except openai.RateLimitError as e:
        print("Rate limit exceeded. Please try again later.")
        print(e)  # Print the error for diagnosis
        time.sleep(retry_delay)  # Sleep before retrying
        retry_delay *= 2  # Exponential backoff
        retries += 1

    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        retries += 1
        if retries >= max_retries:
            raise
        time.sleep(retry_delay)
        retry_delay *= 2  # double the delay for the next retry

def generate_questions(df, word_file):
doc = Document(word_file)
prompts = [p.text for p in doc.paragraphs if p.text.startswith(“Prompt”)]

def process_xlsx(input_file, output_file, word_file, client):
df = pd.read_excel(input_file, sheet_name=’FullSample’, engine=’openpyxl’)
generate_questions(df, word_file)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>prompt_cols = [col for col in df.columns if col.startswith("Prompt")]
# Iterate over each row in the DataFrame
for idx, row in tqdm(df.iterrows(), total=len(df)):
# Reset context at the beginning of each row/new deal
conversation_context = ""
initialize = True
# Iterate over each prompt column for the current row
for col in prompt_cols:
prompt = row[col]
# Fetch the response from the GPT model with acquirer and target lists as needed
response = ask_gpt(prompt, client, initialize=initialize)
conversation_context += f"Q: {prompt}nA: {response}n"
# Store the response in the DataFrame
df.at[idx, f'Response_for_{col}'] = response
# Reset initialize only once per row
initialize = False
time.sleep(1) # Throttle requests
df.drop(columns=prompt_cols, inplace=True)
df.to_excel(output_file, index=False, engine='openpyxl')`
</code>
<code>prompt_cols = [col for col in df.columns if col.startswith("Prompt")] # Iterate over each row in the DataFrame for idx, row in tqdm(df.iterrows(), total=len(df)): # Reset context at the beginning of each row/new deal conversation_context = "" initialize = True # Iterate over each prompt column for the current row for col in prompt_cols: prompt = row[col] # Fetch the response from the GPT model with acquirer and target lists as needed response = ask_gpt(prompt, client, initialize=initialize) conversation_context += f"Q: {prompt}nA: {response}n" # Store the response in the DataFrame df.at[idx, f'Response_for_{col}'] = response # Reset initialize only once per row initialize = False time.sleep(1) # Throttle requests df.drop(columns=prompt_cols, inplace=True) df.to_excel(output_file, index=False, engine='openpyxl')` </code>
prompt_cols = [col for col in df.columns if col.startswith("Prompt")]

# Iterate over each row in the DataFrame
for idx, row in tqdm(df.iterrows(), total=len(df)):
    # Reset context at the beginning of each row/new deal
    conversation_context = ""
    initialize = True

    # Iterate over each prompt column for the current row
    for col in prompt_cols:
        prompt = row[col]

        # Fetch the response from the GPT model with acquirer and target lists as needed
        response = ask_gpt(prompt, client, initialize=initialize)

        conversation_context += f"Q: {prompt}nA: {response}n"

        # Store the response in the DataFrame
        df.at[idx, f'Response_for_{col}'] = response

        # Reset initialize only once per row
        initialize = False

    time.sleep(1)  # Throttle requests

df.drop(columns=prompt_cols, inplace=True)
df.to_excel(output_file, index=False, engine='openpyxl')`

New contributor

Adam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật