Files
worklist/backend/ai_service.py
2025-12-30 09:03:29 +00:00

60 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import openai
import os
from dotenv import load_dotenv
load_dotenv()
class AIService:
def __init__(self):
# 设置OpenAI API密钥
self.api_key = os.getenv('OPENAI_API_KEY')
# 延迟初始化客户端避免在没有API密钥时出错
self.client = None
def polish_description(self, description):
"""
使用AI润色任务描述
"""
if not description or not description.strip():
return description
# 检查API密钥
if not self.api_key or self.api_key == 'your_openai_api_key_here':
print("AI润色功能需要配置OpenAI API密钥")
return description
try:
# 使用旧版本OpenAI API
openai.api_key = self.api_key
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": "你是一个专业的工作任务描述润色助手。请将用户提供的工作任务描述润色得更加专业、清晰、具体。保持原意不变,但让描述更加规范和易于理解。"
},
{
"role": "user",
"content": f"请润色以下工作任务描述:\n\n{description}"
}
],
max_tokens=500,
temperature=0.7
)
polished = response.choices[0].message.content.strip()
return polished
except Exception as e:
print(f"AI润色失败: {e}")
# 如果AI服务失败返回原始描述
return description
def is_available(self):
"""检查AI服务是否可用"""
return bool(self.api_key and self.api_key != 'your_openai_api_key_here')
# 创建全局AI服务实例
ai_service = AIService()