This commit is contained in:
aaron 2025-04-29 22:52:16 +08:00
parent e8ff4b80f8
commit e2f5aef205
7 changed files with 85 additions and 28 deletions

View File

@ -56,10 +56,7 @@ class CryptoAgent:
test_mode=self.okx_config['test_mode']
)
self.deepseek_api = DeepSeekAPI(
api_key=self.deepseek_config['api_key'],
model=self.deepseek_config['model']
)
self.deepseek_api = DeepSeekAPI()
# 初始化数据处理器
self.data_processor = DataProcessor(storage_path=self.data_config['storage_path'])

View File

@ -52,10 +52,7 @@ class GoldAgent:
api_key=self.alltick_config['api_key']
)
self.deepseek_api = DeepSeekAPI(
api_key=self.deepseek_config['api_key'],
model=self.deepseek_config['model']
)
self.deepseek_api = DeepSeekAPI()
# 初始化数据处理器
self.data_processor = DataProcessor(storage_path=os.path.join(self.data_config['storage_path'], 'gold'))

View File

@ -6,6 +6,8 @@ import time
import logging
import datetime
from cryptoai.utils.config_loader import ConfigLoader
# 配置日志
logging.basicConfig(
level=logging.INFO,
@ -19,7 +21,7 @@ logging.basicConfig(
class DeepSeekAPI:
"""DeepSeek API交互类用于进行大语言模型调用"""
def __init__(self, api_key: str, model: str = "deepseek-moe-16b-chat"):
def __init__(self):
"""
初始化DeepSeek API
@ -27,12 +29,16 @@ class DeepSeekAPI:
api_key: DeepSeek API密钥
model: 使用的模型名称
"""
self.api_key = api_key
self.model = model
config_loader = ConfigLoader()
self.deepseek_config = config_loader.get_deepseek_config()
self.api_key = self.deepseek_config['api_key']
self.model = self.deepseek_config['model']
self.base_url = "https://api.deepseek.com/v1"
self.headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
"Authorization": f"Bearer {self.api_key}"
}
# Token 使用统计
@ -45,6 +51,58 @@ class DeepSeekAPI:
# 创建日志记录器
self.logger = logging.getLogger("DeepSeekAPI")
def streaming_call(self, user_prompt: str):
"""
流式调用DeepSeek API
"""
system_prompt = "你是一个专业的区块链分析高手"
try:
endpoint = f"{self.base_url}/chat/completions"
payload = {
"model": self.model,
"messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
"stream": True
}
response = requests.post(endpoint, headers=self.headers, json=payload, stream=True)
response.raise_for_status()
for line in response.iter_lines():
if line:
# 解码二进制数据为字符串
line = line.decode('utf-8')
# 跳过空行和心跳检查行
if not line or line == "data: [DONE]":
continue
# 移除 "data: " 前缀
if line.startswith("data: "):
line = line[6:]
try:
# 解析JSON数据
data = json.loads(line)
# 提取content内容
if (data.get("choices") and
len(data["choices"]) > 0 and
data["choices"][0].get("delta") and
data["choices"][0]["delta"].get("content")):
content = data["choices"][0]["delta"]["content"]
yield content
except json.JSONDecodeError as e:
self.logger.error(f"解析JSON时出错: {e}, 原始数据: {line}")
continue
except Exception as e:
self.logger.error(f"流式调用DeepSeek API时出错: {e}")
raise e
def call_model(self, prompt: str, system_prompt: str = None, task_type: str = "未知任务", symbol: str = "未知", temperature: float = 0.2, max_tokens: int = 2000) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""

View File

@ -14,6 +14,21 @@ import logging
from cryptoai.api.deepseek_api import DeepSeekAPI
from cryptoai.utils.config_loader import ConfigLoader
from fastapi.responses import StreamingResponse
# 创建路由
router = APIRouter(prefix="/api", tags=["加密AI接口"])
router = APIRouter()
class ChatRequest(BaseModel):
user_prompt: str
@router.post("/chat")
async def chat(request: ChatRequest):
"""
聊天接口
"""
deepseek_api = DeepSeekAPI()
response = deepseek_api.streaming_call(request.user_prompt)
return StreamingResponse(response, media_type="text/plain")

View File

@ -15,7 +15,7 @@ from fastapi.responses import JSONResponse
import time
from typing import Dict, Any
from cryptoai.routes.routes import router as api_router
from cryptoai.routes.agent import router as agent_router
# 配置日志
logging.basicConfig(
@ -45,7 +45,7 @@ app.add_middleware(
)
# 添加API路由
app.include_router(api_router)
app.include_router(agent_router, prefix="/agent")
# 请求计时中间件
@app.middleware("http")
@ -103,7 +103,7 @@ def start():
"cryptoai.routes.fastapi_app:app",
host=host,
port=port,
reload=False # 生产环境设为False
reload=True # 生产环境设为False
)
if __name__ == "__main__":

View File

@ -24,17 +24,7 @@ def get_deepseek_api() -> DeepSeekAPI:
"""
获取已配置的DeepSeekAPI实例
"""
config_loader = ConfigLoader()
deepseek_config = config_loader.get_deepseek_config()
if not deepseek_config or 'api_key' not in deepseek_config:
print("错误: 未找到DeepSeek API配置或API密钥")
sys.exit(1)
return DeepSeekAPI(
api_key=deepseek_config['api_key'],
model=deepseek_config.get('model', 'deepseek-moe-16b-chat')
)
return DeepSeekAPI()
def show_token_usage_stats():