|
2 | 2 | from pydantic import BaseModel
|
3 | 3 | from dspy.primitives.tool import Tool
|
4 | 4 | from typing import Any, Optional
|
| 5 | +import asyncio |
5 | 6 |
|
6 | 7 |
|
7 | 8 | # Test fixtures
|
@@ -67,6 +68,52 @@ def complex_dummy_function(profile: UserProfile, priority: int, notes: Optional[
|
67 | 68 | }
|
68 | 69 |
|
69 | 70 |
|
| 71 | +async def async_dummy_function(x: int, y: str = "hello") -> str: |
| 72 | + """An async dummy function for testing. |
| 73 | +
|
| 74 | + Args: |
| 75 | + x: An integer parameter |
| 76 | + y: A string parameter |
| 77 | + """ |
| 78 | + await asyncio.sleep(0.1) # Simulate some async work |
| 79 | + return f"{y} {x}" |
| 80 | + |
| 81 | + |
| 82 | +async def async_dummy_with_pydantic(model: DummyModel) -> str: |
| 83 | + """An async dummy function that accepts a Pydantic model.""" |
| 84 | + await asyncio.sleep(0.1) # Simulate some async work |
| 85 | + return f"{model.field1} {model.field2}" |
| 86 | + |
| 87 | + |
| 88 | +async def async_complex_dummy_function( |
| 89 | + profile: UserProfile, priority: int, notes: Optional[str] = None |
| 90 | +) -> dict[str, Any]: |
| 91 | + """Process user profile with complex nested structure asynchronously. |
| 92 | +
|
| 93 | + Args: |
| 94 | + profile: User profile containing nested contact and address information |
| 95 | + priority: Priority level of the processing |
| 96 | + notes: Optional processing notes |
| 97 | + """ |
| 98 | + # Simulate some async processing work |
| 99 | + await asyncio.sleep(0.1) |
| 100 | + |
| 101 | + primary_address = next( |
| 102 | + (addr for addr in profile.contact.addresses if addr.is_primary), profile.contact.addresses[0] |
| 103 | + ) |
| 104 | + |
| 105 | + # Simulate more async work after finding primary address |
| 106 | + await asyncio.sleep(0.1) |
| 107 | + |
| 108 | + return { |
| 109 | + "user_id": profile.user_id, |
| 110 | + "name": profile.name, |
| 111 | + "priority": priority, |
| 112 | + "primary_address": primary_address.model_dump(), |
| 113 | + "notes": notes, |
| 114 | + } |
| 115 | + |
| 116 | + |
70 | 117 | def test_basic_initialization():
|
71 | 118 | tool = Tool(name="test_tool", desc="A test tool", args={"param1": {"type": "string"}}, func=lambda x: x)
|
72 | 119 | assert tool.name == "test_tool"
|
@@ -198,7 +245,107 @@ def dummy_function(x: list[list[DummyModel]]):
|
198 | 245 | def test_tool_call_kwarg():
|
199 | 246 | def fn(x: int, **kwargs):
|
200 | 247 | return kwargs
|
| 248 | + |
201 | 249 | tool = Tool(fn)
|
202 | 250 |
|
203 | 251 | assert tool(x=1, y=2, z=3) == {"y": 2, "z": 3}
|
204 | 252 |
|
| 253 | + |
| 254 | +@pytest.mark.asyncio |
| 255 | +async def test_async_tool_from_function(): |
| 256 | + tool = Tool(async_dummy_function) |
| 257 | + |
| 258 | + assert tool.name == "async_dummy_function" |
| 259 | + assert "An async dummy function for testing" in tool.desc |
| 260 | + assert "x" in tool.args |
| 261 | + assert "y" in tool.args |
| 262 | + assert tool.args["x"]["type"] == "integer" |
| 263 | + assert tool.args["y"]["type"] == "string" |
| 264 | + assert tool.args["y"]["default"] == "hello" |
| 265 | + |
| 266 | + # Test async call |
| 267 | + result = await tool.acall(x=42, y="hello") |
| 268 | + assert result == "hello 42" |
| 269 | + |
| 270 | + |
| 271 | +@pytest.mark.asyncio |
| 272 | +async def test_async_tool_with_pydantic(): |
| 273 | + tool = Tool(async_dummy_with_pydantic) |
| 274 | + |
| 275 | + assert tool.name == "async_dummy_with_pydantic" |
| 276 | + assert "model" in tool.args |
| 277 | + assert tool.args["model"]["type"] == "object" |
| 278 | + assert "field1" in tool.args["model"]["properties"] |
| 279 | + assert "field2" in tool.args["model"]["properties"] |
| 280 | + |
| 281 | + # Test async call with pydantic model |
| 282 | + model = DummyModel(field1="test", field2=123) |
| 283 | + result = await tool.acall(model=model) |
| 284 | + assert result == "test 123" |
| 285 | + |
| 286 | + # Test async call with dict |
| 287 | + result = await tool.acall(model={"field1": "test", "field2": 123}) |
| 288 | + assert result == "test 123" |
| 289 | + |
| 290 | + |
| 291 | +@pytest.mark.asyncio |
| 292 | +async def test_async_tool_with_complex_pydantic(): |
| 293 | + tool = Tool(async_complex_dummy_function) |
| 294 | + |
| 295 | + profile = UserProfile( |
| 296 | + user_id=1, |
| 297 | + name="Test User", |
| 298 | + contact=ContactInfo( |
| 299 | + |
| 300 | + addresses=[ |
| 301 | + Address(street="123 Main St", city="Test City", zip_code="12345", is_primary=True), |
| 302 | + Address(street="456 Side St", city="Test City", zip_code="12345"), |
| 303 | + ], |
| 304 | + ), |
| 305 | + ) |
| 306 | + |
| 307 | + result = await tool.acall(profile=profile, priority=1, notes="Test note") |
| 308 | + assert result["user_id"] == 1 |
| 309 | + assert result["name"] == "Test User" |
| 310 | + assert result["priority"] == 1 |
| 311 | + assert result["notes"] == "Test note" |
| 312 | + assert result["primary_address"]["street"] == "123 Main St" |
| 313 | + |
| 314 | + |
| 315 | +@pytest.mark.asyncio |
| 316 | +async def test_async_tool_invalid_call(): |
| 317 | + tool = Tool(async_dummy_function) |
| 318 | + with pytest.raises(ValueError): |
| 319 | + await tool.acall(x="not an integer", y="hello") |
| 320 | + |
| 321 | + |
| 322 | +@pytest.mark.asyncio |
| 323 | +async def test_async_tool_with_kwargs(): |
| 324 | + async def fn(x: int, **kwargs): |
| 325 | + return kwargs |
| 326 | + |
| 327 | + tool = Tool(fn) |
| 328 | + |
| 329 | + result = await tool.acall(x=1, y=2, z=3) |
| 330 | + assert result == {"y": 2, "z": 3} |
| 331 | + |
| 332 | + |
| 333 | +@pytest.mark.asyncio |
| 334 | +async def test_async_concurrent_calls(): |
| 335 | + """Test that multiple async tools can run concurrently.""" |
| 336 | + tool = Tool(async_dummy_function) |
| 337 | + |
| 338 | + # Create multiple concurrent calls |
| 339 | + tasks = [tool.acall(x=i, y=f"hello{i}") for i in range(5)] |
| 340 | + |
| 341 | + # Run them concurrently and measure time |
| 342 | + start_time = asyncio.get_event_loop().time() |
| 343 | + results = await asyncio.gather(*tasks) |
| 344 | + end_time = asyncio.get_event_loop().time() |
| 345 | + |
| 346 | + # Verify results, `asyncio.gather` returns results in the order of the tasks |
| 347 | + assert results == [f"hello{i} {i}" for i in range(5)] |
| 348 | + |
| 349 | + # Check that it ran concurrently (should take ~0.1s, not ~0.5s) |
| 350 | + # We use 0.3s as threshold to account for some overhead |
| 351 | + assert end_time - start_time < 0.3 |
0 commit comments