ChatGPT流式传输(stream=True)的实现-OpenAI API 流式传输

这篇具有很好参考价值的文章主要介绍了ChatGPT流式传输(stream=True)的实现-OpenAI API 流式传输。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


一、介绍:

默认情况下,当请求OpenAI的API时,整个响应将在生成后一次性发送回来。如果需要的响应比较复杂,就会需要很长时间来等待响应。

为了更快地获得响应,可以在请求API时选择“流式传输”。

要使用流式传输,调用API时设置stream=True。这将返回一个对象,以data-only server-sent events流式返回响应。需要从delta字段而不是message字段中提取块。

二、不足之处:

  1. 由于是逐步传输的,所以使用流式传输会提高对内容审核的难度。
  2. 流式响应的另一个小缺点是,响应不再包括“usage”字段,所以无法立即得知使用了多少令牌。

三、示例代码:

0. 引入库:

import openai  # for OpenAI API calls
import time  # for measuring time duration of API calls

1. 不使用stream的后台代码(官方示例):

在不使用stream的ChatCompletions API调用中,响应被计算出来后一次性地返回。

# Example of an OpenAI ChatCompletion request
# https://platform.openai.com/docs/guides/chat

# record the time before the request is sent
start_time = time.time()

# send a ChatCompletion request to count to 100
response = openai.ChatCompletion.create(
    model='gpt-3.5-turbo',
    messages=[
        {'role': 'user', 'content': 'Count to 100, with a comma between each number and no newlines. E.g., 1, 2, 3, ...'}
    ],
    temperature=0,
)

# calculate the time it took to receive the response
response_time = time.time() - start_time

# print the time delay and text received
print(f"Full response received {response_time:.2f} seconds after request")
print(f"Full response received:\n{response}")

reply = response['choices'][0]['message']
print(f"Extracted reply: \n{reply}")

reply_content = response['choices'][0]['message']['content']
print(f"Extracted content: \n{reply_content}")

2. 使用stream的后台代码(官方示例):

在流式 API 调用中,响应通过事件流以分块的方式递增送回。在Python中,可以用一个for循环来迭代这些事件。

# Example of an OpenAI ChatCompletion request with stream=True
# https://platform.openai.com/docs/guides/chat

# record the time before the request is sent
start_time = time.time()

# send a ChatCompletion request to count to 100
response = openai.ChatCompletion.create(
    model='gpt-3.5-turbo',
    messages=[
        {'role': 'user', 'content': 'Count to 100, with a comma between each number and no newlines. E.g., 1, 2, 3, ...'}
    ],
    temperature=0,
    stream=True  # again, we set stream=True
)

# create variables to collect the stream of chunks
collected_chunks = []
collected_messages = []
# iterate through the stream of events
for chunk in response:
    chunk_time = time.time() - start_time  # calculate the time delay of the chunk
    collected_chunks.append(chunk)  # save the event response
    chunk_message = chunk['choices'][0]['delta']  # extract the message
    collected_messages.append(chunk_message)  # save the message
    print(f"Message received {chunk_time:.2f} seconds after request: {chunk_message}")  # print the delay and text

# print the time delay and text received
print(f"Full response received {chunk_time:.2f} seconds after request")
full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
print(f"Full conversation received: {full_reply_content}")

3. 实际生产环境的示例后台代码(Sanic):

	api_response = openai.ChatCompletion.create(
	        model='gpt-3.5-turbo',
	        messages=request.ctx.session['message'],
	        temperature=1,
	        stream=True
	)

    response = await request.respond(content_type='text/event-stream')
    answer = ''
    for part in api_response:
        finish_reason = part["choices"][0]["finish_reason"]
        if "content" in part["choices"][0]["delta"]:
            content = part["choices"][0]["delta"]["content"]
            answer += content
            content = content.replace('\n', '<br>')  # 将换行替换为<br>,用于前端显示。
            await response.send(f"data: {content}\n\n")  # 使用 Server-Sent Events (SSE) 格式发送数据
        elif finish_reason:
            await response.send(f"event: end\ndata: {answer}\n\n")

4. 实际生产环境的示例前端代码(SSE):

const source = new EventSource("/api/chat_stream/?message=" + message);
const messageDiv = document.createElement('div');
let res_msg = ''
chatContainer.appendChild(messageDiv);
source.addEventListener('message', (e) => {
    messageDiv.innerHTML += e.data;
    chatContainer.scrollTop = chatContainer.scrollHeight;
    res_msg += e.data;
})
// 收到所有的回复后,重新整理格式,这里用的是marked.js,也可以用mark-it。
source.addEventListener('end', (e) => {
    source.close()
    res_msg = res_msg.replaceAll('<br>', '\r\n')
    messageDiv.innerHTML = marked.parse(res_msg)
    chatContainer.scrollTop = chatContainer.scrollHeight;
})
source.onerror = function (e) {
    console.log(e)
}

四、总结:

本文介绍了OpenAI API中流式传输(stream=True)的实现方法,以及如何使用该功能来处理大型文本数据。

此外,还列出了使用流式传输的优缺点,以及示例代码,包括不使用流式传输的代码和使用流式传输的代码。其中使用流式传输的代码示例演示了如何通过事件流以分块的方式递增接收响应,并在 Python 中使用 for 循环迭代这些事件,最终获得完整的响应。同时,本文还提供了实际生产环境的示例代码,包括后台代码和前端代码。文章来源地址https://www.toymoban.com/news/detail-472337.html

到了这里,关于ChatGPT流式传输(stream=True)的实现-OpenAI API 流式传输的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java 8:Stream API 流式操作

    💗wei_shuo的个人主页 💫wei_shuo的学习社区 🌐Hello World ! Java 8 中的 Stream API 是一组用于对集合数据进行处理的新特性;提供一种以声明式风格对集合进行操作的方式,简化集合的处理,使得代码更加简洁、优雅,并且能够更高效地处理数据; 这种风格将要处理的元素集合看

    2024年02月13日
    浏览(32)
  • Java 8:Stream API 流式操作(学习)

    Java 8 中的 Stream API 是一组用于对集合数据进行处理的新特性;提供一种以声明式风格对集合进行操作的方式,简化集合的处理,使得代码更加简洁、优雅,并且能够更高效地处理数据; 这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进

    2024年02月10日
    浏览(34)
  • 使用OkHttp流式请求OpenAI API(GPT API)接口

    因为 GPT 流式请求的出色交互体验,我们打算做一个开源基础应用,方便开发者快速集成项目。 本应用集成 ChatGPT API,使用模型为 gpt-3.5-turbo,项目代码为 Kotlin 语言开发的安卓应用。 人机交互的趋势已经到来,本应用框架也希望能帮助更多开发者快速集成 ChatGPT 体验到人机

    2024年02月11日
    浏览(30)
  • ASP.NET Core Web API 流式返回,实现ChatGPT逐字显示

    🏆作者:科技、互联网行业优质创作者 🏆专注领域:.Net技术、软件架构、人工智能、数字化转型、DeveloperSharp、微服务、工业互联网、智能制造 🏆欢迎关注我(Net数字智慧化基地),里面有很多 高价值 技术文章, 是你刻苦努力也积累不到的经验 ,能助你快速成长。升职

    2024年02月22日
    浏览(43)
  • Java调用ChatGPT(基于SpringBoot),实现可连续对话和流式输出的ChatGPT API(可自定义实现AI助手)

    源码及更详细的介绍说明参见Git上的 README.md 文档 https://github.com/asleepyfish/chatgpt 本文Demo(SpringBoot和Main方法Demo均包括)的Git地址:https://github.com/asleepyfish/chatgpt-demo 流式输出结合Vue前端的Demo的Git地址:https://github.com/asleepyfish/chatgpt-vue 后续使用方法和api版本更新均在Github的READM

    2023年04月13日
    浏览(37)
  • openAI 通过php方式 发送请求,流数据形式传输,php 实现chatGPT功能

    此处使用的框架是 symfony ,可自行根据自己框架开发,大同小异,框架无所谓,主要是功能! 先上代码 :

    2024年01月19日
    浏览(37)
  • Java调用ChatGPT(基于SpringBoot和Vue),实现可连续对话和流式输出的ChatGPT API(可自定义实现AI助手)

    源码及更详细的介绍说明参见Git上的 README.md 文档 https://github.com/asleepyfish/chatgpt 本文Demo(SpringBoot和Main方法Demo均包括)的Git地址:https://github.com/asleepyfish/chatgpt-demo 流式输出结合Vue前端的Demo的Git地址:https://github.com/asleepyfish/chatgpt-vue 后续使用方法和api版本更新均在Github的READM

    2023年04月24日
    浏览(38)
  • 【课件】Python调用OpenAI API实现ChatGPT多轮对话

    如何实现多轮对话? gpt-3.5-turbo 模型调用方法 openai.ChatCompletion.create 里传入的 message 是一个列表,列表里每个元素是字典,包含了角色和内容,我们只需将每轮对话都存储起来,然后每次提问都带上之前的问题和回答即可。 代码解析: ChatGPT 类,包含三个函数: __init__ 初始

    2024年02月03日
    浏览(37)
  • Server-Sent Events(SSE) 入门、原理、介绍、类ChatGpt流式输出实现

    一、引言 在现代Web应用程序中,实时数据传输和实时通信变得越来越重要。为了实现这种实时通信,多种技术应运而生,如WebSocket、长轮询和Server-Sent Events(SSE)。在本文中,我们将重点探讨Server-Sent Events,一种基于HTTP的实时通信协议。 二、技术背景 Server-Sent Events(SSE)它

    2024年02月08日
    浏览(37)
  • 17行代码用python对接openai的api实现chatgpt微信对话机器人

    itchat python依赖下载 这里推荐这个。链接:衡天云

    2024年02月01日
    浏览(46)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包