跟踪生成器函数
在大多数 LLM 应用程序中,你将希望流式传输输出,以最大限度地减少用户看到第一个 Token 的时间。
LangSmith 的追踪功能原生支持通过 generator
函数进行流式输出。以下是一个示例。
- Python
- TypeScript
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())
import { traceable } from "langsmith/traceable";
const myGenerator = traceable(function* () {
for (const chunk of ["Hello", "World", "!"]) {
yield chunk;
}
});
for (const output of myGenerator()) {
console.log(output);
}
聚合结果
默认情况下,被追踪函数的 outputs
会在 LangSmith 中聚合到一个数组中。 如果你想自定义其存储方式(例如,将输出连接成一个字符串),你可以使用 aggregate
选项(Python 中为 reduce_fn
)。 这对于聚合流式 LLM 输出尤其有用。
注意
聚合输出仅影响输出的追踪表示。 它不会改变你的函数返回的值。
- Python
- TypeScript
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())
import { traceable } from "langsmith/traceable";
const concatenateStrings = (outputs: string[]) => outputs.join("");
const myGenerator = traceable(function* () {
for (const chunk of ["Hello", "World", "!"]) {
yield chunk;
}
}, { aggregator: concatenateStrings });
for (const output of await myGenerator()) {
console.log(output);
}