https://github.com/exosever/chatbot/blob/main/twitchbot%205.0.py
の会話部分について
主な関数
query_gemini_with_memory(user_id, prompt)
この関数は、ユーザーの入力(prompt)に対して、過去の会話履歴(メモリ)や、感情分析、Wikipedia からの情報などを組み合わせたフルプロンプトを作成し、
model.start_chat(history=[]) を使って AI との対話セッションを開始し、その応答を取得します。
つまり、実際の会話の核心部分はこの関数で処理されています。
query_gemini_with_STT(user_id, prompt)
音声(STT)から変換されたテキスト入力の場合に呼ばれる実験的な関数で、基本的な流れは query_gemini_with_memory と似ていますが、音声からの入力処理が組み込まれています。
また、event_message(message) イベントハンドラー内で、メッセージが受信されるとこれらの関数が呼ばれて、実際に AI からの応答が得られ、チャットに送信されます。
例:query_gemini_with_memory の抜粋
async def query_gemini_with_memory(user_id, prompt):
global message_count
chat_session = model.start_chat(history=[])
full_prompt = (
"This is the user's current prompt:\n"
f"{prompt}\n\n"
)
if AI_MEMORY_FEATURE:
user_memory = await load_cached_memory(user_id)
previous_data = "\n".join(
['User prompt: ' + interaction['prompt'] +
" Generated Response:" + interaction['response']
for interaction in user_memory])
full_prompt += ("Here is some previous data from the user to keep in mind:\n"
f"{previous_data}\n\n")
if AI_EMOTION_DETECTION_FEATURE:
emotion_analysis = emotion_classifier(prompt)
detected_emotion = emotion_analysis[0]['label']
emotion_confidence = emotion_analysis[0]['score']
full_prompt += (f"Here is the current emotional state of the bot: \n{mood_instructions}\n\n")
if AI_MOODS_FEATURE:
if AI_EMOTION_DETECTION_FEATURE:
adjust_emotional_state_analysis(detected_emotion)
full_prompt += ("The user seems to be feeling "
f"{detected_emotion} with a confidence of {emotion_confidence:.2f}. \n"
"Please respond in a way that reflects this mood.\n\n")
if AI_WIKIPEDIA_FEATURE:
try:
if prompt.lower().startswith(f"@{BOT_TWITCH_NAME.lower()}"):
prompt = prompt[len(BOT_TWITCH_NAME) + 1:].strip()
elif prompt.lower().startswith(BOT_NICKNAME.lower()):
prompt = prompt[len(BOT_NICKNAME):].strip()
wiki_summary = await fetch_information(prompt)
if wiki_summary:
full_prompt += (
"Additionally, here is some related factual "
"information from Wikipedia to consider in your response:\n"
f"{wiki_summary}\n\n"
)
except Exception as e:
logging.error(f"Error in query processing: {e}")
return "Sorry, I'm having trouble with the AI service right now."
logging.info("Full prompt: " + full_prompt)
response = chat_session.send_message(full_prompt)
generated_text = response.text.strip()
if AI_LEARNING_FEATURE:
add_feedback_user_id(user_id)
if AI_MEMORY_FEATURE:
user_memory.append({'prompt': prompt, 'response': generated_text})
await save_cached_memory(user_id, user_memory)
message_count = 0
return generated_text
このように、query_gemini_with_memory が AI との会話の「根本部分」となっており、
ここで生成するプロンプトと、model.start_chat() からの応答が実際にユーザーへの返答として利用されています。