import requests import json def get_response(messages, api_key, base_url): """原有非流式调用(保留兼容)""" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } data = { "model": "deepseek-chat", "messages": messages, "temperature": 0.7, "max_tokens": 2048 } try: response = requests.post(base_url, headers=headers, json=data, timeout=30) response.raise_for_status() result = response.json() return result["choices"][0]["message"]["content"] except requests.exceptions.HTTPError as e: return f"API请求失败(HTTP错误):{str(e)},请检查API密钥是否正确" except requests.exceptions.ConnectionError: return "网络连接失败,请检查网络或API地址是否正确" except Exception as e: return f"请求异常:{str(e)}" def get_response_stream(messages, api_key, base_url): """流式调用DeepSeek API""" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } data = { "model": "deepseek-chat", "messages": messages, "temperature": 0.7, "max_tokens": 2048, "stream": True # 开启流式输出 } try: response = requests.post( base_url, headers=headers, json=data, timeout=30, stream=True ) response.raise_for_status() for line in response.iter_lines(): if line: line = line.decode("utf-8").strip() if line.startswith("data: "): line = line[6:] if line == "[DONE]": break try: chunk = json.loads(line) if "choices" in chunk and len(chunk["choices"]) > 0: content = chunk["choices"][0]["delta"].get("content", "") if content: yield content except json.JSONDecodeError: continue except requests.exceptions.HTTPError as e: yield f"API请求失败(HTTP错误):{str(e)},请检查API密钥是否正确" except requests.exceptions.ConnectionError: yield "网络连接失败,请检查网络或API地址是否正确" except Exception as e: yield f"请求异常:{str(e)}"