步骤装饰器会根据被装饰的函数记录步骤。默认情况下,函数的参数将用作步骤的输入,返回值将用作输出。

在底层,步骤装饰器使用了 cl.Step 类。

参数

name
str

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

type
str
默认值:"undefined"

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

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

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

访问当前步骤

您可以使用 cl.context.current_step 访问当前步骤对象并覆盖值。

import chainlit as cl

@cl.step
async def my_step():
    current_step = cl.context.current_step

    # Override the input of the step
    current_step.input = "My custom input"

    # Override the output of the step
    current_step.output = "My custom output"

流式输出

from openai import AsyncOpenAI

import chainlit as cl

client = AsyncOpenAI(api_key="YOUR_API_KEY")

@cl.step(type="llm")
async def gpt4():
    settings = {
        "model": "gpt-4",
        "temperature": 0,
    }

    stream = await client.chat.completions.create(
        messages=message_history, stream=True, **settings
    )

    current_step = cl.context.current_step

    async for part in stream:
        delta = part.choices[0].delta

        if delta.content:
            # Stream the output of the step
            await current_step.stream_token(delta.content)

嵌套步骤

如果在被装饰的函数内部调用另一个步骤装饰的函数,子步骤将嵌套在父步骤下。

import chainlit as cl

@cl.step
async def parent_step():
    await child_step()
    return "Parent step output"

@cl.step
async def child_step():
    return "Child step output"

@cl.on_chat_start
async def main():
    await parent_step()