Everett Kleven
08/28/2025, 5:01 PMKevin Wang
08/28/2025, 5:31 PMEverett Kleven
08/28/2025, 5:35 PMEverett Kleven
08/28/2025, 5:36 PMKevin Wang
08/28/2025, 5:36 PMKevin Wang
08/28/2025, 5:39 PM@daft.udf because it's kind of a roundabout way of describing rate limits. what users probably want to express are some combination of
• number of UDF calls to make per second/minute/hour/etc in total
• number of UDF calls to make per second/minute/hour/etc per machine/IP
• in special cases, some mechanism to dynamically tell Daft to throttle requests
What are your thoughts on this?Kevin Wang
08/28/2025, 5:47 PMI’m also getting a pickle error when I specify concurrency on my batch variant of the same workloadCould you share more about this error and the code you are trying to run?
Everett Kleven
08/28/2025, 5:50 PM@daft.udf(return_dtype=daft.DataType.string(), concurrency=8)
def struct_output_batch(
model_id: str,
text_col: daft.Series,
image_col: daft.Series,
extra_body: dict | None = None
) -> list[str]:
async def generate(model_id: str, text: str, image: str) -> str:
result = await client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": text},
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{image}"},
},
],
}
],
model=model_id,
extra_body={"guided_choice": ["A", "B", "C", "D"]},
)
return result.choices[0].message.content
texts = text_col.to_pylist()
images = image_col.to_pylist()
async def gather_completions() -> list[str]:
tasks = [generate(model_id, t,i) for t,i in zip(texts,images) ]
return await asyncio.gather(*tasks)
return asyncio.run(gather_completions())Everett Kleven
08/28/2025, 5:50 PMEverett Kleven
08/28/2025, 5:51 PMEverett Kleven
08/28/2025, 5:51 PMERROR:daft_local_execution:Error when running pipeline node UDF struct_output_batch
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/tmp/ipython-input-1876801372.py in <cell line: 0>()
42 image_col = df["image_base64"],
43 extra_body={"guided_choice": ["A", "B", "C", "D"]}
---> 44 )).collect()
45 collect = time.time()
46 print(f"Collect time: {collect-start} seconds")
5 frames
/usr/local/lib/python3.12/dist-packages/daft/execution/udf.py in __init__(self, project_expr, passthrough_exprs)
84 [Expression._from_pyexpr(expr) for expr in passthrough_exprs] + [Expression._from_pyexpr(project_expr)]
85 )
---> 86 expr_projection_bytes = pickle.dumps(expr_projection)
87 self.handle_conn.send((_ENTER, expr_projection_bytes))
88 response = self.handle_conn.recv()
RuntimeError: Failed to serialize: TypeError: cannot pickle '_thread.RLock' objectSrinivas Lade
08/28/2025, 5:56 PMclient outside of the UDF, as a global var?Everett Kleven
08/28/2025, 5:58 PM# instantiating a new client inside the funciton..... (this is crazy)
@daft.func(return_dtype=daft.DataType.string())
async def struct_output_rowwise(model_id: str, text: str, image: str) -> str:
from openai import AsyncOpenAI
api_key = "none"
base_url = "http://0.0.0.0:8000/v1"
client = AsyncOpenAI(api_key=api_key, base_url=base_url)
result = await client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": text},
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{image}"},
},
],
}
],
model=model_id,
extra_body={"guided_choice": ["A", "B", "C", "D"]},
)
return result.choices[0].message.contentEverett Kleven
08/28/2025, 5:58 PMRuntimeError: no running event loop
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.12/dist-packages/httpx/_client.py", line 1985, in aclose
await self._transport.aclose()
File "/usr/local/lib/python3.12/dist-packages/httpx/_transports/default.py", line 406, in aclose
await self._pool.aclose()
File "/usr/local/lib/python3.12/dist-packages/httpcore/_async/connection_pool.py", line 353, in aclose
await self._close_connections(closing_connections)
File "/usr/local/lib/python3.12/dist-packages/httpcore/_async/connection_pool.py", line 345, in _close_connections
await connection.aclose()
File "/usr/local/lib/python3.12/dist-packages/httpcore/_async/connection.py", line 173, in aclose
await self._connection.aclose()
File "/usr/local/lib/python3.12/dist-packages/httpcore/_async/http11.py", line 258, in aclose
await self._network_stream.aclose()
File "/usr/local/lib/python3.12/dist-packages/httpcore/_backends/anyio.py", line 53, in aclose
await self._stream.aclose()
File "/usr/local/lib/python3.12/dist-packages/anyio/_backends/_asyncio.py", line 1314, in aclose
self._transport.close()
File "/usr/lib/python3.12/asyncio/selector_events.py", line 1213, in close
super().close()
File "/usr/lib/python3.12/asyncio/selector_events.py", line 875, in close
self._loop.call_soon(self._call_connection_lost, None)
File "/usr/lib/python3.12/asyncio/base_events.py", line 799, in call_soon
self._check_closed()
File "/usr/lib/python3.12/asyncio/base_events.py", line 545, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-2115' coro=<AsyncClient.aclose() done, defined at /usr/local/lib/python3.12/dist-packages/httpx/_client.py:1978> exception=RuntimeError('Event loop is closed')>
Traceback (most recent call last):
File "/usr/local/lib/python3.12/dist-packages/daft/udf/row_wise.py", line 90, in __call_async_batch
event_loop = asyncio.get_running_loop()
^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loopEverett Kleven
08/28/2025, 6:00 PMEverett Kleven
08/28/2025, 6:00 PMasync def ... I'm trying the sync client now.Everett Kleven
08/28/2025, 6:05 PMSrinivas Lade
08/28/2025, 6:05 PMYeah totally agree, we're working on designing a new way to instantiate thisCopy code# instantiating a new client inside the funciton..... (this is crazy)
Everett Kleven
08/28/2025, 6:06 PMSrinivas Lade
08/28/2025, 6:16 PMdaft.func types. But absolutely, that would be best for now.
Alternatively, could you also try moving the AsyncOpenAI(api_key=api_key, base_url=base_url) outside the UDF?Everett Kleven
08/28/2025, 6:20 PMfrom openai import OpenAI
api_key = "none"
base_url = "http://0.0.0.0:8000/v1"
client = OpenAI(api_key=api_key, base_url=base_url)
@daft.func(return_dtype=daft.DataType.string())
async def struct_output_rowwise(model_id: str, text: str, image: str) -> str:
result = await client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": text},
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{image}"},
},
],
}
],
model=model_id,
extra_body={"guided_choice": ["A", "B", "C", "D"]},
)
return result.choices[0].message.content
# Lets try 1000 rows
start = time.time()
df_result_rowwise = df.limit(1000).with_column("result", struct_output_rowwise(
model_id,
df["user"],
df["image_base64"]
)).collect()
collect = time.time()
print(f"Collect time: {collect-start} seconds")
but I get an error after the job finishes. Its the same error, which turns out to be more distracting than anythingSrinivas Lade
08/28/2025, 6:21 PMTraceback (most recent call last):
File "/usr/local/lib/python3.12/dist-packages/daft/udf/row_wise.py", line 90, in __call_async_batch
event_loop = asyncio.get_running_loop()
^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loopEverett Kleven
08/28/2025, 6:21 PMEverett Kleven
08/28/2025, 6:21 PMSrinivas Lade
08/28/2025, 6:26 PMEverett Kleven
08/28/2025, 6:27 PMCory Grinstead
08/28/2025, 7:52 PMtry:
event_loop = asyncio.get_running_loop() # <---- here
outputs = asyncio.run_coroutine_threadsafe(run_tasks(), event_loop).result()
except RuntimeError:
outputs = asyncio.run(run_tasks())
We're catching the RuntimeError's so i'm not entirely sure how that error ever gets surfaced 🤔Everett Kleven
08/28/2025, 9:04 PMCory Grinstead
08/28/2025, 11:17 PMZhiping Wu
08/29/2025, 2:19 AMclass CustomUDF:
def __init__(self) -> None:
self._local = threading.local()
def _get_event_loop(self) -> asyncio.AbstractEventLoop:
"""Get or create the event loop of current thread."""
if not hasattr(self._local, "loop"):
self._local.loop = asyncio.new_event_loop()
return self._local.loop
async def async_run(self, a: list[str]) -> list[str]:
pass
def __call__(self, a: Series) -> Series:
loop = self._get_event_loop()
if loop.is_running():
future = asyncio.run_coroutine_threadsafe(self.async_run(a.to_pylist()), loop)
results = future.result()
else:
results = loop.run_until_complete(self.async_run(a.to_pylist()))
passEverett Kleven
08/29/2025, 7:09 PMEverett Kleven
08/29/2025, 8:23 PMKevin Wang
08/29/2025, 8:55 PM