Elffuss BraidHub

kikocis/llama-stack public

842c3e3bbdd0 · 14.9 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 textwrap
8import unittest
9from datetime import datetime
10
11from llama_models.llama3.api.datatypes import (
12 BuiltinTool,
13 SamplingParams,
14 SamplingStrategy,
15 StopReason,
16 SystemMessage,
17 ToolDefinition,
18 ToolParamDefinition,
19 ToolPromptFormat,
20 ToolResponseMessage,
21 UserMessage,
22)
23from llama_stack.inference.api import (
24 ChatCompletionRequest,
25 ChatCompletionResponseEventType,
26)
27from llama_stack.inference.ollama.config import OllamaImplConfig
28from llama_stack.inference.ollama.ollama import get_provider_impl
29
30
31class OllamaInferenceTests(unittest.IsolatedAsyncioTestCase):
32 async def asyncSetUp(self):
33 ollama_config = OllamaImplConfig(url="http://localhost:11434")
34
35 # setup ollama
36 self.api = await get_provider_impl(ollama_config, {})
37 await self.api.initialize()
38
39 self.custom_tool_defn = ToolDefinition(
40 tool_name="get_boiling_point",
41 description="Get the boiling point of a imaginary liquids (eg. polyjuice)",
42 parameters={
43 "liquid_name": ToolParamDefinition(
44 param_type="str",
45 description="The name of the liquid",
46 required=True,
47 ),
48 "celcius": ToolParamDefinition(
49 param_type="boolean",
50 description="Whether to return the boiling point in Celcius",
51 required=False,
52 ),
53 },
54 )
55 self.valid_supported_model = "Meta-Llama3.1-8B-Instruct"
56
57 async def asyncTearDown(self):
58 await self.api.shutdown()
59
60 async def test_text(self):
61 request = ChatCompletionRequest(
62 model=self.valid_supported_model,
63 messages=[
64 UserMessage(
65 content="What is the capital of France?",
66 ),
67 ],
68 stream=False,
69 )
70 iterator = self.api.chat_completion(
71 request.model, request.messages, stream=request.stream
72 )
73 async for r in iterator:
74 response = r
75 print(response.completion_message.content)
76 self.assertTrue("Paris" in response.completion_message.content)
77 self.assertEqual(
78 response.completion_message.stop_reason, StopReason.end_of_turn
79 )
80
81 async def test_tool_call(self):
82 request = ChatCompletionRequest(
83 model=self.valid_supported_model,
84 messages=[
85 UserMessage(
86 content="Who is the current US President?",
87 ),
88 ],
89 stream=False,
90 tools=[ToolDefinition(tool_name=BuiltinTool.brave_search)],
91 )
92 iterator = self.api.chat_completion(request)
93 async for r in iterator:
94 response = r
95
96 completion_message = response.completion_message
97
98 self.assertEqual(completion_message.content, "")
99 self.assertEqual(completion_message.stop_reason, StopReason.end_of_turn)
100
101 self.assertEqual(
102 len(completion_message.tool_calls), 1, completion_message.tool_calls
103 )
104 self.assertEqual(
105 completion_message.tool_calls[0].tool_name, BuiltinTool.brave_search
106 )
107 self.assertTrue(
108 "president" in completion_message.tool_calls[0].arguments["query"].lower()
109 )
110
111 async def test_code_execution(self):
112 request = ChatCompletionRequest(
113 model=self.valid_supported_model,
114 messages=[
115 UserMessage(
116 content="Write code to compute the 5th prime number",
117 ),
118 ],
119 tools=[ToolDefinition(tool_name=BuiltinTool.code_interpreter)],
120 stream=False,
121 )
122 iterator = self.api.chat_completion(request)
123 async for r in iterator:
124 response = r
125
126 completion_message = response.completion_message
127
128 self.assertEqual(completion_message.content, "")
129 self.assertEqual(completion_message.stop_reason, StopReason.end_of_turn)
130
131 self.assertEqual(
132 len(completion_message.tool_calls), 1, completion_message.tool_calls
133 )
134 self.assertEqual(
135 completion_message.tool_calls[0].tool_name, BuiltinTool.code_interpreter
136 )
137 code = completion_message.tool_calls[0].arguments["code"]
138 self.assertTrue("def " in code.lower(), code)
139
140 async def test_custom_tool(self):
141 request = ChatCompletionRequest(
142 model=self.valid_supported_model,
143 messages=[
144 UserMessage(
145 content="Use provided function to find the boiling point of polyjuice?",
146 ),
147 ],
148 stream=False,
149 tools=[self.custom_tool_defn],
150 )
151 iterator = self.api.chat_completion(request)
152 async for r in iterator:
153 response = r
154
155 completion_message = response.completion_message
156
157 self.assertEqual(completion_message.content, "")
158 self.assertTrue(
159 completion_message.stop_reason
160 in {
161 StopReason.end_of_turn,
162 StopReason.end_of_message,
163 }
164 )
165
166 self.assertEqual(
167 len(completion_message.tool_calls), 1, completion_message.tool_calls
168 )
169 self.assertEqual(
170 completion_message.tool_calls[0].tool_name, "get_boiling_point"
171 )
172
173 args = completion_message.tool_calls[0].arguments
174 self.assertTrue(isinstance(args, dict))
175 self.assertTrue(args["liquid_name"], "polyjuice")
176
177 async def test_text_streaming(self):
178 request = ChatCompletionRequest(
179 model=self.valid_supported_model,
180 messages=[
181 UserMessage(
182 content="What is the capital of France?",
183 ),
184 ],
185 stream=True,
186 )
187 iterator = self.api.chat_completion(request)
188 events = []
189 async for chunk in iterator:
190 # print(f"{chunk.event.event_type:<40} | {str(chunk.event.stop_reason):<26} | {chunk.event.delta} ")
191 events.append(chunk.event)
192
193 response = ""
194 for e in events[1:-1]:
195 response += e.delta
196
197 self.assertEqual(events[0].event_type, ChatCompletionResponseEventType.start)
198 # last event is of type "complete"
199 self.assertEqual(
200 events[-1].event_type, ChatCompletionResponseEventType.complete
201 )
202 # last but 1 event should be of type "progress"
203 self.assertEqual(
204 events[-2].event_type, ChatCompletionResponseEventType.progress
205 )
206 self.assertEqual(
207 events[-2].stop_reason,
208 None,
209 )
210 self.assertTrue("Paris" in response, response)
211
212 async def test_tool_call_streaming(self):
213 request = ChatCompletionRequest(
214 model=self.valid_supported_model,
215 messages=[
216 UserMessage(
217 content="Using web search tell me who is the current US President?",
218 ),
219 ],
220 stream=True,
221 tools=[ToolDefinition(tool_name=BuiltinTool.brave_search)],
222 )
223 iterator = self.api.chat_completion(request)
224 events = []
225 async for chunk in iterator:
226 events.append(chunk.event)
227
228 self.assertEqual(events[0].event_type, ChatCompletionResponseEventType.start)
229 # last event is of type "complete"
230 self.assertEqual(
231 events[-1].event_type, ChatCompletionResponseEventType.complete
232 )
233 # last but one event should be eom with tool call
234 self.assertEqual(
235 events[-2].event_type, ChatCompletionResponseEventType.progress
236 )
237 self.assertEqual(events[-2].stop_reason, StopReason.end_of_turn)
238 self.assertEqual(events[-2].delta.content.tool_name, BuiltinTool.brave_search)
239
240 async def test_custom_tool_call_streaming(self):
241 request = ChatCompletionRequest(
242 model=self.valid_supported_model,
243 messages=[
244 UserMessage(
245 content="Use provided function to find the boiling point of polyjuice?",
246 ),
247 ],
248 stream=True,
249 tools=[self.custom_tool_defn],
250 tool_prompt_format=ToolPromptFormat.function_tag,
251 )
252 iterator = self.api.chat_completion(request)
253 events = []
254 async for chunk in iterator:
255 # print(f"{chunk.event.event_type:<40} | {str(chunk.event.stop_reason):<26} | {chunk.event.delta} ")
256 events.append(chunk.event)
257
258 self.assertEqual(events[0].event_type, ChatCompletionResponseEventType.start)
259 # last event is of type "complete"
260 self.assertEqual(
261 events[-1].event_type, ChatCompletionResponseEventType.complete
262 )
263 self.assertEqual(events[-1].stop_reason, StopReason.end_of_turn)
264 # last but one event should be eom with tool call
265 self.assertEqual(
266 events[-2].event_type, ChatCompletionResponseEventType.progress
267 )
268 self.assertEqual(events[-2].delta.content.tool_name, "get_boiling_point")
269 self.assertEqual(events[-2].stop_reason, StopReason.end_of_turn)
270
271 def test_resolve_ollama_model(self):
272 ollama_model = self.api.resolve_ollama_model(self.valid_supported_model)
273 self.assertEqual(ollama_model, "llama3.1:8b-instruct-fp16")
274
275 invalid_model = "Meta-Llama3.1-8B"
276 with self.assertRaisesRegex(
277 AssertionError, f"Unsupported model: {invalid_model}"
278 ):
279 self.api.resolve_ollama_model(invalid_model)
280
281 async def test_ollama_chat_options(self):
282 request = ChatCompletionRequest(
283 model=self.valid_supported_model,
284 messages=[
285 UserMessage(
286 content="What is the capital of France?",
287 ),
288 ],
289 stream=False,
290 sampling_params=SamplingParams(
291 sampling_strategy=SamplingStrategy.top_p,
292 top_p=0.99,
293 temperature=1.0,
294 ),
295 )
296 options = self.api.get_ollama_chat_options(request)
297 self.assertEqual(
298 options,
299 {
300 "temperature": 1.0,
301 "top_p": 0.99,
302 },
303 )
304
305 async def test_multi_turn(self):
306 request = ChatCompletionRequest(
307 model=self.valid_supported_model,
308 messages=[
309 UserMessage(
310 content="Search the web and tell me who the "
311 "44th president of the United States was",
312 ),
313 ToolResponseMessage(
314 call_id="1",
315 tool_name=BuiltinTool.brave_search,
316 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..."}]]}',
317 ),
318 ],
319 stream=True,
320 tools=[ToolDefinition(tool_name=BuiltinTool.brave_search)],
321 )
322 iterator = self.api.chat_completion(request)
323
324 events = []
325 async for chunk in iterator:
326 events.append(chunk.event)
327
328 response = ""
329 for e in events[1:-1]:
330 response += e.delta
331
332 self.assertTrue("obama" in response.lower())
333
334 async def test_tool_call_code_streaming(self):
335 request = ChatCompletionRequest(
336 model=self.valid_supported_model,
337 messages=[
338 UserMessage(
339 content="Write code to answer this question: What is the 100th prime number?",
340 ),
341 ],
342 stream=True,
343 tools=[ToolDefinition(tool_name=BuiltinTool.code_interpreter)],
344 )
345 iterator = self.api.chat_completion(request)
346 events = []
347 async for chunk in iterator:
348 events.append(chunk.event)
349
350 self.assertEqual(events[0].event_type, ChatCompletionResponseEventType.start)
351 # last event is of type "complete"
352 self.assertEqual(
353 events[-1].event_type, ChatCompletionResponseEventType.complete
354 )
355 # last but one event should be eom with tool call
356 self.assertEqual(
357 events[-2].event_type, ChatCompletionResponseEventType.progress
358 )
359 self.assertEqual(events[-2].stop_reason, StopReason.end_of_turn)
360 self.assertEqual(
361 events[-2].delta.content.tool_name, BuiltinTool.code_interpreter
362 )