-
Notifications
You must be signed in to change notification settings - Fork 3k
TaskAdherence V2 prompt updates #41616
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ghyadav
wants to merge
11
commits into
Azure:main
Choose a base branch
from
ghyadav:ghyadav/task_adherence_v2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+581
−146
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
1871240
TaskAdherence V2 prompt updates
ghyadav a347a40
Add system messages to task adherence examples
ghyadav edd6e60
Add system messages to task adherence examples
ghyadav f692e37
Merge branch 'main' of https://github.com/ghyadav/azure-sdk-for-pytho…
ghyadav 0669e9f
Add system messages to task adherence examples
ghyadav 1da09c8
Add system messages to task adherence examples
ghyadav 7d685ab
Add system messages to task adherence examples
ghyadav 1a5115d
Add system messages to task adherence examples
ghyadav d745555
Prompt hanges with lesses example. Inter variance similar
ghyadav 6ed8325
Prompt hanges with lesses example. Inter variance similar
ghyadav dcaf3c9
Latest prompt
ghyadav File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -97,7 +97,7 @@ def _is_openai_model_config(val: object) -> TypeGuard[OpenAIModelConfiguration]: | |
|
||
|
||
def parse_model_config_type( | ||
model_config: Union[AzureOpenAIModelConfiguration, OpenAIModelConfiguration], | ||
model_config: Union[AzureOpenAIModelConfiguration, OpenAIModelConfiguration], | ||
) -> None: | ||
if _is_aoi_model_config(model_config): | ||
model_config["type"] = AZURE_OPENAI_TYPE | ||
|
@@ -106,9 +106,9 @@ def parse_model_config_type( | |
|
||
|
||
def construct_prompty_model_config( | ||
model_config: Union[AzureOpenAIModelConfiguration, OpenAIModelConfiguration], | ||
default_api_version: str, | ||
user_agent: str, | ||
model_config: Union[AzureOpenAIModelConfiguration, OpenAIModelConfiguration], | ||
default_api_version: str, | ||
user_agent: str, | ||
) -> dict: | ||
parse_model_config_type(model_config) | ||
|
||
|
@@ -126,6 +126,7 @@ def construct_prompty_model_config( | |
|
||
return prompty_model_config | ||
|
||
|
||
def is_onedp_project(azure_ai_project: AzureAIProject) -> bool: | ||
"""Check if the Azure AI project is an OneDP project. | ||
|
@@ -138,6 +139,7 @@ def is_onedp_project(azure_ai_project: AzureAIProject) -> bool: | |
return True | ||
return False | ||
|
||
|
||
def validate_azure_ai_project(o: object) -> AzureAIProject: | ||
fields = {"subscription_id": str, "resource_group_name": str, "project_name": str} | ||
|
||
|
@@ -230,7 +232,7 @@ def _validate_typed_dict(o: object, t: Type[T_TypedDict]) -> T_TypedDict: | |
k | ||
for k in annotations | ||
if (is_total and get_origin(annotations[k]) is not NotRequired) | ||
or (not is_total and get_origin(annotations[k]) is Required) | ||
or (not is_total and get_origin(annotations[k]) is Required) | ||
} | ||
|
||
missing_keys = required_keys - o.keys() | ||
|
@@ -291,7 +293,8 @@ def validate_annotation(v: object, annotation: Union[str, type, object]) -> bool | |
|
||
return cast(T_TypedDict, o) | ||
|
||
def check_score_is_valid(score: Union[str, float], min_score = 1, max_score = 5) -> bool: | ||
|
||
def check_score_is_valid(score: Union[str, float], min_score=1, max_score=5) -> bool: | ||
"""Check if the score is valid, i.e. is convertable to number and is in the range [min_score, max_score]. | ||
:param score: The score to check. | ||
|
@@ -310,6 +313,7 @@ def check_score_is_valid(score: Union[str, float], min_score = 1, max_score = 5) | |
|
||
return min_score <= numeric_score <= max_score | ||
|
||
|
||
def parse_quality_evaluator_reason_score(llm_output: str, valid_score_range: str = "[1-5]") -> Tuple[float, str]: | ||
"""Parse the output of prompt-based quality evaluators that return a score and reason. | ||
|
@@ -422,11 +426,11 @@ def raise_exception(msg, target): | |
except ImportError as ex: | ||
raise MissingRequiredPackage( | ||
message="Please install 'azure-ai-inference' package to use SystemMessage, " | ||
"UserMessage or AssistantMessage." | ||
"UserMessage or AssistantMessage." | ||
) from ex | ||
|
||
if isinstance(message, ChatRequestMessage) and not isinstance( | ||
message, (UserMessage, AssistantMessage, SystemMessage) | ||
message, (UserMessage, AssistantMessage, SystemMessage) | ||
): | ||
raise_exception( | ||
f"Messages must be a strongly typed class of ChatRequestMessage. Message number: {num}", | ||
|
@@ -437,7 +441,7 @@ def raise_exception(msg, target): | |
if isinstance(message, UserMessage): | ||
user_message_count += 1 | ||
if isinstance(message.content, list) and any( | ||
isinstance(item, ImageContentItem) for item in message.content | ||
isinstance(item, ImageContentItem) for item in message.content | ||
): | ||
image_found = True | ||
continue | ||
|
@@ -481,21 +485,26 @@ def raise_exception(msg, target): | |
ErrorTarget.CONTENT_SAFETY_CHAT_EVALUATOR, | ||
) | ||
|
||
|
||
def _extract_text_from_content(content): | ||
text = [] | ||
for msg in content: | ||
if 'text' in msg: | ||
text.append(msg['text']) | ||
return text | ||
|
||
def _get_conversation_history(query): | ||
|
||
def _get_conversation_history(query, include_system_messages=False): | ||
all_user_queries = [] | ||
cur_user_query = [] | ||
all_agent_responses = [] | ||
cur_agent_response = [] | ||
system_message = None | ||
for msg in query: | ||
if not 'role' in msg: | ||
continue | ||
if include_system_messages and msg['role'] == 'system' and 'content' in msg: | ||
system_message = msg.get('content', '') | ||
if msg['role'] == 'user' and 'content' in msg: | ||
if cur_agent_response != []: | ||
all_agent_responses.append(cur_agent_response) | ||
|
@@ -505,15 +514,15 @@ def _get_conversation_history(query): | |
cur_user_query.append(text_in_msg) | ||
|
||
if msg['role'] == 'assistant' and 'content' in msg: | ||
if cur_user_query !=[]: | ||
if cur_user_query != []: | ||
all_user_queries.append(cur_user_query) | ||
cur_user_query = [] | ||
text_in_msg = _extract_text_from_content(msg['content']) | ||
if text_in_msg: | ||
cur_agent_response.append(text_in_msg) | ||
if cur_user_query !=[]: | ||
if cur_user_query != []: | ||
all_user_queries.append(cur_user_query) | ||
if cur_agent_response !=[]: | ||
if cur_agent_response != []: | ||
all_agent_responses.append(cur_agent_response) | ||
|
||
if len(all_user_queries) != len(all_agent_responses) + 1: | ||
|
@@ -524,31 +533,37 @@ def _get_conversation_history(query): | |
category=ErrorCategory.INVALID_VALUE, | ||
blame=ErrorBlame.USER_ERROR, | ||
) | ||
|
||
return { | ||
'user_queries' : all_user_queries, | ||
'agent_responses' : all_agent_responses | ||
} | ||
'system_message': system_message, | ||
'user_queries': all_user_queries, | ||
'agent_responses': all_agent_responses | ||
} | ||
|
||
|
||
def _pretty_format_conversation_history(conversation_history): | ||
"""Formats the conversation history for better readability.""" | ||
formatted_history = "" | ||
for i, (user_query, agent_response) in enumerate(zip(conversation_history['user_queries'], conversation_history['agent_responses']+[None])): | ||
formatted_history+=f"User turn {i+1}:\n" | ||
if 'system_message' in conversation_history and conversation_history['system_message'] is not None: | ||
formatted_history += "SYSTEM MESSAGE:\n" | ||
formatted_history += " " + conversation_history['system_message'] + "\n\n" | ||
for i, (user_query, agent_response) in enumerate( | ||
zip(conversation_history['user_queries'], conversation_history['agent_responses'] + [None])): | ||
formatted_history += f"User turn {i + 1}:\n" | ||
for msg in user_query: | ||
formatted_history+=" " + "\n ".join(msg) | ||
formatted_history+="\n\n" | ||
formatted_history += " " + "\n ".join(msg) | ||
formatted_history += "\n\n" | ||
if agent_response: | ||
formatted_history+=f"Agent turn {i+1}:\n" | ||
formatted_history += f"Agent turn {i + 1}:\n" | ||
for msg in agent_response: | ||
formatted_history+=" " + "\n ".join(msg) | ||
formatted_history+="\n\n" | ||
formatted_history += " " + "\n ".join(msg) | ||
formatted_history += "\n\n" | ||
return formatted_history | ||
|
||
def reformat_conversation_history(query, logger = None): | ||
|
||
def reformat_conversation_history(query, logger=None, include_system_messages=False): | ||
"""Reformats the conversation history to a more compact representation.""" | ||
try: | ||
conversation_history = _get_conversation_history(query) | ||
conversation_history = _get_conversation_history(query, include_system_messages=include_system_messages) | ||
return _pretty_format_conversation_history(conversation_history) | ||
except: | ||
# If the conversation history cannot be parsed for whatever reason (e.g. the converter format changed), the original query is returned | ||
|
@@ -562,25 +577,59 @@ def reformat_conversation_history(query, logger = None): | |
logger.warning(f"Conversation history could not be parsed, falling back to original query: {query}") | ||
return query | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The fallback returns the original message list rather than a string, which may break downstream prompts that expect a formatted string. Consider serializing or stringifying the original query for consistency. Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||
|
||
def _get_agent_response(agent_response_msgs): | ||
"""Extracts the text from the agent response content.""" | ||
|
||
def _get_agent_response(agent_response_msgs, include_tool_messages=False): | ||
"""Extracts formatted agent response including text, and optionally tool calls/results.""" | ||
agent_response_text = [] | ||
tool_results = {} | ||
|
||
# First pass: collect tool results | ||
if include_tool_messages: | ||
for msg in agent_response_msgs: | ||
if msg.get("role") == "tool" and "tool_call_id" in msg: | ||
for content in msg.get("content", []): | ||
if content.get("type") == "tool_result": | ||
result = content.get("tool_result") | ||
tool_results[msg["tool_call_id"]] = f'[TOOL_RESULT] {result}' | ||
|
||
# Second pass: parse assistant messages and tool calls | ||
for msg in agent_response_msgs: | ||
if 'role' in msg and msg['role'] == 'assistant' and 'content' in msg: | ||
text = _extract_text_from_content(msg['content']) | ||
if 'role' in msg and msg.get("role") == "assistant" and "content" in msg: | ||
text = _extract_text_from_content(msg["content"]) | ||
if text: | ||
agent_response_text.extend(text) | ||
if include_tool_messages: | ||
for content in msg.get("content", []): | ||
# Todo: Verify if this is the correct way to handle tool calls | ||
if content.get("type") == "tool_call": | ||
if "tool_call" in content: | ||
tc = content.get("tool_call", {}) | ||
func_name = tc.get("function", {}).get("name", "") | ||
args = tc.get("function", {}).get("arguments", {}) | ||
tool_call_id = tc.get("id") | ||
else: | ||
tool_call_id = content.get("tool_call_id") | ||
func_name = content.get("name", "") | ||
args = content.get("arguments", {}) | ||
args_str = ", ".join(f'{k}="{v}"' for k, v in args.items()) | ||
call_line = f'[TOOL_CALL] {func_name}({args_str})' | ||
agent_response_text.append(call_line) | ||
if tool_call_id in tool_results: | ||
agent_response_text.append(tool_results[tool_call_id]) | ||
|
||
return agent_response_text | ||
|
||
def reformat_agent_response(response, logger = None): | ||
|
||
def reformat_agent_response(response, logger=None, include_tool_messages=False): | ||
try: | ||
if response is None or response == []: | ||
return "" | ||
agent_response = _get_agent_response(response) | ||
agent_response = _get_agent_response(response, include_tool_messages=include_tool_messages) | ||
if agent_response == []: | ||
# If no message could be extracted, likely the format changed, fallback to the original response in that case | ||
if logger: | ||
logger.warning(f"Empty agent response extracted, likely due to input schema change. Falling back to using the original response: {response}") | ||
logger.warning( | ||
f"Empty agent response extracted, likely due to input schema change. Falling back to using the original response: {response}") | ||
return response | ||
return "\n".join(agent_response) | ||
except: | ||
|
@@ -590,6 +639,18 @@ def reformat_agent_response(response, logger = None): | |
logger.warning(f"Agent response could not be parsed, falling back to original response: {response}") | ||
return response | ||
|
||
|
||
def reformat_tool_definitions(tool_definitions, logger=None): | ||
output_lines = ["TOOL DEFINITIONS:"] | ||
for tool in tool_definitions: | ||
name = tool.get("name", "unnamed_tool") | ||
desc = tool.get("description", "").strip() | ||
params = tool.get("parameters", {}).get("properties", {}) | ||
param_names = ", ".join(params.keys()) if params else "no parameters" | ||
output_lines.append(f"- {name}: {desc} (inputs: {param_names})") | ||
return "\n".join(output_lines) | ||
|
||
|
||
def upload(path: str, container_client: ContainerClient, logger=None): | ||
"""Upload files or directories to Azure Blob Storage using a container client. | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid using a bare except which can hide unexpected errors; catch specific exceptions (e.g.,
ValueError
,KeyError
) and log the exception to aid debugging.Copilot uses AI. Check for mistakes.