Skip to content
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

correctly handle raised exception inside function calls #1057

Merged
merged 6 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/lazy-rabbits-confess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-agents": patch
---

handles error in function calls
4 changes: 3 additions & 1 deletion examples/voice-pipeline-agent/function_calling_weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ async def get_weather(
# response from the function call is returned to the LLM
return f"The weather in {location} is {weather_data}."
else:
raise f"Failed to get weather data, status code: {response.status}"
raise Exception(
f"Failed to get weather data, status code: {response.status}"
)


def prewarm_process(proc: JobProcess):
Expand Down
2 changes: 1 addition & 1 deletion livekit-agents/livekit/agents/pipeline/pipeline_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,7 @@ def _commit_user_question_if_needed() -> None:

for called_fnc in called_fncs:
# ignore the function calls that returns None
if called_fnc.result is None:
if called_fnc.result is None and called_fnc.exception is None:
continue

tool_calls_info.append(called_fnc.call_info)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,25 @@ async def test_basic_fnc_calls(llm_factory: Callable[[], llm.LLM]):
assert len(calls) == 2, "get_weather should be called twice"


@pytest.mark.parametrize("llm_factory", LLMS)
async def test_function_call_exception_handling(llm_factory: Callable[[], llm.LLM]):
input_llm = llm_factory()
fnc_ctx = FncCtx()

@fnc_ctx.ai_callable(description="Simulate a failure")
async def failing_function():
raise RuntimeError("Simulated failure")

stream = await _request_fnc_call(input_llm, "Call the failing function", fnc_ctx)
calls = stream.execute_functions()
await asyncio.gather(*[f.task for f in calls], return_exceptions=True)
await stream.aclose()

assert len(calls) == 1
assert isinstance(calls[0].exception, RuntimeError)
assert str(calls[0].exception) == "Simulated failure"


@pytest.mark.parametrize("llm_factory", LLMS)
async def test_runtime_addition(llm_factory: Callable[[], llm.LLM]):
input_llm = llm_factory()
Expand Down
Loading