python openai 流式数据返回

技术 · 09-05 · 访问: 163 次
from openai import OpenAI


def client_chat():
    client = OpenAI(api_key=os.getenv("API_KEY"), base_url="https://xx.xx.xx")
    
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "You are a helpful assistant"},
            {"role": "user", "content": "Hello"},
        ],
        stream=True
    )

    # 用于保存并逐步构建消息内容
    message_content = ''

    for chunk in response:
        message_content += chunk.choices[0].delta.content
        print(chunk.choices[0].delta.content)

        # 打印完整的消息内容(如果需要)
    print("\n完整消息内容:\n", message_content)


client_chat()
python openai
icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif
Theme Jasmine by Kent Liao