Elffuss BraidHub

kikocis/llama-stack public

main · 18.6 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7import unittest
8from unittest import mock
9
10from llama_models.llama3.api.datatypes import (
11 BuiltinTool,
12 CompletionMessage,
13 SamplingParams,
14 SamplingStrategy,
15 StopReason,
16 ToolCall,
17 ToolChoice,
18 ToolDefinition,
19 ToolParamDefinition,
20 ToolResponseMessage,
21 UserMessage,
22)
23from llama_stack.apis.inference.inference import (
24 ChatCompletionRequest,
25 ChatCompletionResponseEventType,
26)
27from llama_stack.providers.adapters.inference.bedrock import get_adapter_impl
28from llama_stack.providers.adapters.inference.bedrock.config import BedrockConfig
29
30
31class BedrockInferenceTests(unittest.IsolatedAsyncioTestCase):
32
33 async def asyncSetUp(self):
34 bedrock_config = BedrockConfig()
35
36 # setup Bedrock
37 self.api = await get_adapter_impl(bedrock_config, {})
38 await self.api.initialize()
39
40 self.custom_tool_defn = ToolDefinition(
41 tool_name="get_boiling_point",
42 description="Get the boiling point of a imaginary liquids (eg. polyjuice)",
43 parameters={
44 "liquid_name": ToolParamDefinition(
45 param_type="str",
46 description="The name of the liquid",
47 required=True,
48 ),
49 "celcius": ToolParamDefinition(
50 param_type="boolean",
51 description="Whether to return the boiling point in Celcius",
52 required=False,
53 ),
54 },
55 )
56 self.valid_supported_model = "Meta-Llama3.1-8B-Instruct"
57
58 async def asyncTearDown(self):
59 await self.api.shutdown()
60
61 async def test_text(self):
62 with mock.patch.object(self.api.client, "converse") as mock_converse:
63 mock_converse.return_value = {
64 "ResponseMetadata": {
65 "RequestId": "8ad04352-cd81-4946-b811-b434e546385d",
66 "HTTPStatusCode": 200,
67 "HTTPHeaders": {},
68 "RetryAttempts": 0,
69 },
70 "output": {
71 "message": {
72 "role": "assistant",
73 "content": [{"text": "\n\nThe capital of France is Paris."}],
74 }
75 },
76 "stopReason": "end_turn",
77 "usage": {"inputTokens": 21, "outputTokens": 9, "totalTokens": 30},
78 "metrics": {"latencyMs": 307},
79 }
80 request = ChatCompletionRequest(
81 model=self.valid_supported_model,
82 messages=[
83 UserMessage(
84 content="What is the capital of France?",
85 ),
86 ],
87 stream=False,
88 )
89 iterator = self.api.chat_completion(
90 request.model,
91 request.messages,
92 request.sampling_params,
93 request.tools,
94 request.tool_choice,
95 request.tool_prompt_format,
96 request.stream,
97 request.logprobs,
98 )
99 async for r in iterator:
100 response = r
101 print(response.completion_message.content)
102 self.assertTrue("Paris" in response.completion_message.content[0])
103 self.assertEqual(
104 response.completion_message.stop_reason, StopReason.end_of_turn
105 )
106
107 async def test_tool_call(self):
108 with mock.patch.object(self.api.client, "converse") as mock_converse:
109 mock_converse.return_value = {
110 "ResponseMetadata": {
111 "RequestId": "ec9da6a4-656b-4343-9e1f-71dac79cbf53",
112 "HTTPStatusCode": 200,
113 "HTTPHeaders": {},
114 "RetryAttempts": 0,
115 },
116 "output": {
117 "message": {
118 "role": "assistant",
119 "content": [
120 {
121 "toolUse": {
122 "name": "brave_search",
123 "toolUseId": "tooluse_d49kUQ3rTc6K_LPM-w96MQ",
124 "input": {"query": "current US President"},
125 }
126 }
127 ],
128 }
129 },
130 "stopReason": "end_turn",
131 "usage": {"inputTokens": 48, "outputTokens": 81, "totalTokens": 129},
132 "metrics": {"latencyMs": 1236},
133 }
134 request = ChatCompletionRequest(
135 model=self.valid_supported_model,
136 messages=[
137 UserMessage(
138 content="Who is the current US President?",
139 ),
140 ],
141 stream=False,
142 tools=[ToolDefinition(tool_name=BuiltinTool.brave_search)],
143 )
144 iterator = self.api.chat_completion(
145 request.model,
146 request.messages,
147 request.sampling_params,
148 request.tools,
149 request.tool_choice,
150 request.tool_prompt_format,
151 request.stream,
152 request.logprobs,
153 )
154 async for r in iterator:
155 response = r
156
157 completion_message = response.completion_message
158
159 self.assertEqual(len(completion_message.content), 0)
160 self.assertEqual(completion_message.stop_reason, StopReason.end_of_turn)
161
162 self.assertEqual(
163 len(completion_message.tool_calls), 1, completion_message.tool_calls
164 )
165 self.assertEqual(
166 completion_message.tool_calls[0].tool_name, BuiltinTool.brave_search
167 )
168 self.assertTrue(
169 "president"
170 in completion_message.tool_calls[0].arguments["query"].lower()
171 )
172
173 async def test_custom_tool(self):
174 with mock.patch.object(self.api.client, "converse") as mock_converse:
175 mock_converse.return_value = {
176 "ResponseMetadata": {
177 "RequestId": "243c4316-0965-4b79-a145-2d9ac6b4e9ad",
178 "HTTPStatusCode": 200,
179 "HTTPHeaders": {},
180 "RetryAttempts": 0,
181 },
182 "output": {
183 "message": {
184 "role": "assistant",
185 "content": [
186 {
187 "toolUse": {
188 "toolUseId": "tooluse_7DViuqxXS6exL8Yug9Apjw",
189 "name": "get_boiling_point",
190 "input": {
191 "liquid_name": "polyjuice",
192 "celcius": "True",
193 },
194 }
195 }
196 ],
197 }
198 },
199 "stopReason": "tool_use",
200 "usage": {"inputTokens": 110, "outputTokens": 37, "totalTokens": 147},
201 "metrics": {"latencyMs": 743},
202 }
203
204 request = ChatCompletionRequest(
205 model=self.valid_supported_model,
206 messages=[
207 UserMessage(
208 content="Use provided function to find the boiling point of polyjuice?",
209 ),
210 ],
211 stream=False,
212 tools=[self.custom_tool_defn],
213 tool_choice=ToolChoice.required,
214 )
215 iterator = self.api.chat_completion(
216 request.model,
217 request.messages,
218 request.sampling_params,
219 request.tools,
220 request.tool_choice,
221 request.tool_prompt_format,
222 request.stream,
223 request.logprobs,
224 )
225 async for r in iterator:
226 response = r
227
228 completion_message = response.completion_message
229
230 self.assertEqual(len(completion_message.content), 0)
231 self.assertTrue(
232 completion_message.stop_reason
233 in {
234 StopReason.end_of_turn,
235 StopReason.end_of_message,
236 }
237 )
238
239 self.assertEqual(
240 len(completion_message.tool_calls), 1, completion_message.tool_calls
241 )
242 self.assertEqual(
243 completion_message.tool_calls[0].tool_name, "get_boiling_point"
244 )
245
246 args = completion_message.tool_calls[0].arguments
247 self.assertTrue(isinstance(args, dict))
248 self.assertTrue(args["liquid_name"], "polyjuice")
249
250 async def test_text_streaming(self):
251 events = [
252 {"messageStart": {"role": "assistant"}},
253 {"contentBlockDelta": {"delta": {"text": "\n\n"}, "contentBlockIndex": 0}},
254 {"contentBlockDelta": {"delta": {"text": "The"}, "contentBlockIndex": 0}},
255 {
256 "contentBlockDelta": {
257 "delta": {"text": " capital"},
258 "contentBlockIndex": 0,
259 }
260 },
261 {"contentBlockDelta": {"delta": {"text": " of"}, "contentBlockIndex": 0}},
262 {
263 "contentBlockDelta": {
264 "delta": {"text": " France"},
265 "contentBlockIndex": 0,
266 }
267 },
268 {"contentBlockDelta": {"delta": {"text": " is"}, "contentBlockIndex": 0}},
269 {
270 "contentBlockDelta": {
271 "delta": {"text": " Paris"},
272 "contentBlockIndex": 0,
273 }
274 },
275 {"contentBlockDelta": {"delta": {"text": "."}, "contentBlockIndex": 0}},
276 {"contentBlockDelta": {"delta": {"text": ""}, "contentBlockIndex": 0}},
277 {"contentBlockStop": {"contentBlockIndex": 0}},
278 {"messageStop": {"stopReason": "end_turn"}},
279 {
280 "metadata": {
281 "usage": {"inputTokens": 21, "outputTokens": 9, "totalTokens": 30},
282 "metrics": {"latencyMs": 1},
283 }
284 },
285 ]
286
287 with mock.patch.object(
288 self.api.client, "converse_stream"
289 ) as mock_converse_stream:
290 mock_converse_stream.return_value = {"stream": events}
291 request = ChatCompletionRequest(
292 model=self.valid_supported_model,
293 messages=[
294 UserMessage(
295 content="What is the capital of France?",
296 ),
297 ],
298 stream=True,
299 )
300 iterator = self.api.chat_completion(
301 request.model,
302 request.messages,
303 request.sampling_params,
304 request.tools,
305 request.tool_choice,
306 request.tool_prompt_format,
307 request.stream,
308 request.logprobs,
309 )
310 events = []
311 async for chunk in iterator:
312 events.append(chunk.event)
313
314 response = ""
315 for e in events[1:-1]:
316 response += e.delta
317
318 self.assertEqual(
319 events[0].event_type, ChatCompletionResponseEventType.start
320 )
321 # last event is of type "complete"
322 self.assertEqual(
323 events[-1].event_type, ChatCompletionResponseEventType.complete
324 )
325 # last but 1 event should be of type "progress"
326 self.assertEqual(
327 events[-2].event_type, ChatCompletionResponseEventType.progress
328 )
329 self.assertEqual(
330 events[-2].stop_reason,
331 None,
332 )
333 self.assertTrue("Paris" in response, response)
334
335 def test_resolve_bedrock_model(self):
336 bedrock_model = self.api.resolve_bedrock_model(self.valid_supported_model)
337 self.assertEqual(bedrock_model, "meta.llama3-1-8b-instruct-v1:0")
338
339 invalid_model = "Meta-Llama3.1-8B"
340 with self.assertRaisesRegex(
341 AssertionError, f"Unsupported model: {invalid_model}"
342 ):
343 self.api.resolve_bedrock_model(invalid_model)
344
345 async def test_bedrock_chat_inference_config(self):
346 request = ChatCompletionRequest(
347 model=self.valid_supported_model,
348 messages=[
349 UserMessage(
350 content="What is the capital of France?",
351 ),
352 ],
353 stream=False,
354 sampling_params=SamplingParams(
355 sampling_strategy=SamplingStrategy.top_p,
356 top_p=0.99,
357 temperature=1.0,
358 ),
359 )
360 options = self.api.get_bedrock_inference_config(request.sampling_params)
361 self.assertEqual(
362 options,
363 {
364 "temperature": 1.0,
365 "topP": 0.99,
366 },
367 )
368
369 async def test_multi_turn_non_streaming(self):
370 with mock.patch.object(self.api.client, "converse") as mock_converse:
371 mock_converse.return_value = {
372 "ResponseMetadata": {
373 "RequestId": "4171abf1-a5f4-4eee-bb12-0e472a73bdbe",
374 "HTTPStatusCode": 200,
375 "HTTPHeaders": {},
376 "RetryAttempts": 0,
377 },
378 "output": {
379 "message": {
380 "role": "assistant",
381 "content": [
382 {
383 "text": "\nThe 44th president of the United States was Barack Obama."
384 }
385 ],
386 }
387 },
388 "stopReason": "end_turn",
389 "usage": {"inputTokens": 723, "outputTokens": 15, "totalTokens": 738},
390 "metrics": {"latencyMs": 449},
391 }
392
393 request = ChatCompletionRequest(
394 model=self.valid_supported_model,
395 messages=[
396 UserMessage(
397 content="Search the web and tell me who the "
398 "44th president of the United States was",
399 ),
400 CompletionMessage(
401 content=[],
402 stop_reason=StopReason.end_of_turn,
403 tool_calls=[
404 ToolCall(
405 call_id="1",
406 tool_name=BuiltinTool.brave_search,
407 arguments={
408 "query": "44th president of the United States"
409 },
410 )
411 ],
412 ),
413 ToolResponseMessage(
414 call_id="1",
415 tool_name=BuiltinTool.brave_search,
416 content='{"query": "44th president of the United States", "top_k": [{"title": "Barack Obama | The White House", "url": "https://www.whitehouse.gov/about-the-white-house/presidents/barack-obama/", "description": "<strong>Barack Obama</strong> served as the 44th President of the United States. His story is the American story \\u2014 values from the heartland, a middle-class upbringing in a strong family, hard work and education as the means of getting ahead, and the conviction that a life so blessed should be lived in service ...", "type": "search_result"}, {"title": "Barack Obama \\u2013 The White House", "url": "https://trumpwhitehouse.archives.gov/about-the-white-house/presidents/barack-obama/", "description": "After working his way through college with the help of scholarships and student loans, <strong>President Obama</strong> moved to Chicago, where he worked with a group of churches to help rebuild communities devastated by the closure of local steel plants.", "type": "search_result"}, [{"type": "video_result", "url": "https://www.instagram.com/reel/CzMZbJmObn9/", "title": "Fifteen years ago, on Nov. 4, Barack Obama was elected as ...", "description": ""}, {"type": "video_result", "url": "https://video.alexanderstreet.com/watch/the-44th-president-barack-obama?context=channel:barack-obama", "title": "The 44th President (Barack Obama) - Alexander Street, a ...", "description": "You need to enable JavaScript to run this app"}, {"type": "video_result", "url": "https://www.youtube.com/watch?v=iyL7_2-em5k", "title": "Barack Obama for Kids | Learn about the life and contributions ...", "description": "Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube."}, {"type": "video_result", "url": "https://www.britannica.com/video/172743/overview-Barack-Obama", "title": "President of the United States of America Barack Obama | Britannica", "description": "[NARRATOR] Barack Obama was elected the 44th president of the United States in 2008, becoming the first African American to hold the office. Obama vowed to bring change to the political system."}, {"type": "video_result", "url": "https://www.youtube.com/watch?v=rvr2g8-5dcE", "title": "The 44th President: In His Own Words - Toughest Day | Special ...", "description": "President Obama reflects on his toughest day in the Presidency and seeing Secret Service cry for the first time. Watch the premiere of The 44th President: In..."}]]}',
417 ),
418 ],
419 stream=False,
420 tools=[ToolDefinition(tool_name=BuiltinTool.brave_search)],
421 )
422 iterator = self.api.chat_completion(
423 request.model,
424 request.messages,
425 request.sampling_params,
426 request.tools,
427 request.tool_choice,
428 request.tool_prompt_format,
429 request.stream,
430 request.logprobs,
431 )
432 async for r in iterator:
433 response = r
434
435 completion_message = response.completion_message
436
437 self.assertEqual(len(completion_message.content), 1)
438 self.assertTrue(
439 completion_message.stop_reason
440 in {
441 StopReason.end_of_turn,
442 StopReason.end_of_message,
443 }
444 )
445
446 self.assertTrue("obama" in completion_message.content[0].lower())