Step 类是一个 Python 上下文管理器,可用于在 chainlit 应用中创建步骤。当进入上下文管理器时会创建步骤,并在退出上下文管理器时将其更新到客户端。

参数

name
str

步骤的名称。默认为被装饰函数的名称。

type
Enum
默认值:"undefined"

步骤的类型,用于监控和调试。

elements
List[Element]

要附加到此步骤的元素。

language
str
show_input
Union[bool, str]
默认值:"False"

默认只显示步骤的输出。将此设置为 True 也会显示输入。您也可以将其设置为 jsonpython 等语言以进行语法高亮显示。

发送步骤

import chainlit as cl

@cl.on_message
async def main():
    async with cl.Step(name="Test") as step:
        # Step is sent as soon as the context manager is entered
        step.input = "hello"
        step.output = "world"

    # Step is updated when the context manager is exited

流式输出

from openai import AsyncOpenAI

import chainlit as cl

client = AsyncOpenAI()

@cl.on_message
async def main(msg: cl.Message):

    async with cl.Step(name="gpt4", type="llm") as step:
        step.input = msg.content

        stream = await client.chat.completions.create(
            messages=[{"role": "user", "content": msg.content}],
            stream=True,
            model="gpt-4",
            temperature=0,
        )

        async for part in stream:
            delta = part.choices[0].delta
            if delta.content:
                # Stream the output of the step
                await step.stream_token(delta.content)

嵌套步骤

要嵌套步骤,只需在另一个步骤中创建一个步骤即可。

import chainlit as cl


@cl.on_chat_start
async def main():
    async with cl.Step(name="Parent step") as parent_step:
        parent_step.input = "Parent step input"

        async with cl.Step(name="Child step") as child_step:
            child_step.input = "Child step input"
            child_step.output = "Child step output"

        parent_step.output = "Parent step output"

更新步骤

import chainlit as cl


@cl.on_chat_start
async def main():
    async with cl.Step(name="Parent step") as step:
        step.input = "Parent step input"
        step.output = "Parent step output"

    await cl.sleep(2)

    step.output = "Parent step output updated"
    await step.update()

移除步骤

import chainlit as cl


@cl.on_chat_start
async def main():
    async with cl.Step(name="Parent step") as step:
        step.input = "Parent step input"
        step.output = "Parent step output"

    await cl.sleep(2)

    await step.remove()