aashish1904 commited on
Commit
54b2cf8
1 Parent(s): dfead1a

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +440 -0
README.md ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ---
3
+
4
+ extra_gated_heading: >-
5
+ Acknowledge to follow corresponding license to access the
6
+ repository
7
+ extra_gated_button_content: Agree and access repository
8
+ extra_gated_fields:
9
+ First Name: text
10
+ Last Name: text
11
+ Country: country
12
+ Affiliation: text
13
+ license: cc-by-nc-4.0
14
+ datasets:
15
+ - Salesforce/xlam-function-calling-60k
16
+ language:
17
+ - en
18
+ pipeline_tag: text-generation
19
+ tags:
20
+ - function-calling
21
+ - LLM Agent
22
+ - tool-use
23
+ - mistral
24
+ - pytorch
25
+
26
+ ---
27
+
28
+ ![](https://lh7-rt.googleusercontent.com/docsz/AD_4nXeiuCm7c8lEwEJuRey9kiVZsRn2W-b4pWlu3-X534V3YmVuVc2ZL-NXg2RkzSOOS2JXGHutDuyyNAUtdJI65jGTo8jT9Y99tMi4H4MqL44Uc5QKG77B0d6-JfIkZHFaUA71-RtjyYZWVIhqsNZcx8-OMaA?key=xt3VSDoCbmTY7o-cwwOFwQ)
29
+
30
+ # QuantFactory/xLAM-7b-r-GGUF
31
+ This is quantized version of [Salesforce/xLAM-7b-r](https://huggingface.co/Salesforce/xLAM-7b-r) created using llama.cpp
32
+
33
+ # Original Model Card
34
+
35
+
36
+ <p align="center">
37
+ <img width="500px" alt="xLAM" src="https://huggingface.co/datasets/jianguozhang/logos/resolve/main/xlam-no-background.png">
38
+ </p>
39
+ <p align="center">
40
+ <a href="">[Homepage]</a> |
41
+ <a href="">[Paper]</a> |
42
+ <a href="https://github.com/SalesforceAIResearch/xLAM">[Github]</a>
43
+ </p>
44
+ <hr>
45
+
46
+
47
+ Welcome to the xLAM model family! [Large Action Models (LAMs)](https://blog.salesforceairesearch.com/large-action-models/) are advanced large language models designed to enhance decision-making and translate user intentions into executable actions that interact with the world. LAMs autonomously plan and execute tasks to achieve specific goals, serving as the brains of AI agents. They have the potential to automate workflow processes across various domains, making them invaluable for a wide range of applications.
48
+ **The model release is exclusively for research purposes. A new and enhanced version of xLAM will soon be available exclusively to customers on our Platform.**
49
+
50
+ ## Table of Contents
51
+ - [Model Series](#model-series)
52
+ - [Repository Overview](#repository-overview)
53
+ - [Benchmark Results](#benchmark-results)
54
+ - [Usage](#usage)
55
+ - [Basic Usage with Huggingface](#basic-usage-with-huggingface)
56
+ - [License](#license)
57
+ - [Citation](#citation)
58
+
59
+ ## Model Series
60
+
61
+ We provide a series of xLAMs in different sizes to cater to various applications, including those optimized for function-calling and general agent applications:
62
+
63
+ | Model | # Total Params | Context Length | Download Model | Download GGUF files |
64
+ |------------------------|----------------|----------------|----------------|----------|
65
+ | xLAM-1b-fc-r | 1.35B | 16k | [🤗 Link](https://huggingface.co/Salesforce/xLAM-1b-fc-r) | [🤗 Link](https://huggingface.co/Salesforce/xLAM-1b-fc-r-gguf) |
66
+ | xLAM-7b-fc-r | 6.91B | 4k | [🤗 Link](https://huggingface.co/Salesforce/xLAM-7b-fc-r) | [🤗 Link](https://huggingface.co/Salesforce/xLAM-7b-fc-r-gguf) |
67
+ | xLAM-7b-r | 7.24B | 32k | [🤗 Link](https://huggingface.co/Salesforce/xLAM-7b-r) | -- |
68
+ | xLAM-8x7b-r | 46.7B | 32k | [🤗 Link](https://huggingface.co/Salesforce/xLAM-8x7b-r) | -- |
69
+ | xLAM-8x22b-r | 141B | 64k | [🤗 Link](https://huggingface.co/Salesforce/xLAM-8x22b-r) | -- |
70
+
71
+
72
+
73
+
74
+
75
+
76
+ For our Function-calling series (more details are included at [here](https://huggingface.co/Salesforce/xLAM-7b-fc-r)), we also provide their quantized [GGUF](https://huggingface.co/docs/hub/en/gguf) files for efficient deployment and execution. GGUF is a file format designed to efficiently store and load large language models, making GGUF ideal for running AI models on local devices with limited resources, enabling offline functionality and enhanced privacy.
77
+
78
+ For more details, check our [GitHub](https://github.com/SalesforceAIResearch/xLAM) and [paper]().
79
+
80
+
81
+ ## Repository Overview
82
+
83
+ This repository is about the general tool use series. For more specialized function calling models, please take a look into our `fc` series [here](https://huggingface.co/Salesforce/xLAM-7b-fc-r).
84
+
85
+ The instructions will guide you through the setup, usage, and integration of our model series with HuggingFace.
86
+ ### Framework Versions
87
+
88
+ - Transformers 4.41.0
89
+ - Pytorch 2.3.0+cu121
90
+ - Datasets 2.19.1
91
+ - Tokenizers 0.19.1
92
+
93
+ ## Usage
94
+
95
+ ### Basic Usage with Huggingface
96
+
97
+ To use the model from Huggingface, please first install the `transformers` library:
98
+ ```bash
99
+ pip install transformers>=4.41.0
100
+ ```
101
+
102
+ Please note that, our model works best with our provided prompt format.
103
+ It allows us to extract JSON output that is similar to the [function-calling mode of ChatGPT](https://platform.openai.com/docs/guides/function-calling).
104
+
105
+ We use the following example to illustrate how to use our model for 1) single-turn use case, and 2) multi-turn use case
106
+
107
+ #### 1. Single-turn use case
108
+
109
+ ````python
110
+ import json
111
+ import torch
112
+ from transformers import AutoModelForCausalLM, AutoTokenizer
113
+
114
+ torch.random.manual_seed(0)
115
+
116
+ model_name = "Salesforce/xLAM-7b-r"
117
+ model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype="auto", trust_remote_code=True)
118
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
119
+
120
+ # Please use our provided instruction prompt for best performance
121
+ task_instruction = """
122
+ Based on the previous context and API request history, generate an API request or a response as an AI assistant.""".strip()
123
+
124
+ format_instruction = """
125
+ The output should be of the JSON format, which specifies a list of generated function calls. The example format is as follows, please make sure the parameter type is correct. If no function call is needed, please make
126
+ tool_calls an empty list "[]".
127
+ ```
128
+ {"thought": "the thought process, or an empty string", "tool_calls": [{"name": "api_name1", "arguments": {"argument1": "value1", "argument2": "value2"}}]}
129
+ ```
130
+ """.strip()
131
+
132
+ # Define the input query and available tools
133
+ query = "What's the weather like in New York in fahrenheit?"
134
+
135
+ get_weather_api = {
136
+ "name": "get_weather",
137
+ "description": "Get the current weather for a location",
138
+ "parameters": {
139
+ "type": "object",
140
+ "properties": {
141
+ "location": {
142
+ "type": "string",
143
+ "description": "The city and state, e.g. San Francisco, New York"
144
+ },
145
+ "unit": {
146
+ "type": "string",
147
+ "enum": ["celsius", "fahrenheit"],
148
+ "description": "The unit of temperature to return"
149
+ }
150
+ },
151
+ "required": ["location"]
152
+ }
153
+ }
154
+
155
+ search_api = {
156
+ "name": "search",
157
+ "description": "Search for information on the internet",
158
+ "parameters": {
159
+ "type": "object",
160
+ "properties": {
161
+ "query": {
162
+ "type": "string",
163
+ "description": "The search query, e.g. 'latest news on AI'"
164
+ }
165
+ },
166
+ "required": ["query"]
167
+ }
168
+ }
169
+
170
+ openai_format_tools = [get_weather_api, search_api]
171
+
172
+ # Helper function to convert openai format tools to our more concise xLAM format
173
+ def convert_to_xlam_tool(tools):
174
+ ''''''
175
+ if isinstance(tools, dict):
176
+ return {
177
+ "name": tools["name"],
178
+ "description": tools["description"],
179
+ "parameters": {k: v for k, v in tools["parameters"].get("properties", {}).items()}
180
+ }
181
+ elif isinstance(tools, list):
182
+ return [convert_to_xlam_tool(tool) for tool in tools]
183
+ else:
184
+ return tools
185
+
186
+ def build_conversation_history_prompt(conversation_history: str):
187
+ parsed_history = []
188
+ for step_data in conversation_history:
189
+ parsed_history.append({
190
+ "step_id": step_data["step_id"],
191
+ "thought": step_data["thought"],
192
+ "tool_calls": step_data["tool_calls"],
193
+ "next_observation": step_data["next_observation"],
194
+ "user_input": step_data['user_input']
195
+ })
196
+
197
+ history_string = json.dumps(parsed_history)
198
+ return f"\n[BEGIN OF HISTORY STEPS]\n{history_string}\n[END OF HISTORY STEPS]\n"
199
+
200
+
201
+ # Helper function to build the input prompt for our model
202
+ def build_prompt(task_instruction: str, format_instruction: str, tools: list, query: str, conversation_history: list):
203
+ prompt = f"[BEGIN OF TASK INSTRUCTION]\n{task_instruction}\n[END OF TASK INSTRUCTION]\n\n"
204
+ prompt += f"[BEGIN OF AVAILABLE TOOLS]\n{json.dumps(xlam_format_tools)}\n[END OF AVAILABLE TOOLS]\n\n"
205
+ prompt += f"[BEGIN OF FORMAT INSTRUCTION]\n{format_instruction}\n[END OF FORMAT INSTRUCTION]\n\n"
206
+ prompt += f"[BEGIN OF QUERY]\n{query}\n[END OF QUERY]\n\n"
207
+
208
+ if len(conversation_history) > 0: prompt += build_conversation_history_prompt(conversation_history)
209
+ return prompt
210
+
211
+ # Build the input and start the inference
212
+ xlam_format_tools = convert_to_xlam_tool(openai_format_tools)
213
+
214
+ conversation_history = []
215
+ content = build_prompt(task_instruction, format_instruction, xlam_format_tools, query, conversation_history)
216
+
217
+ messages=[
218
+ { 'role': 'user', 'content': content}
219
+ ]
220
+
221
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
222
+
223
+ # tokenizer.eos_token_id is the id of <|EOT|> token
224
+ outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
225
+ agent_action = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
226
+ ````
227
+
228
+ Then you should be able to see the following output string in JSON format:
229
+
230
+ ```shell
231
+ {"thought": "I need to get the current weather for New York in fahrenheit.", "tool_calls": [{"name": "get_weather", "arguments": {"location": "New York", "unit": "fahrenheit"}}]}
232
+ ```
233
+
234
+ #### 2. Multi-turn use case
235
+
236
+ We also support multi-turn interaction with our model series. Here is the example of next round of interaction from the above example:
237
+
238
+ ````python
239
+ def parse_agent_action(agent_action: str):
240
+ """
241
+ Given an agent's action, parse it to add to conversation history
242
+ """
243
+ try: parsed_agent_action_json = json.loads(agent_action)
244
+ except: return "", []
245
+
246
+ if "thought" not in parsed_agent_action_json.keys(): thought = ""
247
+ else: thought = parsed_agent_action_json["thought"]
248
+
249
+ if "tool_calls" not in parsed_agent_action_json.keys(): tool_calls = []
250
+ else: tool_calls = parsed_agent_action_json["tool_calls"]
251
+
252
+ return thought, tool_calls
253
+
254
+ def update_conversation_history(conversation_history: list, agent_action: str, environment_response: str, user_input: str):
255
+ """
256
+ Update the conversation history list based on the new agent_action, environment_response, and/or user_input
257
+ """
258
+ thought, tool_calls = parse_agent_action(agent_action)
259
+ new_step_data = {
260
+ "step_id": len(conversation_history) + 1,
261
+ "thought": thought,
262
+ "tool_calls": tool_calls,
263
+ "step_id": len(conversation_history),
264
+ "next_observation": environment_response,
265
+ "user_input": user_input,
266
+ }
267
+
268
+ conversation_history.append(new_step_data)
269
+
270
+ def get_environment_response(agent_action: str):
271
+ """
272
+ Get the environment response for the agent_action
273
+ """
274
+ # TODO: add custom implementation here
275
+ error_message, response_message = "", ""
276
+ return {"error": error_message, "response": response_message}
277
+
278
+ # ------------- before here are the steps to get agent_response from the example above ----------
279
+
280
+ # 1. get the next state after agent's response:
281
+ # The next 2 lines are examples of getting environment response and user_input.
282
+ # It is depended on particular usage, we can have either one or both of those.
283
+ environment_response = get_environment_response(agent_action)
284
+ user_input = "Now, search on the Internet for cute puppies"
285
+
286
+ # 2. after we got environment_response and (or) user_input, we want to add to our conversation history
287
+ update_conversation_history(conversation_history, agent_action, environment_response, user_input)
288
+
289
+ # 3. we now can build the prompt
290
+ content = build_prompt(task_instruction, format_instruction, xlam_format_tools, query, conversation_history)
291
+
292
+ # 4. Now, we just retrieve the inputs for the LLM
293
+ messages=[
294
+ { 'role': 'user', 'content': content}
295
+ ]
296
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
297
+
298
+ # 5. Generate the outputs & decode
299
+ # tokenizer.eos_token_id is the id of <|EOT|> token
300
+ outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
301
+ agent_action = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
302
+ ````
303
+
304
+ This would be the corresponding output:
305
+ ```shell
306
+ {"thought": "I need to get the current weather for New York in fahrenheit.", "tool_calls": [{"name": "get_weather", "arguments": {"location": "New York", "unit": "fahrenheit"}}]}
307
+ ```
308
+
309
+ We highly recommend to use our provided prompt format and helper functions to yield the best function-calling performance of our model.
310
+
311
+ #### Example multi-turn prompt and output
312
+
313
+ Prompt:
314
+ ````json
315
+ [BEGIN OF TASK INSTRUCTION]
316
+ Based on the previous context and API request history, generate an API request or a response as an AI assistant.
317
+ [END OF TASK INSTRUCTION]
318
+
319
+ [BEGIN OF AVAILABLE TOOLS]
320
+ [
321
+ {
322
+ "name": "get_fire_info",
323
+ "description": "Query the latest wildfire information",
324
+ "parameters": {
325
+ "location": {
326
+ "type": "string",
327
+ "description": "Location of the wildfire, for example: 'California'",
328
+ "required": true,
329
+ "format": "free"
330
+ },
331
+ "radius": {
332
+ "type": "number",
333
+ "description": "The radius (in miles) around the location where the wildfire is occurring, for example: 10",
334
+ "required": false,
335
+ "format": "free"
336
+ }
337
+ }
338
+ },
339
+ {
340
+ "name": "get_hurricane_info",
341
+ "description": "Query the latest hurricane information",
342
+ "parameters": {
343
+ "name": {
344
+ "type": "string",
345
+ "description": "Name of the hurricane, for example: 'Irma'",
346
+ "required": true,
347
+ "format": "free"
348
+ }
349
+ }
350
+ },
351
+ {
352
+ "name": "get_earthquake_info",
353
+ "description": "Query the latest earthquake information",
354
+ "parameters": {
355
+ "magnitude": {
356
+ "type": "number",
357
+ "description": "The minimum magnitude of the earthquake that needs to be queried.",
358
+ "required": false,
359
+ "format": "free"
360
+ },
361
+ "location": {
362
+ "type": "string",
363
+ "description": "Location of the earthquake, for example: 'California'",
364
+ "required": false,
365
+ "format": "free"
366
+ }
367
+ }
368
+ }
369
+ ]
370
+ [END OF AVAILABLE TOOLS]
371
+
372
+ [BEGIN OF FORMAT INSTRUCTION]
373
+ Your output should be in the JSON format, which specifies a list of function calls. The example format is as follows. Please make sure the parameter type is correct. If no function call is needed, please make tool_calls an empty list '[]'.
374
+ ```{"thought": "the thought process, or an empty string", "tool_calls": [{"name": "api_name1", "arguments": {"argument1": "value1", "argument2": "value2"}}]}```
375
+ [END OF FORMAT INSTRUCTION]
376
+
377
+ [BEGIN OF QUERY]
378
+ User: Can you give me the latest information on the wildfires occurring in California?
379
+ [END OF QUERY]
380
+
381
+ [BEGIN OF HISTORY STEPS]
382
+ [
383
+ {
384
+ "thought": "Sure, what is the radius (in miles) around the location of the wildfire?",
385
+ "tool_calls": [],
386
+ "step_id": 1,
387
+ "next_observation": "",
388
+ "user_input": "User: Let me think... 50 miles."
389
+ },
390
+ {
391
+ "thought": "",
392
+ "tool_calls": [
393
+ {
394
+ "name": "get_fire_info",
395
+ "arguments": {
396
+ "location": "California",
397
+ "radius": 50
398
+ }
399
+ }
400
+ ],
401
+ "step_id": 2,
402
+ "next_observation": [
403
+ {
404
+ "location": "Los Angeles",
405
+ "acres_burned": 1500,
406
+ "status": "contained"
407
+ },
408
+ {
409
+ "location": "San Diego",
410
+ "acres_burned": 12000,
411
+ "status": "active"
412
+ }
413
+ ]
414
+ },
415
+ {
416
+ "thought": "Based on the latest information, there are wildfires in Los Angeles and San Diego. The wildfire in Los Angeles has burned 1,500 acres and is contained, while the wildfire in San Diego has burned 12,000 acres and is still active.",
417
+ "tool_calls": [],
418
+ "step_id": 3,
419
+ "next_observation": "",
420
+ "user_input": "User: Can you tell me about the latest earthquake?"
421
+ }
422
+ ]
423
+
424
+ [END OF HISTORY STEPS]
425
+ ````
426
+
427
+ Output:
428
+ ````json
429
+ {"thought": "", "tool_calls": [{"name": "get_earthquake_info", "arguments": {"location": "California"}}]}
430
+ ````
431
+
432
+
433
+ ## License
434
+ The model is distributed under the CC-BY-NC-4.0 license.
435
+
436
+ <!-- ## Citation
437
+
438
+ If you find this repo helpful, please cite our paper:
439
+ ```bibtex
440
+ ``` -->