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
        }))
相关推荐
小白学大数据3 小时前
Python爬虫开发中的分析与方案制定
开发语言·c++·爬虫·python
Shy9604184 小时前
Doc2Vec句子向量
python·语言模型
秀儿还能再秀7 小时前
机器学习——简单线性回归、逻辑回归
笔记·python·学习·机器学习
阿_旭8 小时前
如何使用OpenCV和Python进行相机校准
python·opencv·相机校准·畸变校准
幸运的星竹8 小时前
使用pytest+openpyxl做接口自动化遇到的问题
python·自动化·pytest
清尘沐歌8 小时前
有什么好用的 WebSocket 测试工具吗?
websocket·网络协议·测试工具
清尘沐歌8 小时前
有什么好用的 WebSocket 调试工具吗?
网络·websocket·网络协议
Tttian6229 小时前
Vue全栈开发旅游网项目(11)-用户管理前端接口联调
前端·vue.js·django
kali-Myon9 小时前
ctfshow-web入门-SSTI(web361-web368)上
前端·python·学习·安全·web安全·web