Elffuss BraidHub

kikocis/llama-stack public

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