Skip to content

Adding configurability for CopilotClient ClientSession creation#277

Closed
rodrigobr-msft wants to merge 3 commits intomainfrom
users/robrandao/copilot-client-config
Closed

Adding configurability for CopilotClient ClientSession creation#277
rodrigobr-msft wants to merge 3 commits intomainfrom
users/robrandao/copilot-client-config

Conversation

@rodrigobr-msft
Copy link
Contributor

@rodrigobr-msft rodrigobr-msft commented Dec 3, 2025

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_defaults option in the connection settings, which is then used to configure the underlying aiohttp.ClientSession in API requests.

Session customization improvements:

  • Added a new client_session_defaults parameter to the ConnectionSettings class initializer, allowing users to specify custom options for aiohttp.ClientSession.
  • Set self.client_session_defaults in the ConnectionSettings class, defaulting to an empty dictionary if none is provided.

API request handling:

  • Updated the CopilotClient.post_request method to use the client_session_defaults from the connection settings when creating the aiohttp.ClientSession, enabling custom session configuration for outgoing requests.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_defaults parameter to ConnectionSettings.__init__() to accept custom session configuration
  • Modified CopilotClient.post_request() to pass these settings when creating the ClientSession

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,
Copy link

Copilot AI Dec 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
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 {}
Copy link

Copilot AI Dec 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +31 to 34
async with aiohttp.ClientSession(
**self.settings.client_session_defaults
) as session:
async with session.post(url, json=data, headers=headers) as response:
Copy link

Copilot AI Dec 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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 uses AI. Check for mistakes.
copilot_agent_type: Optional[AgentType],
custom_power_platform_cloud: Optional[str],
client_session_defaults: Optional[dict] = None,
) -> None:
Copy link

Copilot AI Dec 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
) -> 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
)
"""

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments