Elffuss BraidHub

kikocis/llama-stack public

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