Skip to content

Commit 3daf2df

Browse files
committed
Match exact working sample pattern from SSH test
1 parent 562a748 commit 3daf2df

1 file changed

Lines changed: 26 additions & 44 deletions

File tree

main.py

Lines changed: 26 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ async def chat_with_agent(self, message: str) -> ChatResponse:
218218

219219
# Create a fresh client for each request to avoid transport issues
220220
try:
221-
# Create fresh agents client for this request
221+
# Create fresh agents client for this request (exactly like working sample)
222222
fresh_client = AgentsClient(
223223
endpoint=PROJECT_ENDPOINT,
224224
credential=DefaultAzureCredential()
@@ -232,65 +232,49 @@ async def chat_with_agent(self, message: str) -> ChatResponse:
232232

233233
# Default instructions for MCP-enabled agent
234234
instructions = """
235-
You are a helpful agent with access to to-do management tools via MCP.
236-
You can help users create, list, update, and delete to-do items using the available MCP tools.
237-
When users ask about to-dos, use the MCP tools to perform the requested actions.
238-
Always be helpful and provide clear feedback about what actions you've taken.
239-
"""
235+
You are a helpful agent that can use MCP tools to assist users.
236+
Use the available MCP tools to answer questions and perform tasks."""
240237

241238
with fresh_client:
242-
# Create agent with MCP tool definitions
239+
# Create agent with MCP tool definitions (exactly like working sample)
243240
agent = fresh_client.create_agent(
244241
model=MODEL_DEPLOYMENT,
245-
name="todo-mcp-agent",
242+
name="my-mcp-agent",
246243
instructions=instructions,
247244
tools=mcp_tool.definitions,
248245
)
249246
logger.info(f"Created agent with MCP tools, ID: {agent.id}")
247+
logger.info(f"MCP Server: {mcp_tool.server_label} at {mcp_tool.server_url}")
250248

251-
# Create thread for communication
249+
# Create thread for communication (exactly like working sample)
252250
thread = fresh_client.threads.create()
253251
logger.info(f"Created thread, ID: {thread.id}")
254252

255-
# Create message on the thread
253+
# Create message on the thread (exactly like working sample)
256254
message_obj = fresh_client.messages.create(
257255
thread_id=thread.id,
258256
role="user",
259257
content=message,
260258
)
261259
logger.info(f"Created message, ID: {message_obj.id}")
262260

263-
# Set MCP tool approval mode
261+
# Set MCP tool approval mode (exactly like working sample)
264262
mcp_tool.set_approval_mode("never")
265263

266-
# Create and process agent run with MCP tools
264+
# Create and process agent run with MCP tools (exactly like working sample)
267265
run = fresh_client.runs.create_and_process(
268266
thread_id=thread.id,
269267
agent_id=agent.id,
270268
tool_resources=mcp_tool.resources
271269
)
272270
logger.info(f"Created run, ID: {run.id}, Status: {run.status}")
273271

274-
# Log detailed run information for debugging
275-
logger.info(f"Run object type: {type(run)}")
276-
logger.info(f"Run object attributes: {dir(run)}")
277-
if hasattr(run, '__dict__'):
278-
logger.info(f"Run object dict: {run.__dict__}")
279-
if hasattr(run, 'last_error'):
280-
logger.info(f"Run last_error: {run.last_error}")
281-
if hasattr(run, 'required_action'):
282-
logger.info(f"Run required_action: {run.required_action}")
283-
284-
# Check run status (detailed debugging like sample script)
272+
# Check run status (exactly like working sample)
285273
logger.info(f"Run completed with status: {run.status}")
286-
if hasattr(run, 'last_error') and run.last_error:
287-
logger.error(f"Run failed: {run.last_error}")
288-
assistant_response = f"Run failed: {run.last_error}"
289-
elif "failed" in str(run.status).lower():
290-
logger.error(f"Run failed with status: {run.status}")
291-
assistant_response = f"Run failed with status: {run.status}"
274+
if run.status == "failed":
275+
logger.error(f"Run failed: {getattr(run, 'last_error', 'Unknown error')}")
292276

293-
# Display run steps and tool calls (like sample script)
277+
# Display run steps and tool calls (exactly like working sample)
294278
try:
295279
run_steps = fresh_client.run_steps.list(thread_id=thread.id, run_id=run.id)
296280
for step in run_steps:
@@ -303,24 +287,22 @@ async def chat_with_agent(self, message: str) -> ChatResponse:
303287
if tool_calls:
304288
logger.info(" MCP Tool calls:")
305289
for call in tool_calls:
306-
logger.info(f" Tool Call ID: {call.get('id', 'N/A')}")
307-
logger.info(f" Type: {call.get('type', 'N/A')}")
308-
logger.info(f" Name: {call.get('name', 'N/A')}")
290+
logger.info(f" Tool Call ID: {call.get('id')}")
291+
logger.info(f" Type: {call.get('type')}")
292+
logger.info(f" Name: {call.get('name')}")
309293
except Exception as e:
310294
logger.error(f"Error retrieving run steps: {e}")
311295

312296
if "completed" in str(run.status).lower():
313-
# Get the response
314-
messages_paged = fresh_client.messages.list(thread_id=thread.id)
315-
messages = list(messages_paged) # Convert ItemPaged to list
316-
logger.info(f"Retrieved {len(messages)} messages from thread")
317-
318-
# Log all messages for debugging
319-
for i, msg in enumerate(messages):
320-
logger.info(f"Message {i}: role={msg.role}, has_text={bool(msg.text_messages)}")
297+
# Fetch and log all messages (exactly like working sample)
298+
messages = fresh_client.messages.list(thread_id=thread.id)
299+
logger.info("Conversation:")
300+
logger.info("-" * 50)
301+
for msg in messages:
321302
if msg.text_messages:
322-
for j, text_msg in enumerate(msg.text_messages):
323-
logger.info(f" Text {j}: {text_msg.text.value[:100]}...")
303+
last_text = msg.text_messages[-1]
304+
logger.info(f"{msg.role.upper()}: {last_text.text.value}")
305+
logger.info("-" * 50)
324306

325307
# Extract the assistant's response (get the last assistant message)
326308
assistant_response = "No response generated"
@@ -334,7 +316,7 @@ async def chat_with_agent(self, message: str) -> ChatResponse:
334316
logger.warning(f"Run completed with unexpected status: {run.status}")
335317
assistant_response = f"Run completed with status: {run.status}"
336318

337-
# Clean up - delete the agent
319+
# Clean up - delete the agent (exactly like working sample)
338320
fresh_client.delete_agent(agent.id)
339321
logger.info("Deleted agent")
340322

0 commit comments

Comments
 (0)