Skip to content

Commit c250fc0

Browse files
authored
share thread context (#1146)
1 parent 28fea41 commit c250fc0

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

src/strands/_async.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Private async execution utilities."""
22

33
import asyncio
4+
import contextvars
45
from concurrent.futures import ThreadPoolExecutor
56
from typing import Awaitable, Callable, TypeVar
67

@@ -27,5 +28,6 @@ def execute() -> T:
2728
return asyncio.run(execute_async())
2829

2930
with ThreadPoolExecutor() as executor:
30-
future = executor.submit(execute)
31+
context = contextvars.copy_context()
32+
future = executor.submit(context.run, execute)
3133
return future.result()

tests_integ/tools/__init__.py

Whitespace-only changes.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import contextvars
2+
3+
import pytest
4+
5+
from strands import Agent, tool
6+
7+
8+
@pytest.fixture
9+
def result():
10+
return {}
11+
12+
13+
@pytest.fixture
14+
def contextvar():
15+
return contextvars.ContextVar("agent")
16+
17+
18+
@pytest.fixture
19+
def context_tool(result, contextvar):
20+
@tool(name="context_tool")
21+
def tool_():
22+
result["context_value"] = contextvar.get("local_context")
23+
24+
return tool_
25+
26+
27+
@pytest.fixture
28+
def agent(context_tool):
29+
return Agent(tools=[context_tool])
30+
31+
32+
def test_agent_invoke_context_sharing(result, contextvar, agent):
33+
contextvar.set("shared_context")
34+
agent("Execute context_tool")
35+
36+
tru_context = result["context_value"]
37+
exp_context = contextvar.get()
38+
assert tru_context == exp_context
39+
40+
41+
def test_tool_call_context_sharing(result, contextvar, agent):
42+
contextvar.set("shared_context")
43+
agent.tool.context_tool()
44+
45+
tru_context = result["context_value"]
46+
exp_context = contextvar.get()
47+
assert tru_context == exp_context

0 commit comments

Comments
 (0)