将流作为函数执行#
实验性功能
这是一个实验性功能,随时可能更改。了解更多。
概述#
Promptflow 允许您加载流并在代码中将其用作函数。当在流之上构建服务时,此功能非常有用,请参阅此处,了解使用流函数消费的简单示例服务。
加载并调用流函数#
要使用流即函数功能,您首先需要使用load_flow
函数加载流。然后,您可以通过为其提供键值参数来像函数一样使用流对象。
f = load_flow("../../examples/flows/standard/web-classification/")
f(url="sample_url")
使用上下文配置流#
您可以通过设置flow.context
在流函数执行之前覆盖一些流配置。
使用内存中连接覆盖加载流作为函数#
通过向流上下文提供连接对象,流在执行时无需获取连接,这在需要多次调用流函数的情况下可以节省时间。
from promptflow.entities import AzureOpenAIConnection
connection_obj = AzureOpenAIConnection(
name=conn_name,
api_key=api_key,
api_base=api_base,
api_type="azure",
api_version=api_version,
)
# no need to create the connection object.
f.context = FlowContext(
connections={"classify_with_llm": {"connection": connection_obj}}
)
具有流输入覆盖的本地流作为函数#
通过提供覆盖,原始流 DAG 将在执行时更新。
f.context = FlowContext(
# node "fetch_text_content_from_url" will take inputs from the following command instead of from flow input
overrides={"nodes.fetch_text_content_from_url.inputs.url": sample_url},
)
注意,overrides
仅在原始flow.dag.yaml
上进行 YAML 内容替换。如果flow.dag.yaml
在overrides
之后变得无效,则在执行时将引发验证错误。
加载带有流式输出的流作为函数#
在流上下文中设置streaming
后,流函数将返回一个迭代器来流式传输输出。
f = load_flow(source="../../examples/flows/chat/chat-basic/")
f.context.streaming = True
result = f(
chat_history=[
{
"inputs": {"chat_input": "Hi"},
"outputs": {"chat_output": "Hello! How can I assist you today?"},
}
],
question="How are you?",
)
answer = ""
# the result will be a generator, iterate it to get the result
for r in result["answer"]:
answer += r
请参阅我们的示例以了解用法。
具有多个覆盖的流#
注意:流上下文配置在某些情况下可能会相互影响。例如,使用connection
和overrides
来覆盖同一个节点。这些场景的行为未定义。请避免此类用法。
# overriding `classify_with_llm`'s connection and inputs in the same time will lead to undefined behavior.
f.context = FlowContext(
connections={"classify_with_llm": {"connection": connection_obj}},
overrides={"nodes.classify_with_llm.inputs.url": sample_url}
)
后续步骤#
了解更多关于