将流程作为函数执行#

实验性功能

这是一个实验性功能,可能会随时更改。了解更多更多

概述#

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 内容替换。 如果在 overridesflow.dag.yaml 变为无效,执行时将引发验证错误。

将流加载为具有流输出的函数#

在流程上下文中设置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

参考我们的sample以了解使用方法。

具有多个覆盖的流程#

注意: 在某些情况下,流程上下文配置可能会相互影响。例如,使用 connectionoverrides 来覆盖相同的节点。 对于这些场景,行为是未定义的。请避免此类用法。

# 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}
)

下一步#

了解更多关于: