import requests
import json
class SimpleLLMChat:
def __init__(self, api_url, api_key, model_name="deepseek-reasoner"):
"""
初始化大模型聊天工具
:param api_url: 大模型API地址
:param api_key: 访问API的密钥
:param model_name: 模型名称
"""
self.api_url = api_url
self.api_key = api_key
self.model_name = model_name
self.chat_history = []
def add_to_history(self, role, content):
"""将消息添加到历史对话"""
self.chat_history.append({"role": role, "content": content})
def clear_history(self):
"""清空历史对话"""
self.chat_history = []
print("已清空对话历史")
def call_llm(self, user_message, max_tokens=1024, temperature=0.7):
"""
调用大模型API
:param user_message: 用户输入的消息
:param max_tokens: 生成的最大token数
:param temperature: 生成多样性参数,0-1之间
:return: 模型返回的响应
"""
self.add_to_history("user", user_message)
payload = {
"model": self.model_name,
"messages": self.chat_history,
"max_tokens": max_tokens,
"temperature": temperature,
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}",
}
try:
response = requests.post(
self.api_url, headers=headers, data=json.dumps(payload)
)
if response.status_code == 200:
result = response.json()
assistant_reply = result["choices"][0]["message"]["content"]
self.add_to_history("assistant", assistant_reply)
return assistant_reply
else:
error_msg = (
f"API请求失败: 状态码 {response.status_code}, 详情: {response.text}"
)
print(error_msg)
return error_msg
except Exception as e:
error_msg = f"调用API时发生错误: {str(e)}"
print(error_msg)
return error_msg
def main():
API_URL = "https://api.deepseek.com/chat/completions"
API_KEY = "your apiKey"
chat = SimpleLLMChat(API_URL, API_KEY)
print("欢迎使用简单大模型聊天工具!")
print("输入消息进行对话,输入 'clear' 清空历史,输入 'exit' 退出程序")
while True:
user_input = input("\n请输入: ")
if user_input.lower() == "exit":
print("再见!")
break
elif user_input.lower() == "clear":
chat.clear_history()
continue
print("思考中...")
reply = chat.call_llm(user_input)
print(f"AI: {reply}")
if __name__ == "__main__":
main()