?对接效果
?
上对代码?,3个地方的体验还是有区别的。
import requests
import json
import os
os.environ["http_proxy"] = "http://127.0.0.1:1080"
os.environ["https_proxy"] = "http://127.0.0.1:1080"
def save_conversation(wxroomid, history):
""" 保存对话历史到 JSON 文件 """
with open(f"{wxroomid}.json", "w") as file:
json.dump(history, file)
def load_conversation(wxroomid):
""" 从 JSON 文件加载对话历史 """
if os.path.exists(f"{wxroomid}.json"):
with open(f"{wxroomid}.json", "r") as file:
return json.load(file)
return []
def extract_response(response_data):
""" 从 Gemini API 的响应中提取机器人的回复 """
if 'candidates' in response_data and response_data['candidates']:
contents = response_data['candidates'][0].get('content', {}).get('parts', [])
return " ".join(part.get('text', '') for part in contents)
return ""
def send_to_gemini(wxroomid, user_input):
""" 发送请求到 Gemini API 并处理响应 """
url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=AI**********"
# 加载历史对话
history = load_conversation(wxroomid)
# 添加用户输入到历史记录
history.append({"role": "user", "parts": [{"text": user_input}]})
# 准备请求数据
payload = json.dumps({"contents": history})
headers = {'Content-Type': 'application/json'}
# 发送请求并获取响应
response = requests.post(url, headers=headers, data=payload)
response_data = response.json()
# 提取回复并更新历史记录
gemini_response = extract_response(response_data)
if gemini_response:
# 添加模型回答到历史记录
history.append({"role": "model", "parts": [{"text": gemini_response}]})
save_conversation(wxroomid, history)
return gemini_response
# 使用示例
wxroomid = "pengsanyuan"
user_input = "董宇辉的小作文"
response = send_to_gemini(wxroomid, user_input)
print(response)
申请api key?https://makersuite.google.com/app/prompts/new_freeform