Skip to content

Instantly share code, notes, and snippets.

@cosven
Created June 4, 2024 12:52
Show Gist options
  • Save cosven/b6922a8e1aaf0f23de93f7e2bc754d0d to your computer and use it in GitHub Desktop.
Save cosven/b6922a8e1aaf0f23de93f7e2bc754d0d to your computer and use it in GitHub Desktop.
给 FeelUOwn 集成 AI 功能
def ask_ai_background(ctx):
global app
from openai import OpenAI, AsyncOpenAI
from functools import partial
from feeluown.utils.aio import run_fn, run_afn
from feeluown.library import ModelType
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox
models = ctx['models']
add_action = ctx['add_action']
song = models[0]
openai_kwargs = dict(
base_url='https://api.deepseek.com/v1',
api_key=os.getenv('DEEPSEEK_API_KEY', '')
)
model = 'deepseek-chat'
openai_kwargs = dict(
base_url='https://api.moonshot.cn/v1',
api_key=os.getenv('MOONSHOT_API_KEY', '')
)
model = 'moonshot-v1-8k'
async def task():
app.show_msg("正在向 AI 提问,这可能需要几秒钟...", timeout=3000)
message = f'你描述一下 “{song.title}-{song.artists_name} ” 这首歌的创作背景'
if True or api_key:
client = AsyncOpenAI(**openai_kwargs)
system_msg = {
"role": "system",
"content": (
"你擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。"
"同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。"
)
}
user_msg = {
"role": "user",
"content": message
}
stream = await client.chat.completions.create(
model=model,
messages=[system_msg, user_msg],
temperature = 0.3,
stream=True,
)
box = QMessageBox(parent=app)
box.setAttribute(Qt.WA_DeleteOnClose);
box.setText('')
box.open()
content = ''
async for chunk in stream:
content += chunk.choices[0].delta.content or ''
box.setText(content)
def callback(models):
run_afn(task)
add_action('AI:歌曲创作背景', callback)
when('app.ui.songs_table.about_to_show_menu', ask_ai_background, use_symbol=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment