Skip to content

Copy context to new thread for sync tool calls #1576

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

tboser
Copy link

@tboser tboser commented Apr 24, 2025

Synchronous tools can be called when running an agent async - this is handled with the run_in_executor utility function. Small but useful change for people using contextvars - pass along contextvars to the new thread.

Comment on lines 35 to 38
loop = asyncio.get_running_loop()
ctx = contextvars.copy_context() # copy the current context to the new thread
func_call = partial(func, *args, **kwargs)
return await loop.run_in_executor(None, ctx.run, func_call)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to run this logic with anyio, they already do this underneath.

@Kludex
Copy link
Member

Kludex commented Apr 24, 2025

We also need a test that proves it solves the issue.

@tboser
Copy link
Author

tboser commented Apr 25, 2025

We also need a test that proves it solves the issue.

sure, added. thanks for being on top of this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants