Django openai websocket live chat

This code works on openai==0.28

python 复制代码
## consumers.py
## consumers.py
import json
import os

from channels.generic.websocket import AsyncWebsocketConsumer
import openai
import asyncio
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AutoServer.settings')
openai.api_key = settings.OPENAI_API_KEY


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        data = json.loads(text_data)
        prompt = data['prompt']

        loop = asyncio.get_event_loop()
        await loop.run_in_executor(None, self.stream_openai_response, prompt)

    def stream_openai_response(self, prompt):
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}],
            stream=True,
        )
        for chunk in response:
            if chunk.choices[0].delta.get('content'):
                asyncio.run(self.send_streaming_data(chunk.choices[0].delta['content']))
                ## return to the webpage as stream

    async def send_streaming_data(self, content):
        await self.send(text_data=json.dumps({
            'response': content
        }))

This works on newest version, 1.31

python 复制代码
import json
import openai
import asyncio
from channels.generic.websocket import AsyncWebsocketConsumer
from django.conf import settings
import os
from openai import OpenAI

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AutoServer.settings')
api_key = settings.OPENAI_API_KEY
client = OpenAI(api_key=api_key)
class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        data = json.loads(text_data)
        prompt = data['prompt']
        # key part, the loop
        loop = asyncio.get_event_loop()
        await loop.run_in_executor(None, self.stream_openai_response, prompt)

    def stream_openai_response(self, prompt):
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt},
            ],
            stream=True,
        )
        for chunk in response:
            if chunk.choices[0].delta.content:
                asyncio.run(self.send_streaming_data(chunk.choices[0].delta.content))

    async def send_streaming_data(self, content):
        await self.send(text_data=json.dumps({
            'response': content
        }))
相关推荐
龙腾AI白云1 小时前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
艾派森1 小时前
深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型
人工智能·python·深度学习·分类
鲸渔1 小时前
【AI Agent系列课程26-Python 基础26】复盘:Python 接口开发知识清单
开发语言·python·ai编程
2401_868534782 小时前
55 个热门网络面试问题及答案
网络·python
aifannihao2 小时前
ON CONFLICT 冲突后返回空:sqlite3 实测 get-or-create
数据库·python·postgresql·sqlite3·标准库
用户0332126663672 小时前
使用 Python 合并 Excel 工作簿
python
__underline__2 小时前
冷门Python知识点008篇:__int__、__index__与__float__,Python数值转换的真实回退顺序?
后端·python
FriendshipT3 小时前
YOLOE Docker 部署实战:三模式推理、掩码输出与跨图视觉的完整实现
运维·人工智能·python·深度学习·docker·容器
tryCbest3 小时前
Python 爬虫扩展篇(一):APP 抓包与 JS 逆向入门——从看见流量到读懂签名
javascript·爬虫·python
月光船幽幽3 小时前
基线漂移破解:微服务测试一致性方案
python·科技·微服务