Elffuss BraidHub

kikocis/llama-stack public

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