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
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions pydantic_ai_slim/pydantic_ai/_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations as _annotations

import asyncio
import contextvars
import time
import uuid
from collections.abc import AsyncIterable, AsyncIterator, Iterator
Expand Down Expand Up @@ -31,11 +32,10 @@


async def run_in_executor(func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R:
if kwargs:
# noinspection PyTypeChecker
return await asyncio.get_running_loop().run_in_executor(None, partial(func, *args, **kwargs))
else:
return await asyncio.get_running_loop().run_in_executor(None, func, *args) # type: ignore
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.



def is_model_like(type_: Any) -> bool:
Expand Down