-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncio_step1.py
More file actions
51 lines (38 loc) · 1.3 KB
/
Copy pathasyncio_step1.py
File metadata and controls
51 lines (38 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import asyncio
from openai import OpenAI
api_key = os.getenv("DEEPSEEK_API_KEY")
if not api_key:
raise ValueError("没有找到 DEEPSEEK_API_KEY,请先在终端设置环境变量。")
client = OpenAI(
api_key=api_key,
base_url="https://api.deepseek.com",
)
def ask_deepseek_sync(question):
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "你是一个耐心的编程学习助手,请用简单中文回答。"},
{"role": "user", "content": question},
],
temperature=1.3,
)
return response.choices[0].message.content
async def ask_deepseek(question):
print(f"开始提问:{question}")
answer = await asyncio.to_thread(ask_deepseek_sync, question)
return question, answer
async def main():
questions = [
"什么是 asyncio?",
"pytest 有什么作用?",
"tenacity 是做什么的?",
]
tasks = [asyncio.create_task(ask_deepseek(question)) for question in questions]
print("\n按完成顺序输出:")
for completed_task in asyncio.as_completed(tasks):
question, answer = await completed_task
print(f"\n问题:{question}")
print("回答:")
print(answer)
asyncio.run(main())