准备工作
环境介绍
- Miniconda,Python,IPython,VsCode
- 懒得介绍了
- 环境是VsCode中的Jupyter(ipynb),需提前安装ipykernel和openai这两个包
- 每轮输出的内容被保存至一个markdown文件中,可以下载Office Viewer(Markdown Editor)这个插件查看
from IPython.display import clear_output, Markdown, display
from openai import OpenAI
client = OpenAI()
system_content = "你是一个精通计算机科学的工程师。请注意:输出的LaTeX公式必须用美元符号($)包围,所有代码块必须使用Markdown语法高亮显示。"
messages = [
{"role": "system", "content": system_content},
]
while True:
user_content = input("'exit' to quit: ")
if user_content.lower() == "exit":
break
messages.append({"role": "user", "content": user_content})
messages_with_system = [{"role": "system", "content": system_content}] + messages
completion = client.chat.completions.create(
model="gpt-4o",
messages=messages_with_system,
stream=True,
)
response = ""
display_str = ""
for chunk in completion:
content = chunk.choices[0].delta.content
if content:
display_str += content
clear_output(wait=True)
display(Markdown(display_str))
with open("openai.md", "a", encoding="utf-8") as file:
file.write(display_str)
messages.append({"role": "assistant", "content": response})
环境介绍
- 30-50条的超长语句问答(gpt-4o),大概$0.7…