Elffuss BraidHub

kikocis/llama-stack public

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