Views
No views yet

| Model | # Total Params | Context Length | Download Model | Download GGUF files |
|---|---|---|---|---|
| xLAM-1b-fc-r | 1.35B | 16k | 🤗 Link | 🤗 Link |
| xLAM-7b-fc-r | 6.91B | 4k | 🤗 Link | 🤗 Link |
| xLAM-7b-r | 7.24B | 32k | 🤗 Link | -- |
| xLAM-8x7b-r | 46.7B | 32k | 🤗 Link | -- |
| xLAM-8x22b-r | 141B | 64k | 🤗 Link | -- |
fc series here.transformers library:pip install transformers>=4.41.01import json
2import torch
3from transformers import AutoModelForCausalLM, AutoTokenizer
4
5torch.random.manual_seed(0)
6
7model_name = "Salesforce/xLAM-7b-r"
8model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype="auto", trust_remote_code=True)
9tokenizer = AutoTokenizer.from_pretrained(model_name)
10
11# Please use our provided instruction prompt for best performance
12task_instruction = """
13Based on the previous context and API request history, generate an API request or a response as an AI assistant.""".strip()
14
15format_instruction = """
16The 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
17tool_calls an empty list "[]".
18```
19{"thought": "the thought process, or an empty string", "tool_calls": [{"name": "api_name1", "arguments": {"argument1": "value1", "argument2": "value2"}}]}
20```
21""".strip()
22
23# Define the input query and available tools
24query = "What's the weather like in New York in fahrenheit?"
25
26get_weather_api = {
27 "name": "get_weather",
28 "description": "Get the current weather for a location",
29 "parameters": {
30 "type": "object",
31 "properties": {
32 "location": {
33 "type": "string",
34 "description": "The city and state, e.g. San Francisco, New York"
35 },
36 "unit": {
37 "type": "string",
38 "enum": ["celsius", "fahrenheit"],
39 "description": "The unit of temperature to return"
40 }
41 },
42 "required": ["location"]
43 }
44}
45
46search_api = {
47 "name": "search",
48 "description": "Search for information on the internet",
49 "parameters": {
50 "type": "object",
51 "properties": {
52 "query": {
53 "type": "string",
54 "description": "The search query, e.g. 'latest news on AI'"
55 }
56 },
57 "required": ["query"]
58 }
59}
60
61openai_format_tools = [get_weather_api, search_api]
62
63# Helper function to convert openai format tools to our more concise xLAM format
64def convert_to_xlam_tool(tools):
65 ''''''
66 if isinstance(tools, dict):
67 return {
68 "name": tools["name"],
69 "description": tools["description"],
70 "parameters": {k: v for k, v in tools["parameters"].get("properties", {}).items()}
71 }
72 elif isinstance(tools, list):
73 return [convert_to_xlam_tool(tool) for tool in tools]
74 else:
75 return tools
76
77def build_conversation_history_prompt(conversation_history: str):
78 parsed_history = []
79 for step_data in conversation_history:
80 parsed_history.append({
81 "step_id": step_data["step_id"],
82 "thought": step_data["thought"],
83 "tool_calls": step_data["tool_calls"],
84 "next_observation": step_data["next_observation"],
85 "user_input": step_data['user_input']
86 })
87
88 history_string = json.dumps(parsed_history)
89 return f"\n[BEGIN OF HISTORY STEPS]\n{history_string}\n[END OF HISTORY STEPS]\n"
90
91
92# Helper function to build the input prompt for our model
93def build_prompt(task_instruction: str, format_instruction: str, tools: list, query: str, conversation_history: list):
94 prompt = f"[BEGIN OF TASK INSTRUCTION]\n{task_instruction}\n[END OF TASK INSTRUCTION]\n\n"
95 prompt += f"[BEGIN OF AVAILABLE TOOLS]\n{json.dumps(xlam_format_tools)}\n[END OF AVAILABLE TOOLS]\n\n"
96 prompt += f"[BEGIN OF FORMAT INSTRUCTION]\n{format_instruction}\n[END OF FORMAT INSTRUCTION]\n\n"
97 prompt += f"[BEGIN OF QUERY]\n{query}\n[END OF QUERY]\n\n"
98
99 if len(conversation_history) > 0: prompt += build_conversation_history_prompt(conversation_history)
100 return prompt
101
102# Build the input and start the inference
103xlam_format_tools = convert_to_xlam_tool(openai_format_tools)
104
105conversation_history = []
106content = build_prompt(task_instruction, format_instruction, xlam_format_tools, query, conversation_history)
107
108messages=[
109 { 'role': 'user', 'content': content}
110]
111
112inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
113
114# tokenizer.eos_token_id is the id of <|EOT|> token
115outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
116agent_action = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True){"thought": "I need to get the current weather for New York in fahrenheit.", "tool_calls": [{"name": "get_weather", "arguments": {"location": "New York", "unit": "fahrenheit"}}]}1def parse_agent_action(agent_action: str):
2 """
3 Given an agent's action, parse it to add to conversation history
4 """
5 try: parsed_agent_action_json = json.loads(agent_action)
6 except: return "", []
7
8 if "thought" not in parsed_agent_action_json.keys(): thought = ""
9 else: thought = parsed_agent_action_json["thought"]
10
11 if "tool_calls" not in parsed_agent_action_json.keys(): tool_calls = []
12 else: tool_calls = parsed_agent_action_json["tool_calls"]
13
14 return thought, tool_calls
15
16def update_conversation_history(conversation_history: list, agent_action: str, environment_response: str, user_input: str):
17 """
18 Update the conversation history list based on the new agent_action, environment_response, and/or user_input
19 """
20 thought, tool_calls = parse_agent_action(agent_action)
21 new_step_data = {
22 "step_id": len(conversation_history) + 1,
23 "thought": thought,
24 "tool_calls": tool_calls,
25 "step_id": len(conversation_history),
26 "next_observation": environment_response,
27 "user_input": user_input,
28 }
29
30 conversation_history.append(new_step_data)
31
32def get_environment_response(agent_action: str):
33 """
34 Get the environment response for the agent_action
35 """
36 # TODO: add custom implementation here
37 error_message, response_message = "", ""
38 return {"error": error_message, "response": response_message}
39
40# ------------- before here are the steps to get agent_response from the example above ----------
41
42# 1. get the next state after agent's response:
43# The next 2 lines are examples of getting environment response and user_input.
44# It is depended on particular usage, we can have either one or both of those.
45environment_response = get_environment_response(agent_action)
46user_input = "Now, search on the Internet for cute puppies"
47
48# 2. after we got environment_response and (or) user_input, we want to add to our conversation history
49update_conversation_history(conversation_history, agent_action, environment_response, user_input)
50
51# 3. we now can build the prompt
52content = build_prompt(task_instruction, format_instruction, xlam_format_tools, query, conversation_history)
53
54# 4. Now, we just retrieve the inputs for the LLM
55messages=[
56 { 'role': 'user', 'content': content}
57]
58inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
59
60# 5. Generate the outputs & decode
61# tokenizer.eos_token_id is the id of <|EOT|> token
62outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
63agent_action = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True){"thought": "I need to get the current weather for New York in fahrenheit.", "tool_calls": [{"name": "get_weather", "arguments": {"location": "New York", "unit": "fahrenheit"}}]}1[BEGIN OF TASK INSTRUCTION]
2Based on the previous context and API request history, generate an API request or a response as an AI assistant.
3[END OF TASK INSTRUCTION]
4
5[BEGIN OF AVAILABLE TOOLS]
6[
7 {
8 "name": "get_fire_info",
9 "description": "Query the latest wildfire information",
10 "parameters": {
11 "location": {
12 "type": "string",
13 "description": "Location of the wildfire, for example: 'California'",
14 "required": true,
15 "format": "free"
16 },
17 "radius": {
18 "type": "number",
19 "description": "The radius (in miles) around the location where the wildfire is occurring, for example: 10",
20 "required": false,
21 "format": "free"
22 }
23 }
24 },
25 {
26 "name": "get_hurricane_info",
27 "description": "Query the latest hurricane information",
28 "parameters": {
29 "name": {
30 "type": "string",
31 "description": "Name of the hurricane, for example: 'Irma'",
32 "required": true,
33 "format": "free"
34 }
35 }
36 },
37 {
38 "name": "get_earthquake_info",
39 "description": "Query the latest earthquake information",
40 "parameters": {
41 "magnitude": {
42 "type": "number",
43 "description": "The minimum magnitude of the earthquake that needs to be queried.",
44 "required": false,
45 "format": "free"
46 },
47 "location": {
48 "type": "string",
49 "description": "Location of the earthquake, for example: 'California'",
50 "required": false,
51 "format": "free"
52 }
53 }
54 }
55]
56[END OF AVAILABLE TOOLS]
57
58[BEGIN OF FORMAT INSTRUCTION]
59Your 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 '[]'.
60```{"thought": "the thought process, or an empty string", "tool_calls": [{"name": "api_name1", "arguments": {"argument1": "value1", "argument2": "value2"}}]}```
61[END OF FORMAT INSTRUCTION]
62
63[BEGIN OF QUERY]
64User: Can you give me the latest information on the wildfires occurring in California?
65[END OF QUERY]
66
67[BEGIN OF HISTORY STEPS]
68[
69 {
70 "thought": "Sure, what is the radius (in miles) around the location of the wildfire?",
71 "tool_calls": [],
72 "step_id": 1,
73 "next_observation": "",
74 "user_input": "User: Let me think... 50 miles."
75 },
76 {
77 "thought": "",
78 "tool_calls": [
79 {
80 "name": "get_fire_info",
81 "arguments": {
82 "location": "California",
83 "radius": 50
84 }
85 }
86 ],
87 "step_id": 2,
88 "next_observation": [
89 {
90 "location": "Los Angeles",
91 "acres_burned": 1500,
92 "status": "contained"
93 },
94 {
95 "location": "San Diego",
96 "acres_burned": 12000,
97 "status": "active"
98 }
99 ]
100 },
101 {
102 "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.",
103 "tool_calls": [],
104 "step_id": 3,
105 "next_observation": "",
106 "user_input": "User: Can you tell me about the latest earthquake?"
107 }
108]
109
110[END OF HISTORY STEPS]{"thought": "", "tool_calls": [{"name": "get_earthquake_info", "arguments": {"location": "California"}}]}