Skip to content

Commit

Permalink
make sure context is always carried (Chainlit#552)
Browse files Browse the repository at this point in the history
  • Loading branch information
willydouhard authored Nov 17, 2023
1 parent d30eed2 commit a4548d1
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
2 changes: 1 addition & 1 deletion backend/chainlit/langchain/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ def __init__(
self.to_keep = to_keep

def _run_sync(self, co):
asyncio.run_coroutine_threadsafe(co, loop=self.context.loop)
self.context.loop.create_task(co)

def _persist_run(self, run: Run) -> None:
pass
Expand Down
18 changes: 15 additions & 3 deletions backend/chainlit/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
import threading

from asyncer import asyncify
from chainlit.context import context_var
from syncer import sync
from chainlit.context import context

make_async = asyncify

Expand All @@ -22,9 +22,21 @@

def run_sync(co: Coroutine[Any, Any, T_Retval]) -> T_Retval:
"""Run the coroutine synchronously."""

# Copy the current context
current_context = context_var.get()

# Define a wrapper coroutine that sets the context before running the original coroutine
async def context_preserving_coroutine():
# Set the copied context to the coroutine
context_var.set(current_context)
return await co

# Execute from the main thread in the main event loop
if threading.current_thread() == threading.main_thread():
return sync(co)
return sync(context_preserving_coroutine())
else: # Execute from a thread in the main event loop
result = asyncio.run_coroutine_threadsafe(co, loop=context.loop)
result = asyncio.run_coroutine_threadsafe(
context_preserving_coroutine(), loop=current_context.loop
)
return result.result()
2 changes: 1 addition & 1 deletion backend/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "chainlit"
version = "0.7.604rc0"
version = "0.7.604rc1"
keywords = ['LLM', 'Agents', 'gen ai', 'chat ui', 'chatbot ui', 'langchain']
description = "A faster way to build chatbot UIs."
authors = ["Chainlit"]
Expand Down

0 comments on commit a4548d1

Please sign in to comment.