python - 使用 langchain 和 websockets 完成流式聊天

标签 python django websocket django-channels langchain

我不确定我做错了什么,我正在使用长链完成并想将它们发布到我的 WebSocket 房间。使用 BaseCallbackHandler,我可以将 token 打印到控制台,但是,使用 AsyncCallbackHandler 是一个挑战,基本上,似乎什么也没有发生,我尝试打印东西,但是在 init 上打印消息之后,似乎什么也没有发生。

async def send_message_to_room(room_group_name, message):
    print("sending message to room", room_group_name, message)
    channel_layer = get_channel_layer()
    await channel_layer.group_send(
        room_group_name,
        {
            "type": "chat_message",
            "message": message,
        }
    )

class MyCustomHandler(AsyncCallbackHandler):

    def __init__(self, room_group_name):
        self.channel_layer = get_channel_layer()
        self.room_group_name = room_group_name

        print("MyCustomHandler init")

    async def on_llm_new_token(self, token: str, **kwargs):
        print(token)
        await send_message_to_room(self.room_group_name, token)

def generate_cited_answer_stream(roomname, question=question, texts=texts, responsetype="Simple and Pedagogical"
                                       , system_message_with_response_type=system_message_with_response_type
                                       , human_message_with_response_type=human_message_with_response_type):


    handler = MyCustomHandler(room_group_name=roomname)

    chat = ChatOpenAI(temperature=0, streaming=True, callbacks=[handler])

    system_message_with_response_type = SystemMessagePromptTemplate.from_template(system_message_with_response_type)
    human_message_prompt = HumanMessagePromptTemplate.from_template(human_message_with_response_type)

    chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

    prompt_value = chat_prompt.format_prompt(question=question, texts=texts, responsetype=responsetype)

    chat(prompt_value.to_messages())

最佳答案

截取有效的代码

from langchain.callbacks.streaming_aiter import AsyncIteratorCallbackHandler

class TestLangchainAsync(unittest.IsolatedAsyncioTestCase):
    async def test_aiter(self):
        handler = AsyncIteratorCallbackHandler()
        llm = OpenAI(
            temperature=0,
            streaming=True,
            callbacks=[handler],
            openai_api_key="sk-xxxxx",
            openai_proxy="http://127.0.0.1:7890",
        )
        prompt = PromptTemplate(
            input_variables=["product"],
            template="What is a good name for a company that makes {product}?",
        )
        prompt = prompt.format(product="colorful socks")
        asyncio.create_task(llm.agenerate([prompt]))
        async for i in handler.aiter():
            print(i)

引用

https://github.com/hwchase17/langchain/issues/2428#:~:text=AsyncIteratorCallbackHandler%20works.%20Here%20is%20the%20example%20code%3A

关于python - 使用 langchain 和 websockets 完成流式聊天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76369344/

相关文章:

C# HTML5 Websocket 服务器

python - 如何将 VectorAssembler 输出的特征映射回 Spark ML 中的列名?

python - azure-storage-python - 使用 create_blob_from_path 进行异常处理

django - Django session : sometimes session information is erased 的棘手问题

django - 如何修复异常类型 : UnicodeEncodeError

nginx - ElasticBeanstalk 上的 Websockets 给出 404

python - Python-调用函数和继续的主程序

python - 我将 python 社交身份验证与 django 结合使用。我无法断开与 Steam 的连接

django - 找出正在运行哪个端口的Django实例?

node.js - 使用socket.io 广播的效率与向每个客户端发送消息的效率相同