-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathtest_fmapi_tool_calling.py
More file actions
335 lines (261 loc) · 12.1 KB
/
test_fmapi_tool_calling.py
File metadata and controls
335 lines (261 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
"""
End-to-end FMAPI tool calling tests for ChatDatabricks via LangGraph.
Prerequisites:
- FMAPI endpoints must be available on the test workspace
"""
from __future__ import annotations
import os
import pytest
from databricks_ai_bridge.test_utils.fmapi import (
SKIP_CHAT_COMPLETIONS_LANGCHAIN,
SKIP_RESPONSES_API,
async_retry,
discover_chat_models,
discover_responses_models,
max_tokens_for_model,
retry,
)
from langchain_core.messages import AIMessage, AIMessageChunk, ToolMessage
from langchain_core.tools import tool
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
from databricks_langchain import ChatDatabricks
pytestmark = pytest.mark.skipif(
os.environ.get("RUN_FMAPI_TOOL_CALLING_TESTS") != "1",
reason="FMAPI tool calling tests disabled. Set RUN_FMAPI_TOOL_CALLING_TESTS=1 to enable.",
)
_CHAT_MODELS = discover_chat_models(SKIP_CHAT_COMPLETIONS_LANGCHAIN)
_RESPONSES_MODELS = discover_responses_models(SKIP_RESPONSES_API)
@tool
def add(a: int, b: int) -> int:
"""Add two integers.
Args:
a: First integer
b: Second integer
"""
return a + b
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers.
Args:
a: First integer
b: Second integer
"""
return a * b
# =============================================================================
# Sync LangGraph Agent
# =============================================================================
@pytest.mark.integration
@pytest.mark.parametrize("model", _CHAT_MODELS)
class TestLangGraphSync:
"""Sync LangGraph agent tests using ChatDatabricks + create_react_agent."""
def test_single_turn(self, model):
"""Single-turn: agent calls tools and produces a final answer."""
def _run():
llm = ChatDatabricks(model=model, max_tokens=max_tokens_for_model(model))
agent = create_react_agent(llm, [add, multiply])
response = agent.invoke(
{
"messages": [
(
"human",
"Use the add tool to compute 10 + 5, then use the multiply tool "
"to multiply the result by 3. You MUST use the tools.",
)
]
}
)
last_message = response["messages"][-1]
assert isinstance(last_message, AIMessage)
assert "45" in last_message.content
tool_messages = [m for m in response["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) > 0, "Expected tool calls in conversation history"
retry(_run)
def test_multi_turn(self, model):
"""Multi-turn: agent maintains conversation context across turns."""
def _run():
llm = ChatDatabricks(model=model, max_tokens=max_tokens_for_model(model))
agent = create_react_agent(llm, [add, multiply], checkpointer=MemorySaver())
config = {"configurable": {"thread_id": f"test-sync-multi-turn-{model}"}}
response = agent.invoke({"messages": [("human", "What is 10 + 5?")]}, config=config)
last_message = response["messages"][-1]
assert isinstance(last_message, AIMessage)
assert "15" in last_message.content
response = agent.invoke({"messages": [("human", "Multiply that by 3")]}, config=config)
last_message = response["messages"][-1]
assert isinstance(last_message, AIMessage)
assert "45" in last_message.content
retry(_run)
def test_streaming(self, model):
"""Streaming: agent streams node updates and tool execution events."""
def _run():
llm = ChatDatabricks(model=model, max_tokens=max_tokens_for_model(model))
agent = create_react_agent(llm, [add, multiply])
events = list(
agent.stream(
{
"messages": [
(
"human",
"Use the add tool to compute 10 + 5, then use the multiply tool "
"to multiply the result by 3. You MUST use the tools.",
)
]
},
stream_mode="updates",
)
)
assert len(events) > 0, "No stream events received"
nodes_seen = set()
for event in events:
nodes_seen.update(event.keys())
assert "agent" in nodes_seen, f"Expected 'agent' node, got: {nodes_seen}"
assert "tools" in nodes_seen, f"Expected 'tools' node, got: {nodes_seen}"
last_event = events[-1]
last_messages = list(last_event.values())[0]["messages"]
assert any("45" in str(m.content) for m in last_messages)
retry(_run)
# =============================================================================
# Async LangGraph Agent
# =============================================================================
@pytest.mark.integration
@pytest.mark.asyncio
@pytest.mark.parametrize("model", _CHAT_MODELS)
class TestLangGraphAsync:
"""Async LangGraph agent tests using ChatDatabricks + create_react_agent."""
async def test_single_turn(self, model):
"""Single-turn via ainvoke."""
async def _run():
llm = ChatDatabricks(model=model, max_tokens=max_tokens_for_model(model))
agent = create_react_agent(llm, [add, multiply])
response = await agent.ainvoke(
{
"messages": [
(
"human",
"Use the add tool to compute 10 + 5, then use the multiply tool "
"to multiply the result by 3. You MUST use the tools.",
)
]
}
)
last_message = response["messages"][-1]
assert isinstance(last_message, AIMessage)
assert "45" in last_message.content
tool_messages = [m for m in response["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) > 0, "Expected tool calls in conversation history"
await async_retry(_run)
async def test_multi_turn(self, model):
"""Multi-turn via ainvoke with MemorySaver checkpointer."""
async def _run():
llm = ChatDatabricks(model=model, max_tokens=max_tokens_for_model(model))
agent = create_react_agent(llm, [add, multiply], checkpointer=MemorySaver())
config = {"configurable": {"thread_id": f"test-async-multi-turn-{model}"}}
response = await agent.ainvoke(
{"messages": [("human", "What is 10 + 5?")]}, config=config
)
last_message = response["messages"][-1]
assert isinstance(last_message, AIMessage)
assert "15" in last_message.content
response = await agent.ainvoke(
{"messages": [("human", "Multiply that by 3")]}, config=config
)
last_message = response["messages"][-1]
assert isinstance(last_message, AIMessage)
assert "45" in last_message.content
await async_retry(_run)
async def test_streaming(self, model):
"""Streaming via astream with updates + messages stream modes."""
async def _run():
llm = ChatDatabricks(model=model, max_tokens=max_tokens_for_model(model))
agent = create_react_agent(llm, [add, multiply])
nodes_seen = set()
got_message_chunks = False
event_count = 0
async for event in agent.astream(
{
"messages": [
(
"human",
"Use the add tool to compute 10 + 5, then use the multiply tool "
"to multiply the result by 3. You MUST use the tools.",
)
]
},
stream_mode=["updates", "messages"],
):
event_count += 1
mode, data = event
if mode == "updates":
nodes_seen.update(data.keys())
elif mode == "messages":
chunk, _metadata = data
if isinstance(chunk, AIMessageChunk):
got_message_chunks = True
assert event_count > 0, "No stream events received"
assert "agent" in nodes_seen, f"Expected 'agent' node, got: {nodes_seen}"
assert "tools" in nodes_seen, f"Expected 'tools' node, got: {nodes_seen}"
assert got_message_chunks, "Expected AIMessageChunk tokens in message stream"
await async_retry(_run)
# =============================================================================
# Responses API — LangGraph (GPT models including codex)
# =============================================================================
@pytest.mark.integration
@pytest.mark.parametrize("model", _RESPONSES_MODELS)
class TestLangGraphResponsesAPI:
"""LangGraph agent tests using ChatDatabricks(use_responses_api=True).
Tests GPT models (including codex which only supports Responses API).
"""
def test_single_turn(self, model):
"""Single-turn: agent calls tools and produces a final answer via Responses API."""
llm = ChatDatabricks(model=model, use_responses_api=True)
agent = create_react_agent(llm, [add, multiply])
def _run():
response = agent.invoke({"messages": [("human", "Use the add tool to compute 10 + 5")]})
tool_msgs = [m for m in response["messages"] if isinstance(m, ToolMessage)]
assert len(tool_msgs) >= 1, "Agent should have called at least one tool"
last = response["messages"][-1]
assert isinstance(last, AIMessage)
retry(_run)
def test_multi_turn(self, model):
"""Multi-turn: agent maintains context across turns via Responses API."""
llm = ChatDatabricks(model=model, use_responses_api=True)
checkpointer = MemorySaver()
agent = create_react_agent(llm, [add, multiply], checkpointer=checkpointer)
config = {"configurable": {"thread_id": "responses-api-test"}}
def _run():
r1 = agent.invoke(
{"messages": [("human", "Use the add tool to compute 10 + 5")]}, config=config
)
tool_msgs_1 = [m for m in r1["messages"] if isinstance(m, ToolMessage)]
assert len(tool_msgs_1) >= 1
r2 = agent.invoke(
{"messages": [("human", "Now multiply the result by 3")]}, config=config
)
assert len(r2["messages"]) > len(r1["messages"]), "History should grow across turns"
retry(_run)
def test_streaming(self, model):
"""Streaming: agent streams node updates and tool events via Responses API."""
llm = ChatDatabricks(model=model, use_responses_api=True)
agent = create_react_agent(llm, [add, multiply])
def _run():
event_count = 0
nodes_seen = set()
got_message_chunks = False
for event in agent.stream(
{"messages": [("human", "Use the add tool to compute 10 + 5")]},
stream_mode=["updates", "messages"],
):
event_count += 1
mode, data = event
if mode == "updates":
nodes_seen.update(data.keys())
elif mode == "messages":
chunk, _metadata = data
if isinstance(chunk, AIMessageChunk):
got_message_chunks = True
assert event_count > 0, "No stream events received"
assert "agent" in nodes_seen, f"Expected 'agent' node, got: {nodes_seen}"
assert "tools" in nodes_seen, f"Expected 'tools' node, got: {nodes_seen}"
assert got_message_chunks, "Expected AIMessageChunk tokens in message stream"
retry(_run)