如何保存双子座模特的每条聊天记录

问题描述 投票:0回答:1

简要说明: 我想要的是用户创建多个聊天,并且还能够继续之前的对话。 在下面的代码中继续

chat1
中的
chat3
我需要一个历史记录,如何存储该历史记录,以便我可以在需要时使用它?

import os
import google.generativeai as genai

GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')

genai.configure(api_key=GOOGLE_API_KEY)
model = genai.GenerativeModel('gemini-pro')

chat1 = model.start_chat(history=[])
response = chat1.send_message("Which is asia's largest country?")
response1 = chat1.send_message("What about it's capital?")
response2 = chat1.send_message("What about it's population?")
for message in chat1.history:
    print(f'**{message.role}**: {message.parts[0].text}')

print("*"*50)

chat2 = model.start_chat(history=[])
response = chat2.send_message("Which is india's capital?")
response1 = chat2.send_message("What about it's population?")
for message in chat2.history:
    print(f'**{message.role}**: {message.parts[0].text}')

print("*"*50)

chat3 = model.start_chat(history=chat1.history)
response = chat3.send_message("what's the name of it's currency?")
for message in chat3.history:
    print(f'**{message.role}**: {message.parts[0].text}')

我想要如何存储聊天记录。

注意:我使用django作为框架,mysql作为数据库

python database chat chatbot google-gemini
1个回答
0
投票

我没有有关您的应用程序的详细信息,但也许您不需要多次聊天,而是需要多个历史记录。我遇到了类似的问题,我为解决这个问题所做的就是存储每个用户的历史记录并将其传递给每个调用,f.e:

genai.configure(api_key = gkey)
model = genai.GenerativeModel('gemini-pro', generation_config=generation_config)
history_clients = {}

def start_chat(context, user):
  if user not in history_clients:
    history_clients[user] = []
  
  answer, error = None, None
  try:
    chat = model.start_chat(history=history_clients[user])
    chat.send_message(context)
    history_clients[user] += chat.history

    answers = [message.parts[0].text for message in chat.history if message.role == "model"]
    answer = answers [-1]
  
  except Exception as e:
    error = f'error: {e}'
  
  return answer, error 

就我而言,只想从我的聊天记录中得到最后的答案

因此您可以通过

访问
answer, error = start_chat(message.content, message.author.id)
if erro:
   print(erro)
else:
   print(resposta)
© www.soinside.com 2019 - 2024. All rights reserved.