Skip to main content

跟踪生成器函数

在大多数 LLM 应用中,您希望流式输出以最小化用户看到第一个 token 的时间。

LangSmith 的追踪功能原生支持通过 generator 函数实现的流式输出。以下是示例。

from langsmith import traceable

@traceable
def my_generator():
for chunk in ["Hello", "World", "!"]:
yield chunk

# Stream to the user
for output in my_generator():
print(output)

# It also works with async functions
import asyncio

@traceable
async def my_async_generator():
hunk in ["Hello", "World", "!"]:
yield chunk

# Stream to the user
async def main():
async for output in my_async_generator():
print(output)

asyncio.run(main())

聚合结果

默认情况下,被跟踪函数的 outputs 会聚合为 LangSmith 中的一个单一数组。 如果您想自定义其存储方式(例如将输出连接为单个字符串),可以使用 aggregate 选项(在 Python 中为 reduce_fn)。 这对于聚合流式 LLM 输出尤其有用。

注意

聚合输出 影响输出的追踪表示。它不会改变函数返回的值。

from langsmith import traceable

def concatenate_strings(outputs: list):
return "".join(outputs)

@traceable(reduce_fn=concatenate_strings)
def my_generator():
for chunk in ["Hello", "World", "!"]:
yield chunk

# Stream to the user
for output in my_generator():
print(output)

# It also works with async functions
import asyncio

@traceable(reduce_fn=concatenate_strings)
async def my_async_generator():
for chunk in ["Hello", "World", "!"]:
yield chunk

# Stream to the user
async def main():
async for output in my_async_generator():
print(output)

asyncio.run(main())

此页面有帮助吗?


您可以留下详细的反馈 在 GitHub 上