跳到主要内容
在大多数 LLM 应用程序中,您会希望流式传输输出,以最大程度地减少用户看到第一个标记的时间。 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():
  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())

聚合结果

默认情况下,追踪函数的 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())

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.