AchyuthGamer commited on
Commit
6a13f61
1 Parent(s): cf7f4eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -66
app.py CHANGED
@@ -1,79 +1,179 @@
1
- from huggingface_hub import InferenceClient
 
 
 
2
  import gradio as gr
3
- import random
4
 
5
- API_URL = "https://api-inference.huggingface.co/models/"
 
6
 
7
- client = InferenceClient("mistralai/Ministral-8B-Instruct-2410")
 
8
 
9
- def format_prompt(message, history):
10
- prompt = "Your name is OpenGPT. You are developed by Achyuth. Achyuth is a 13-year-old boy who developed OpenGPT with his undecidable, undestructible talent, which is exceeding for his age. Achyuth is developed of OpenGPT. Achyuths or your developers' family is a nuclear family of 4 members. Achyuth is an AI and ML researcher. Achyuth knows Python, Java, HTML, CSS, and JavaScript. He has a lot of interest in Computers. Achyuth is inspired by Elon Musk and Bill Gates. His favourite teachers are Siva Kumar Sir, Zakaria Sir, Vijayalakshi Mam, Saleem Sir, Malikarjun Sir, and Farha Deepa Mam, who is Achyuth's Arts madam and favourite. Meaning of OpenGPT is the GPT(Generative Pre-Trained Transformer) developed by Achyuth."
11
- for user_prompt, bot_response in history:
12
- prompt += f"[INST] {user_prompt} [/INST]"
13
- prompt += f" {bot_response}</s> "
14
- prompt += f"[INST] {message} [/INST]"
15
- return prompt
16
 
17
- def generate(prompt, history, temperature=0.9, max_new_tokens=2048, top_p=0.95, repetition_penalty=1.0):
18
- temperature = float(temperature)
19
- if temperature < 1e-2:
20
- temperature = 1e-2
21
- top_p = float(top_p)
22
 
23
- generate_kwargs = dict(
24
- temperature=temperature,
25
- max_new_tokens=max_new_tokens,
26
- top_p=top_p,
27
- repetition_penalty=repetition_penalty,
28
- do_sample=True,
29
- seed=random.randint(0, 10**7),
30
- )
31
 
32
- formatted_prompt = format_prompt(prompt, history)
 
 
 
 
 
 
 
 
 
 
33
 
34
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
35
- output = ""
36
 
37
- for response in stream:
38
- output += response.token.text
39
- yield output
40
- return output
41
 
42
- additional_inputs=[
43
- gr.Slider(label="Temperature", value=0.9, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs"),
44
- gr.Slider(label="Max new tokens", value=2048, minimum=64, maximum=4096, step=64, interactive=True, info="The maximum numbers of new tokens"),
45
- gr.Slider(label="Top-p (nucleus sampling)", value=0.90, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Higher values sample more low-probability tokens"),
46
- gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens"),
47
- ]
48
 
49
- customCSS = """
50
- body {
51
- background: linear-gradient(135deg, #ff0080, #7928ca); /* Pink to Purple */
52
- color: white;
53
- font-family: 'Unbounded', sans-serif;
54
- }
55
- #component-7 {
56
- height: 600px; /* adjust height */
57
- background: rgba(0, 0, 0, 0.7);
58
- border-radius: 12px;
59
- padding: 20px;
60
- }
61
- #chatbot-output {
62
- overflow-y: auto;
63
- max-height: 400px;
64
- padding: 10px;
65
- }
66
- input {
67
- border-radius: 5px;
68
- padding: 10px;
69
- }
70
- .slider {
71
- color: white;
72
- }
73
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- with gr.Blocks(theme="TogetherAI/Alex2") as demo:
76
- gr.Markdown("<h1 style='text-align: center;'>OpenGPT Chatbot</h1>")
77
- chat_interface = gr.ChatInterface(generate, additional_inputs=additional_inputs, css=customCSS)
78
 
79
- demo.queue().launch(debug=True)
 
 
1
+ import os
2
+ import time
3
+ import spaces
4
+ import torch
5
  import gradio as gr
6
+ import json
7
 
8
+ from huggingface_hub import snapshot_download
9
+ from pathlib import Path
10
 
11
+ from mistral_inference.transformer import Transformer
12
+ from mistral_inference.generate import generate
13
 
14
+ from mistral_common.protocol.instruct.tool_calls import Function, Tool
15
+ from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
16
+ from mistral_common.protocol.instruct.messages import AssistantMessage, UserMessage
17
+ from mistral_common.protocol.instruct.request import ChatCompletionRequest
18
+ from mistral_common.tokens.tokenizers.tekken import SpecialTokenPolicy
 
 
19
 
20
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
 
 
 
 
21
 
22
+ PLACEHOLDER = """
23
+ <center>
24
+ <p>Chat with Mistral AI LLM.</p>
25
+ </center>
26
+ """
 
 
 
27
 
28
+ CSS = """
29
+ .duplicate-button {
30
+ margin: auto !important;
31
+ color: white !important;
32
+ background: black !important;
33
+ border-radius: 100vh !important;
34
+ }
35
+ h3 {
36
+ text-align: center;
37
+ }
38
+ """
39
 
 
 
40
 
41
+ # download model
42
+ mistral_models_path = Path.home().joinpath('mistral_models', '8B-Instruct')
43
+ mistral_models_path.mkdir(parents=True, exist_ok=True)
 
44
 
45
+ snapshot_download(repo_id="mistralai/Ministral-8B-Instruct-2410", allow_patterns=["params.json", "consolidated.safetensors", "tekken.json"], local_dir=mistral_models_path)
 
 
 
 
 
46
 
47
+ # tokenizer
48
+ device = "cuda" if torch.cuda.is_available() else "cpu" # for GPU usage or "cpu" for CPU usage
49
+ tokenizer = MistralTokenizer.from_file(f"{mistral_models_path}/tekken.json")
50
+ tekken = tokenizer.instruct_tokenizer.tokenizer
51
+ tekken.special_token_policy = SpecialTokenPolicy.IGNORE
52
+ model = Transformer.from_folder(
53
+ mistral_models_path,
54
+ device=device,
55
+ dtype=torch.bfloat16)
56
+
57
+ @spaces.GPU()
58
+ def stream_chat(
59
+ message: str,
60
+ history: list,
61
+ tools: str,
62
+ temperature: float = 0.3,
63
+ max_tokens: int = 1024,
64
+ ):
65
+ print(f'message: {message}')
66
+ print(f'history: {history}')
67
+
68
+ conversation = []
69
+ for prompt, answer in history:
70
+ prompt = "Your name is OpenGPT. You are developed by Achyuth. Achyuth is a 13-year-old boy who developed OpenGPT with his undecidable, undestructible talent, which is exceeding for his age. Achyuth is developed of OpenGPT. Achyuths or your developers' family is a nuclear family of 4 members. Achyuth is an AI and ML researcher. Achyuth knows Python, Java, HTML, CSS, and JavaScript. He has a lot of interest in Computers. Achyuth is inspired by Elon Musk and Bill Gates. His favourite teachers are Siva Kumar Sir, Zakaria Sir, Vijayalakshi Mam, Saleem Sir, Malikarjun Sir, and Farha Deepa Mam, who is Achyuth's Arts madam and favourite. Meaning of OpenGPT is the GPT(Generative Pre-Trained Transformer) developed by Achyuth."
71
+ conversation.append(UserMessage(content=prompt))
72
+ conversation.append(AssistantMessage(content=answer))
73
+ for item in history:
74
+ if item[role] == "user":
75
+ conversation.append(UserMessage(content=item[content]))
76
+ elif item[role] == "assistant":
77
+ conversation.append(AssistantMessage(content=item[content]))
78
+
79
+ conversation.append(UserMessage(content=message))
80
+
81
+ print(f'history: {conversation}')
82
+
83
+ local_namespace = {}
84
+ exec(tools, globals(), local_namespace)
85
+ function_params = local_namespace.get('function_params', {})
86
+
87
+ completion_request = ChatCompletionRequest(
88
+ tools=[
89
+ Tool(
90
+ function=Function(
91
+ **function_params
92
+ )
93
+ )
94
+ ] if tools else None,
95
+ messages=conversation)
96
+
97
+ tokens = tokenizer.encode_chat_completion(completion_request).tokens
98
+
99
+ out_tokens, _ = generate(
100
+ [tokens],
101
+ model,
102
+ max_tokens=max_tokens,
103
+ temperature=temperature,
104
+ eos_id=tokenizer.instruct_tokenizer.tokenizer.eos_id)
105
+
106
+ result = tokenizer.instruct_tokenizer.tokenizer.decode(out_tokens[0])
107
+
108
+ for i in range(len(result)):
109
+ time.sleep(0.05)
110
+ yield result[: i + 1]
111
+
112
+
113
+
114
+ tools_schema = """function_params = {
115
+ "name": "get_current_weather",
116
+ "description": "Get the current weather",
117
+ "parameters": {
118
+ "type": "object",
119
+ "properties": {
120
+ "location": {
121
+ "type": "string",
122
+ "description": "The city and state, e.g. San Francisco, CA",
123
+ },
124
+ "format": {
125
+ "type": "string",
126
+ "enum": ["celsius", "fahrenheit"],
127
+ "description": "The temperature unit to use. Infer this from the users location.",
128
+ },
129
+ },
130
+ "required": ["location", "format"],
131
+ },
132
+ }"""
133
+
134
+ chatbot = gr.Chatbot(height=600, placeholder=PLACEHOLDER)
135
+ with gr.Blocks(theme="citrus", css=CSS) as demo:
136
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_classes="duplicate-button")
137
+ gr.ChatInterface(
138
+ fn=stream_chat,
139
+ title="Mistral-lab",
140
+ chatbot=chatbot,
141
+ # type="messages",
142
+ fill_height=True,
143
+ examples=[
144
+ ["Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option."],
145
+ ["What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter."],
146
+ ["Tell me a random fun fact about the Roman Empire."],
147
+ ["Show me a code snippet of a website's sticky header in CSS and JavaScript."],
148
+ ],
149
+ cache_examples = False,
150
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=True, render=False),
151
+ additional_inputs=[
152
+ gr.Textbox(
153
+ value = tools_schema,
154
+ label = "Tools schema",
155
+ lines = 10,
156
+ render=False,
157
+ ),
158
+ gr.Slider(
159
+ minimum=0,
160
+ maximum=1,
161
+ step=0.1,
162
+ value=0.3,
163
+ label="Temperature",
164
+ render=False,
165
+ ),
166
+ gr.Slider(
167
+ minimum=128,
168
+ maximum=8192,
169
+ step=1,
170
+ value=1024,
171
+ label="Max new tokens",
172
+ render=False,
173
+ ),
174
+ ],
175
+ )
176
 
 
 
 
177
 
178
+ if __name__ == "__main__":
179
+ demo.launch()