Python: Add samples syntax checking with pyright (#3710)

* Add samples syntax checking with pyright

- Add pyrightconfig.samples.json with relaxed type checking but import validation
- Add samples-syntax poe task to check samples for syntax and import errors
- Add samples-syntax to check and pre-commit-check tasks
- Fix 78 sample errors:
  - Update workflow builder imports to use agent_framework_orchestrations
  - Change content type isinstance checks to content.type comparisons
  - Use Content factory methods instead of removed content type classes
  - Fix TypedDict access patterns for Annotation
  - Fix various API mismatches (normalize_messages, ChatMessage.text, role)

* fixed a bunch of samples and tweaks to pre-commit

* updated lock

* updated lock

* fixes

* added lint to samples
This commit is contained in:
Eduard van Valkenburg
2026-02-07 08:10:47 +01:00
committed by GitHub
Unverified
parent 74ac470a56
commit 390f93344c
83 changed files with 606 additions and 498 deletions
@@ -10,6 +10,7 @@ from agent_framework import (
ChatMessage,
ChatMiddleware,
ChatResponse,
MiddlewareTermination,
chat_middleware,
tool,
)
@@ -127,8 +128,7 @@ async def security_and_override_middleware(
)
# Set terminate flag to stop execution
context.terminate = True
return
raise MiddlewareTermination
# Continue to next middleware or AI execution
await next(context)
@@ -10,6 +10,7 @@ from agent_framework import (
AgentMiddleware,
AgentResponse,
ChatMessage,
MiddlewareTermination,
tool,
)
from agent_framework.azure import AzureAIAgentClient
@@ -72,8 +73,7 @@ class PreTerminationMiddleware(AgentMiddleware):
)
# Set terminate flag to prevent further processing
context.terminate = True
break
raise MiddlewareTermination
await next(context)
@@ -98,7 +98,7 @@ class PostTerminationMiddleware(AgentMiddleware):
f"[PostTerminationMiddleware] Maximum responses ({self.max_responses}) reached. "
"Terminating further processing."
)
context.terminate = True
raise MiddlewareTermination
# Allow the agent to process normally
await next(context)
@@ -15,7 +15,6 @@ from agent_framework import (
ChatResponse,
ChatResponseUpdate,
ResponseStream,
Role,
tool,
)
from agent_framework.openai import OpenAIResponsesClient
@@ -76,12 +75,12 @@ async def weather_override_middleware(context: ChatContext, next: Callable[[Chat
index["value"] += 1
return update
context.result.with_update_hook(_update_hook)
context.result.with_transform_hook(_update_hook)
else:
# For non-streaming: just replace with a new message
current_text = context.result.text or ""
current_text = context.result.text or "" # type: ignore
custom_message = f"Weather Advisory: [0] {''.join(chunks)} Original message was: {current_text}"
context.result = ChatResponse(messages=[ChatMessage(role=Role.ASSISTANT, text=custom_message)])
context.result = ChatResponse(messages=[ChatMessage(role="assistant", text=custom_message)])
async def validate_weather_middleware(context: ChatContext, next: Callable[[ChatContext], Awaitable[None]]) -> None:
@@ -96,12 +95,12 @@ async def validate_weather_middleware(context: ChatContext, next: Callable[[Chat
if context.stream and isinstance(context.result, ResponseStream):
def _append_validation_note(response: ChatResponse) -> ChatResponse:
response.messages.append(ChatMessage(role=Role.ASSISTANT, text=validation_note))
response.messages.append(ChatMessage(role="assistant", text=validation_note))
return response
context.result.with_finalizer(_append_validation_note)
context.result.with_result_hook(_append_validation_note)
elif isinstance(context.result, ChatResponse):
context.result.messages.append(ChatMessage(role=Role.ASSISTANT, text=validation_note))
context.result.messages.append(ChatMessage(role="assistant", text=validation_note))
async def agent_cleanup_middleware(context: AgentContext, next: Callable[[AgentContext], Awaitable[None]]) -> None:
@@ -154,7 +153,7 @@ async def agent_cleanup_middleware(context: AgentContext, next: Callable[[AgentC
if not found_validation:
raise RuntimeError("Expected validation note not found in agent response.")
cleaned_messages.append(ChatMessage(role=Role.ASSISTANT, text=" Agent: OK"))
cleaned_messages.append(ChatMessage(role="assistant", text=" Agent: OK"))
response.messages = cleaned_messages
return response
@@ -172,8 +171,8 @@ async def agent_cleanup_middleware(context: AgentContext, next: Callable[[AgentC
content.text = text
return update
context.result.with_update_hook(_clean_update)
context.result.with_finalizer(_sanitize)
context.result.with_transform_hook(_clean_update)
context.result.with_result_hook(_sanitize)
elif isinstance(context.result, AgentResponse):
context.result = _sanitize(context.result)
@@ -192,6 +191,19 @@ async def main() -> None:
tools=get_weather,
middleware=[agent_cleanup_middleware],
)
# Streaming example
print("\n--- Streaming Example ---")
query = "What's the weather like in Portland?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
response = agent.run(query, stream=True)
# add the hooks to print what you want to see
response.with_transform_hook(lambda chunk: print(chunk.text, end="", flush=True)).with_result_hook(
lambda final: print(f"\nFinal streamed response: {final.text}", flush=True)
)
# consume the stream to trigger the hooks
await response.get_final_response()
# Non-streaming example
print("\n--- Non-streaming Example ---")
query = "What's the weather like in Seattle?"
@@ -199,18 +211,6 @@ async def main() -> None:
result = await agent.run(query)
print(f"Agent: {result}")
# Streaming example
print("\n--- Streaming Example ---")
query = "What's the weather like in Portland?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
response = agent.run(query, stream=True)
async for chunk in response:
if chunk.text:
print(chunk.text, end="", flush=True)
print("\n")
print(f"Final Result: {(await response.get_final_response()).text}")
if __name__ == "__main__":
asyncio.run(main())