Elffuss BraidHub

kikocis/llama-stack public

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