You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
import asyncio
|
|
|
|
|
import json
|
|
|
|
|
import re
|
|
|
|
|
from CommonUtil import *
|
|
|
|
|
|
|
|
|
|
# 流式生成数据的函数
|
|
|
|
|
async def generate_stream_markdown(course_name: str):
|
|
|
|
|
"""
|
|
|
|
|
流式生成 Markdown 数据,并在控制台输出完整的 Markdown 内容
|
|
|
|
|
"""
|
|
|
|
|
# 调用阿里云 API,启用流式响应
|
|
|
|
|
stream = client.chat.completions.create(
|
|
|
|
|
model=MODEL_NAME,
|
|
|
|
|
messages=[
|
|
|
|
|
{'role': 'system', 'content': '你是一个教学经验丰富的基础教育教师'},
|
|
|
|
|
{'role': 'user',
|
|
|
|
|
'content': '帮我设计一下' + course_name + '的课件提纲,用markdown格式返回。强调1、标签只能返回 #,##,###,-,其它标签一率不可以返回,这个非常重要!2、不要返回 ```markdown 或者 ``` 这样的内容! 3、每部分都有生成完整的一、二、三级内容,不能省略。'}
|
|
|
|
|
],
|
|
|
|
|
stream=True, # 启用流式响应
|
|
|
|
|
timeout=6000,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# 初始化完整的 Markdown 内容
|
|
|
|
|
full_markdown = ""
|
|
|
|
|
|
|
|
|
|
# 逐字返回数据
|
|
|
|
|
for chunk in stream:
|
|
|
|
|
if chunk.choices[0].delta.content:
|
|
|
|
|
chunk_content = chunk.choices[0].delta.content
|
|
|
|
|
full_markdown += chunk_content # 拼接 Markdown 内容
|
|
|
|
|
for char in chunk_content:
|
|
|
|
|
yield char.encode("utf-8")
|
|
|
|
|
await asyncio.sleep(0.05) # 控制逐字输出的速度
|
|
|
|
|
|
|
|
|
|
# 在控制台输出完整的 Markdown 内容
|
|
|
|
|
print("\n完整的 Markdown 内容:")
|
|
|
|
|
print(full_markdown)
|
|
|
|
|
|
|
|
|
|
# 测试函数
|
|
|
|
|
async def test_generate_stream_markdown():
|
|
|
|
|
async for chunk in generate_stream_markdown("三角形面积"):
|
|
|
|
|
print(chunk.decode("utf-8"), end="", flush=True)
|
|
|
|
|
|
|
|
|
|
# 运行应用
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
# 使用 asyncio.run 运行异步函数
|
|
|
|
|
# asyncio.run(test_generate_stream_markdown())
|
|
|
|
|
|
|
|
|
|
# 读取Sample.md内容
|
|
|
|
|
with open("Sample.md", "r", encoding="utf-8") as file:
|
|
|
|
|
markdown_content = file.read()
|
|
|
|
|
|
|
|
|
|
print("markdown_content:", markdown_content)
|
|
|
|
|
|