Elffuss BraidHub

kikocis/llama-stack public

2e30ba2d48a0 · 11.5 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
7# Run this test using the following command:
8# python -m unittest tests/test_inference.py
9
10import asyncio
11import os
12import textwrap
13import unittest
14
15from datetime import datetime
16
17from llama_models.llama3.api.datatypes import (
18 BuiltinTool,
19 StopReason,
20 SystemMessage,
21 ToolDefinition,
22 ToolParamDefinition,
23 ToolPromptFormat,
24 ToolResponseMessage,
25 UserMessage,
26)
27
28from llama_stack.inference.api import (
29 ChatCompletionRequest,
30 ChatCompletionResponseEventType,
31)
32from llama_stack.inference.meta_reference.config import MetaReferenceImplConfig
33from llama_stack.inference.meta_reference.inference import get_provider_impl
34
35
36MODEL = "Meta-Llama3.1-8B-Instruct"
37HELPER_MSG = """
38This test needs llama-3.1-8b-instruct models.
39Please donwload using the llama cli
40
41llama download --source huggingface --model-id llama3_1_8b_instruct --hf-token <HF_TOKEN>
42"""
43
44
45class InferenceTests(unittest.IsolatedAsyncioTestCase):
46 @classmethod
47 def setUpClass(cls):
48 # This runs the async setup function
49 asyncio.run(cls.asyncSetUpClass())
50
51 @classmethod
52 async def asyncSetUpClass(cls):
53 # assert model exists on local
54 model_dir = os.path.expanduser(f"~/.llama/checkpoints/{MODEL}/original/")
55 assert os.path.isdir(model_dir), HELPER_MSG
56
57 tokenizer_path = os.path.join(model_dir, "tokenizer.model")
58 assert os.path.exists(tokenizer_path), HELPER_MSG
59
60 config = MetaReferenceImplConfig(
61 model=MODEL,
62 max_seq_len=2048,
63 )
64
65 cls.api = await get_provider_impl(config, {})
66 await cls.api.initialize()
67
68 @classmethod
69 def tearDownClass(cls):
70 # This runs the async teardown function
71 asyncio.run(cls.asyncTearDownClass())
72
73 @classmethod
74 async def asyncTearDownClass(cls):
75 await cls.api.shutdown()
76
77 async def asyncSetUp(self):
78 self.valid_supported_model = MODEL
79 self.custom_tool_defn = ToolDefinition(
80 tool_name="get_boiling_point",
81 description="Get the boiling point of a imaginary liquids (eg. polyjuice)",
82 parameters={
83 "liquid_name": ToolParamDefinition(
84 param_type="str",
85 description="The name of the liquid",
86 required=True,
87 ),
88 "celcius": ToolParamDefinition(
89 param_type="boolean",
90 description="Whether to return the boiling point in Celcius",
91 required=False,
92 ),
93 },
94 )
95
96 async def test_text(self):
97 request = ChatCompletionRequest(
98 model=self.valid_supported_model,
99 messages=[
100 UserMessage(
101 content="What is the capital of France?",
102 ),
103 ],
104 stream=False,
105 )
106 iterator = InferenceTests.api.chat_completion(request)
107
108 async for chunk in iterator:
109 response = chunk
110
111 result = response.completion_message.content
112 self.assertTrue("Paris" in result, result)
113
114 async def test_text_streaming(self):
115 request = ChatCompletionRequest(
116 model=self.valid_supported_model,
117 messages=[
118 UserMessage(
119 content="What is the capital of France?",
120 ),
121 ],
122 stream=True,
123 )
124 iterator = InferenceTests.api.chat_completion(request)
125
126 events = []
127 async for chunk in iterator:
128 events.append(chunk.event)
129 # print(f"{chunk.event.event_type:<40} | {str(chunk.event.stop_reason):<26} | {chunk.event.delta} ")
130
131 self.assertEqual(events[0].event_type, ChatCompletionResponseEventType.start)
132 self.assertEqual(
133 events[-1].event_type, ChatCompletionResponseEventType.complete
134 )
135
136 response = ""
137 for e in events[1:-1]:
138 response += e.delta
139
140 self.assertTrue("Paris" in response, response)
141
142 async def test_custom_tool_call(self):
143 request = ChatCompletionRequest(
144 model=self.valid_supported_model,
145 messages=[
146 UserMessage(
147 content="Use provided function to find the boiling point of polyjuice in fahrenheit?",
148 ),
149 ],
150 stream=False,
151 tools=[self.custom_tool_defn],
152 )
153 iterator = InferenceTests.api.chat_completion(request)
154 async for r in iterator:
155 response = r
156
157 completion_message = response.completion_message
158
159 self.assertEqual(completion_message.content, "")
160
161 # FIXME: This test fails since there is a bug where
162 # custom tool calls return incoorect stop_reason as out_of_tokens
163 # instead of end_of_turn
164 # self.assertEqual(completion_message.stop_reason, StopReason.end_of_turn)
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_tool_call_streaming(self):
178 request = ChatCompletionRequest(
179 model=self.valid_supported_model,
180 messages=[
181 UserMessage(
182 content="Who is the current US President?",
183 ),
184 ],
185 tools=[ToolDefinition(tool_name=BuiltinTool.brave_search)],
186 stream=True,
187 )
188 iterator = InferenceTests.api.chat_completion(request)
189
190 events = []
191 async for chunk in iterator:
192 # print(f"{chunk.event.event_type:<40} | {str(chunk.event.stop_reason):<26} | {chunk.event.delta} ")
193 events.append(chunk.event)
194
195 self.assertEqual(events[0].event_type, ChatCompletionResponseEventType.start)
196 # last event is of type "complete"
197 self.assertEqual(
198 events[-1].event_type, ChatCompletionResponseEventType.complete
199 )
200 # last but one event should be eom with tool call
201 self.assertEqual(
202 events[-2].event_type, ChatCompletionResponseEventType.progress
203 )
204 self.assertEqual(events[-2].stop_reason, StopReason.end_of_message)
205 self.assertEqual(events[-2].delta.content.tool_name, BuiltinTool.brave_search)
206
207 async def test_custom_tool_call_streaming(self):
208 request = ChatCompletionRequest(
209 model=self.valid_supported_model,
210 messages=[
211 UserMessage(
212 content="Use provided function to find the boiling point of polyjuice?",
213 ),
214 ],
215 stream=True,
216 tools=[self.custom_tool_defn],
217 tool_prompt_format=ToolPromptFormat.function_tag,
218 )
219 iterator = InferenceTests.api.chat_completion(request)
220 events = []
221 async for chunk in iterator:
222 # print(
223 # f"{chunk.event.event_type:<40} | {str(chunk.event.stop_reason):<26} | {chunk.event.delta} "
224 # )
225 events.append(chunk.event)
226
227 self.assertEqual(events[0].event_type, ChatCompletionResponseEventType.start)
228 # last event is of type "complete"
229 self.assertEqual(
230 events[-1].event_type, ChatCompletionResponseEventType.complete
231 )
232 self.assertEqual(events[-1].stop_reason, StopReason.end_of_turn)
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, "get_boiling_point")
239
240 async def test_multi_turn(self):
241 request = ChatCompletionRequest(
242 model=self.valid_supported_model,
243 messages=[
244 UserMessage(
245 content="Search the web and tell me who the "
246 "44th president of the United States was",
247 ),
248 ToolResponseMessage(
249 call_id="1",
250 tool_name=BuiltinTool.brave_search,
251 # 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..."}]]}',
252 content='"Barack Obama"',
253 ),
254 ],
255 stream=True,
256 tools=[ToolDefinition(tool_name=BuiltinTool.brave_search)],
257 )
258 iterator = self.api.chat_completion(
259 request.model,
260 request.messages,
261 stream=request.stream,
262 tools=request.tools,
263 )
264
265 events = []
266 async for chunk in iterator:
267 events.append(chunk.event)
268
269 response = ""
270 for e in events[1:-1]:
271 response += e.delta
272
273 self.assertTrue("obama" in response.lower())