Adding configurability for CopilotClient ClientSession creation#277
Adding configurability for CopilotClient ClientSession creation#277rodrigobr-msft wants to merge 3 commits intomainfrom
Conversation
There was a problem hiding this comment.
Pull request overview
This PR adds configurability for aiohttp.ClientSession creation in the CopilotClient by introducing a new client_session_defaults parameter. This allows users to customize session parameters such as timeouts, connectors, or other client session settings when making requests to the Copilot Studio service.
Key Changes:
- Added
client_session_defaultsparameter toConnectionSettings.__init__()to accept custom session configuration - Modified
CopilotClient.post_request()to pass these settings when creating theClientSession
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
connection_settings.py |
Added optional client_session_defaults parameter to store custom aiohttp ClientSession configuration |
copilot_client.py |
Updated ClientSession instantiation to unpack client_session_defaults from settings |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| cloud: Optional[PowerPlatformCloud], | ||
| copilot_agent_type: Optional[AgentType], | ||
| custom_power_platform_cloud: Optional[str], | ||
| client_session_defaults: Optional[dict] = None, |
There was a problem hiding this comment.
The type hint dict is too generic. Consider using Dict[str, Any] from the typing module for better type safety, or even better, define the expected structure more explicitly if the aiohttp.ClientSession constructor parameters are known.
| self.cloud = cloud or PowerPlatformCloud.PROD | ||
| self.copilot_agent_type = copilot_agent_type or AgentType.PUBLISHED | ||
| self.custom_power_platform_cloud = custom_power_platform_cloud | ||
| self.client_session_defaults = client_session_defaults or {} |
There was a problem hiding this comment.
The client_session_defaults attribute should be added to the DirectToEngineConnectionSettingsProtocol to maintain protocol conformance. Since ConnectionSettings implements this protocol, all attributes should be declared in the protocol interface.
| async with aiohttp.ClientSession( | ||
| **self.settings.client_session_defaults | ||
| ) as session: | ||
| async with session.post(url, json=data, headers=headers) as response: |
There was a problem hiding this comment.
Passing arbitrary user-provided dictionary values to aiohttp.ClientSession could lead to runtime errors if invalid parameters are provided. Consider adding validation for the dictionary keys/values, or at least wrapping this in a try-except block to provide a more helpful error message if invalid session parameters are provided.
| async with aiohttp.ClientSession( | |
| **self.settings.client_session_defaults | |
| ) as session: | |
| async with session.post(url, json=data, headers=headers) as response: | |
| try: | |
| async with aiohttp.ClientSession( | |
| **self.settings.client_session_defaults | |
| ) as session: | |
| async with session.post(url, json=data, headers=headers) as response: | |
| if response.status != 200: | |
| # self.logger(f"Error sending request: {response.status}") | |
| raise aiohttp.ClientError( | |
| f"Error sending request: {response.status}" | |
| ) | |
| # Set conversation ID from response header when status is 200 | |
| conversation_id_header = response.headers.get("x-ms-conversationid") | |
| if conversation_id_header: | |
| self._current_conversation_id = conversation_id_header | |
| event_type = None | |
| async for line in response.content: | |
| if line.startswith(b"event:"): | |
| event_type = line[6:].decode("utf-8").strip() | |
| if line.startswith(b"data:") and event_type == "activity": | |
| activity_data = line[5:].decode("utf-8").strip() | |
| activity = Activity.model_validate_json(activity_data) | |
| if activity.type == ActivityTypes.message: | |
| self._current_conversation_id = activity.conversation.id | |
| yield activity | |
| except TypeError as e: | |
| raise ValueError( | |
| f"Invalid parameters provided to aiohttp.ClientSession: {e}. " | |
| f"Check self.settings.client_session_defaults for invalid keys/values." | |
| ) from e |
| copilot_agent_type: Optional[AgentType], | ||
| custom_power_platform_cloud: Optional[str], | ||
| client_session_defaults: Optional[dict] = None, | ||
| ) -> None: |
There was a problem hiding this comment.
The client_session_defaults parameter lacks documentation. Consider adding a docstring comment to the __init__ method or inline documentation explaining what this parameter is for, what keys are supported, and providing usage examples.
| ) -> None: | |
| ) -> None: | |
| """ | |
| Initializes a new instance of ConnectionSettings. | |
| Args: | |
| environment_id (str): The ID of the Power Platform environment. | |
| agent_identifier (str): The identifier for the agent. | |
| cloud (Optional[PowerPlatformCloud]): The Power Platform cloud to use. Defaults to PROD if not specified. | |
| copilot_agent_type (Optional[AgentType]): The type of Copilot agent. Defaults to PUBLISHED if not specified. | |
| custom_power_platform_cloud (Optional[str]): Custom cloud endpoint, if applicable. | |
| client_session_defaults (Optional[dict]): Optional dictionary of default values for the client session. | |
| Supported keys may include configuration options such as authentication tokens, | |
| user preferences, or other session-specific settings. The exact keys depend on the | |
| client implementation. | |
| Example: | |
| client_session_defaults = { | |
| "auth_token": "your_token_here", | |
| "locale": "en-US", | |
| "timeout": 30 | |
| } | |
| settings = ConnectionSettings( | |
| environment_id="env123", | |
| agent_identifier="agent456", | |
| cloud=PowerPlatformCloud.PROD, | |
| copilot_agent_type=AgentType.PUBLISHED, | |
| custom_power_platform_cloud=None, | |
| client_session_defaults=client_session_defaults | |
| ) | |
| """ |
This pull request updates the way HTTP client sessions are configured in the Copilot Studio client, allowing for more flexible session customization. The main change is the introduction of a
client_session_defaultsoption in the connection settings, which is then used to configure the underlyingaiohttp.ClientSessionin API requests.Session customization improvements:
client_session_defaultsparameter to theConnectionSettingsclass initializer, allowing users to specify custom options foraiohttp.ClientSession.self.client_session_defaultsin theConnectionSettingsclass, defaulting to an empty dictionary if none is provided.API request handling:
CopilotClient.post_requestmethod to use theclient_session_defaultsfrom the connection settings when creating theaiohttp.ClientSession, enabling custom session configuration for outgoing requests.