test_basetool_context_integration.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """Integration test for BaseTool context support."""
  2. import pytest
  3. from pydantic import Field
  4. from agency_swarm import Agency, Agent, BaseTool
  5. @pytest.mark.asyncio
  6. async def test_basetool_context_integration():
  7. """Test that BaseTools can access agency context."""
  8. class ContextReaderTool(BaseTool):
  9. """A tool that reads from context."""
  10. key: str = Field(..., description="Key to read from context")
  11. def run(self):
  12. if self.context is not None:
  13. value = self.context.get(self.key, "not_found")
  14. return f"Context value for {self.key}: {value}"
  15. else:
  16. return "No context available"
  17. # Create agent with context reader tool
  18. agent = Agent(
  19. name="ContextAgent",
  20. instructions="You read data from context using the ContextReaderTool.",
  21. tools=[ContextReaderTool],
  22. model="gpt-5.4-mini",
  23. )
  24. # Create agency with initial context
  25. agency = Agency(
  26. agent,
  27. user_context={"test_key": "test_value", "another_key": "another_value"},
  28. )
  29. # Test reading from context
  30. response = await agency.get_response("Read the value of test_key using ContextReaderTool", recipient_agent=agent)
  31. # Check that the tool was called and returned the correct value
  32. tool_outputs = [item.output for item in response.new_items if hasattr(item, "output")]
  33. assert any("Context value for test_key: test_value" in str(output) for output in tool_outputs)
  34. @pytest.mark.asyncio
  35. async def test_basetool_async_context():
  36. """Test that async BaseTools also receive context."""
  37. class AsyncContextTool(BaseTool):
  38. """An async tool that uses context."""
  39. data: str = Field(..., description="Data to process")
  40. async def run(self):
  41. if self.context is not None:
  42. ctx_data = self.context.get("async_key", "default")
  43. return f"Async processed: {self.data} with context: {ctx_data}"
  44. else:
  45. return f"Async processed: {self.data} without context"
  46. agent = Agent(
  47. name="AsyncAgent",
  48. instructions="You process data asynchronously.",
  49. tools=[AsyncContextTool],
  50. model="gpt-5.4-mini",
  51. )
  52. agency = Agency(
  53. agent,
  54. user_context={"async_key": "async_value"},
  55. )
  56. response = await agency.get_response("Process 'test_data' using AsyncContextTool")
  57. # Check that the tool was called with context
  58. tool_outputs = [item.output for item in response.new_items if hasattr(item, "output")]
  59. assert any("Async processed: test_data with context: async_value" in str(output) for output in tool_outputs)