Skip to content

Commit 5ed0e82

Browse files
YingChen1996Ying Chen
and
Ying Chen
authored
[Serving] Support default env var override behavior for connection (#713)
# Description Please add an informative description that covers that changes made by the pull request and link all relevant issues. # All Promptflow Contribution checklist: - [ ] **The pull request does not introduce [breaking changes].** - [ ] **CHANGELOG is updated for new features, bug fixes or other significant changes.** - [ ] **I have read the [contribution guidelines](../CONTRIBUTING.md).** - [ ] **Create an issue and link to the pull request to get dedicated review from promptflow team. Learn more: [suggested workflow](../CONTRIBUTING.md#suggested-workflow).** ## General Guidelines and Best Practices - [ ] Title of the pull request is clear and informative. - [ ] There are a small number of commits, each of which have an informative message. This means that previously merged commits do not appear in the history of the PR. For more information on cleaning up the commits in your PR, [see this page](https://github.com/Azure/azure-powershell/blob/master/documentation/development-docs/cleaning-up-commits.md). ### Testing Guidelines - [ ] Pull request includes test coverage for the included changes. --------- Co-authored-by: Ying Chen <2601502859@qq.com>
1 parent 8f04d2e commit 5ed0e82

File tree

4 files changed

+56
-0
lines changed

4 files changed

+56
-0
lines changed

docs/how-to-guides/deploy-a-flow/deploy-using-dev-server.md

+7
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,13 @@ an example to show how to deploy a flow.
1414
Please ensure you have [create the connection](../manage-connections.md#create-a-connection) required by flow, if not, you could
1515
refer to [Setup connection for web-classification](https://github.com/microsoft/promptflow/tree/main/examples/flows/standard/web-classification).
1616

17+
Note: We will use relevant environment variable ({connection_name}_{key_name}) to override connection configurations in
18+
serving mode, white space in connection name will be removed directly from environment variable name. For instance,
19+
if there is a custom connection named 'custom_connection' with a configuration key called 'chat_deployment_name,' the
20+
function will attempt to retrieve 'chat_deployment_name' from the environment variable
21+
'CUSTOM_CONNECTION_CHAT_DEPLOYMENT_NAME' by default. If the environment variable is not set, it will use the original
22+
value as a fallback.
23+
1724

1825
The following CLI commands allows you serve a flow folder as an endpoint. By running this command, a [flask](https://flask.palletsprojects.com/en/) app will start in the environment where command is executed, please ensure all prerequisites required by flow have been installed.
1926
```bash

src/promptflow/promptflow/_sdk/_serving/flow_invoker.py

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
get_local_connections_from_executable,
1313
resolve_connections_environment_variable_reference,
1414
update_environment_variables_with_connections,
15+
override_connection_config_with_environment_variable,
1516
)
1617
from promptflow._sdk.entities._connection import _Connection
1718
from promptflow.executor import FlowExecutor
@@ -61,6 +62,7 @@ def _init_connections(self, connection_provider):
6162
else:
6263
raise UnsupportedConnectionProvider(connection_provider)
6364

65+
override_connection_config_with_environment_variable(self.connections)
6466
resolve_connections_environment_variable_reference(self.connections)
6567
update_environment_variables_with_connections(self.connections)
6668
logger.info(f"Promptflow get connections successfully. keys: {self.connections.keys()}")

src/promptflow/promptflow/_sdk/_utils.py

+23
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,29 @@ def _match_env_reference(val: str):
317317
return name
318318

319319

320+
def override_connection_config_with_environment_variable(connections: Dict[str, dict]):
321+
"""
322+
The function will use relevant environment variable to override connection configurations. For instance, if there
323+
is a custom connection named 'custom_connection' with a configuration key called 'chat_deployment_name,' the
324+
function will attempt to retrieve 'chat_deployment_name' from the environment variable
325+
'CUSTOM_CONNECTION_CHAT_DEPLOYMENT_NAME' by default. If the environment variable is not set, it will use the
326+
original value as a fallback.
327+
"""
328+
logger = logging.getLogger(LOGGER_NAME)
329+
for connection_name, connection in connections.items():
330+
values = connection.get("value", {})
331+
for key, val in values.items():
332+
connection_name = connection_name.replace(" ", "_")
333+
env_name = f"{connection_name}_{key}".upper()
334+
if env_name not in os.environ:
335+
continue
336+
values[key] = os.environ[env_name]
337+
logger.info(
338+
f"Connection {connection_name}'s {key} is overridden with environment variable {env_name}"
339+
)
340+
return connections
341+
342+
320343
def resolve_connections_environment_variable_reference(connections: Dict[str, dict]):
321344
"""The function will resolve connection secrets env var reference like api_key: ${env:KEY}"""
322345
for connection in connections.values():

src/promptflow/tests/sdk_cli_test/unittests/test_utils.py

+24
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
generate_flow_tools_json,
3131
refresh_connections_dir,
3232
resolve_connections_environment_variable_reference,
33+
override_connection_config_with_environment_variable,
3334
snake_to_camel,
3435
)
3536

@@ -87,6 +88,29 @@ def test_resolve_connections_environment_variable_reference(self):
8788
assert connections["test_connection"]["value"]["api_base"] == "BASE"
8889
assert connections["test_custom_connection"]["value"]["key"] == "CUSTOM_VALUE"
8990

91+
def test_override_connection_config_with_environment_variable(self):
92+
connections = {
93+
"test_connection": {
94+
"type": "AzureOpenAIConnection",
95+
"value": {
96+
"api_key": "KEY",
97+
"api_base": "https://gpt-test-eus.openai.azure.com/",
98+
},
99+
},
100+
"test_custom_connection": {
101+
"type": "CustomConnection",
102+
"value": {"key": "value1", "key2": "value2"},
103+
},
104+
}
105+
with mock.patch.dict(
106+
os.environ, {"TEST_CONNECTION_API_BASE": "BASE", "TEST_CUSTOM_CONNECTION_KEY": "CUSTOM_VALUE"}
107+
):
108+
override_connection_config_with_environment_variable(connections)
109+
assert connections["test_connection"]["value"]["api_key"] == "KEY"
110+
assert connections["test_connection"]["value"]["api_base"] == "BASE"
111+
assert connections["test_custom_connection"]["value"]["key"] == "CUSTOM_VALUE"
112+
assert connections["test_custom_connection"]["value"]["key2"] == "value2"
113+
90114
def test_generate_flow_tools_json(self) -> None:
91115
# call twice to ensure system path won't be affected during generation
92116
for _ in range(2):

0 commit comments

Comments
 (0)