fangchagnjun commited on
Commit
757b3bd
1 Parent(s): f197493

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -62
app.py CHANGED
@@ -1,63 +1,105 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+
5
+ # 加载 xLAM 模型和 tokenizer
6
+ model_name = "Salesforce/xLAM-7b-r"
7
+ model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype="auto", trust_remote_code=True)
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+
10
+ # 定义任务提示和格式提示
11
+ task_instruction = """
12
+ Based on the previous context and API request history, generate an API request or a response as an AI assistant.
13
+ """.strip()
14
+
15
+ format_instruction = """
16
+ The output should be of the JSON format, which specifies a list of generated function calls. If no function call is needed, please make tool_calls an empty list "[]".
17
+ """.strip()
18
+
19
+ # 定义工具信息
20
+ get_weather_api = {
21
+ "name": "get_weather",
22
+ "description": "Get the current weather for a location",
23
+ "parameters": {
24
+ "type": "object",
25
+ "properties": {
26
+ "location": {
27
+ "type": "string",
28
+ "description": "The city and state, e.g. San Francisco, New York"
29
+ },
30
+ "unit": {
31
+ "type": "string",
32
+ "enum": ["celsius", "fahrenheit"],
33
+ "description": "The unit of temperature to return"
34
+ }
35
+ },
36
+ "required": ["location"]
37
+ }
38
+ }
39
+
40
+ search_api = {
41
+ "name": "search",
42
+ "description": "Search for information on the internet",
43
+ "parameters": {
44
+ "type": "object",
45
+ "properties": {
46
+ "query": {
47
+ "type": "string",
48
+ "description": "The search query, e.g. 'latest news on AI'"
49
+ }
50
+ },
51
+ "required": ["query"]
52
+ }
53
+ }
54
+
55
+ # 转换工具为 xLAM 的格式
56
+ def convert_to_xlam_tool(tools):
57
+ if isinstance(tools, dict):
58
+ return {
59
+ "name": tools["name"],
60
+ "description": tools["description"],
61
+ "parameters": {k: v for k, v in tools["parameters"].get("properties", {}).items()}
62
+ }
63
+ elif isinstance(tools, list):
64
+ return [convert_to_xlam_tool(tool) for tool in tools]
65
+ else:
66
+ return tools
67
+
68
+ xlam_format_tools = convert_to_xlam_tool([get_weather_api, search_api])
69
+
70
+ # 生成提示
71
+ def build_prompt(task_instruction, format_instruction, tools, query):
72
+ prompt = f"[BEGIN OF TASK INSTRUCTION]\n{task_instruction}\n[END OF TASK INSTRUCTION]\n\n"
73
+ prompt += f"[BEGIN OF AVAILABLE TOOLS]\n{tools}\n[END OF AVAILABLE TOOLS]\n\n"
74
+ prompt += f"[BEGIN OF FORMAT INSTRUCTION]\n{format_instruction}\n[END OF FORMAT INSTRUCTION]\n\n"
75
+ prompt += f"[BEGIN OF QUERY]\n{query}\n[END OF QUERY]\n\n"
76
+ return prompt
77
+
78
+ # 定义模型推理函数
79
+ def generate_response(query):
80
+ # 构建输入提示
81
+ content = build_prompt(task_instruction, format_instruction, xlam_format_tools, query)
82
+ messages = [{'role': 'user', 'content': content}]
83
+
84
+ # 编码输入
85
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
86
+
87
+ # 生成输出
88
+ outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
89
+
90
+ # 解码输出
91
+ response = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
92
+ return response
93
+
94
+ # 使用 Gradio 创建简单的 Web 应用
95
+ with gr.Blocks() as demo:
96
+ gr.Markdown("## 使用 xLAM 模型进行智能对话")
97
+
98
+ query = gr.Textbox(label="输入您的问题", placeholder="请输入您的问题")
99
+ output = gr.Textbox(label="模型响应")
100
+
101
+ submit_btn = gr.Button("提交")
102
+ submit_btn.click(fn=generate_response, inputs=query, outputs=output)
103
+
104
+ # 启动 Gradio 应用
105
+ demo.launch()