Spaces:
Build error
Build error
Update app.py
Browse files2 unmodified lines34567891 unmodified line11121314151617181925 unmodified lines45464748495051525354555657585960616212 unmodified lines7576777879808182838485868788893 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351362 unmodified linesimport spacesimport torchimport gradio as grfrom threading import Threadfrom huggingface_hub import snapshot_downloadfrom pathlib import Path1 unmodified linefrom mistral_inference.transformer import Transformerfrom mistral_inference.generate import generatefrom mistral_common.tokens.tokenizers.mistral import MistralTokenizerfrom mistral_common.protocol.instruct.messages import AssistantMessage, UserMessagefrom mistral_common.protocol.instruct.request import ChatCompletionRequestHF_TOKEN = os.environ.get("HF_TOKEN", None)25 unmodified lines# tokenizerdevice = "cuda" if torch.cuda.is_available() else "cpu" # for GPU usage or "cpu" for CPU usagetokenizer = MistralTokenizer.from_file(f"{mistral_models_path}/tekken.json")model = Transformer.from_folder(mistral_models_path,device=device,dtype=torch.bfloat16)@spaces.GPU()def stream_chat(message: str,history: list,temperature: float = 0.3,max_new_tokens: int = 1024,):print(f'message: {message}')print(f'history: {history}')12 unmodified linesconversation.append(UserMessage(content=message))print(f'history: {conversation}')completion_request = ChatCompletionRequest(messages=conversation)tokens = tokenizer.encode_chat_completion(completion_request).tokensout_tokens, _ = generate([tokens],model,max_tokens=max_new_tokens,temperature=temperature,eos_id=tokenizer.instruct_tokenizer.tokenizer.eos_id)3 unmodified linestime.sleep(0.05)yield result[: i + 1]chatbot = gr.Chatbot(height=600, placeholder=PLACEHOLDER)with gr.Blocks(theme="citrus", css=CSS) as demo:gr.DuplicateButton(value="Duplicate Space for private use", elem_classes="duplicate-button")gr.ChatInterface(fn=stream_chat,title="Mistral-lab",chatbot=chatbot,# type="messages",fill_height=True,examples=[["Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option."],["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."],["Tell me a random fun fact about the Roman Empire."],["Show me a code snippet of a website's sticky header in CSS and JavaScript."],],cache_examples = False,additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),additional_inputs=[gr.Slider(minimum=0,maximum=1,step=0.1,value=0.3,label="Temperature",render=False,),gr.Slider(minimum=128,maximum=8192,step=1,value=1024,label="Max new tokens",render=False,),],)if __name__ == "__main__":demo.launch()2 unmodified lines34567891 unmodified line111213141516171819202125 unmodified lines474849505152535455565758596061626364656612 unmodified lines7980818283848586878889909192939495969798991001011021031041053 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791802 unmodified linesimport spacesimport torchimport gradio as grimport jsonfrom huggingface_hub import snapshot_downloadfrom pathlib import Path1 unmodified linefrom mistral_inference.transformer import Transformerfrom mistral_inference.generate import generatefrom mistral_common.protocol.instruct.tool_calls import Function, Toolfrom mistral_common.tokens.tokenizers.mistral import MistralTokenizerfrom mistral_common.protocol.instruct.messages import AssistantMessage, UserMessagefrom mistral_common.protocol.instruct.request import ChatCompletionRequestfrom mistral_common.tokens.tokenizers.tekken import SpecialTokenPolicyHF_TOKEN = os.environ.get("HF_TOKEN", None)25 unmodified lines# tokenizerdevice = "cuda" if torch.cuda.is_available() else "cpu" # for GPU usage or "cpu" for CPU usagetokenizer = MistralTokenizer.from_file(f"{mistral_models_path}/tekken.json")tekken = tokenizer.instruct_tokenizer.tokenizertekken.special_token_policy = SpecialTokenPolicy.IGNOREmodel = Transformer.from_folder(mistral_models_path,device=device,dtype=torch.bfloat16)@spaces.GPU()def stream_chat(message: str,history: list,tools: str,temperature: float = 0.3,max_tokens: int = 1024,):print(f'message: {message}')print(f'history: {history}')12 unmodified linesconversation.append(UserMessage(content=message))print(f'history: {conversation}')local_namespace = {}exec(tools, globals(), local_namespace)function_params = local_namespace.get('function_params', {})completion_request = ChatCompletionRequest(tools=[Tool(function=Function(**function_params))] if tools else None,messages=conversation)tokens = tokenizer.encode_chat_completion(completion_request).tokensout_tokens, _ = generate([tokens],model,max_tokens=max_tokens,temperature=temperature,eos_id=tokenizer.instruct_tokenizer.tokenizer.eos_id)3 unmodified linestime.sleep(0.05)yield result[: i + 1]tools_schema = """function_params = {name="get_current_weather",description="Get the current weather",parameters={"type": "object","properties": {"location": {"type": "string","description": "The city and state, e.g. San Francisco, CA",},"format": {"type": "string","enum": ["celsius", "fahrenheit"],"description": "The temperature unit to use. Infer this from the users location.",},},"required": ["location", "format"],},}"""with gr.Blocks(theme="citrus", css=CSS) as demo:gr.DuplicateButton(value="Duplicate Space for private use", elem_classes="duplicate-button")chatbot = gr.Chatbot(height=600,placeholder=PLACEHOLDER,examples=[{'text': "Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option."},{'text': "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."},{'text': "Tell me a random fun fact about the Roman Empire."},{'text': "Show me a code snippet of a website's sticky header in CSS and JavaScript."},])msg = gr.Textbox(value = "",label = "Chat")with gr.Row():send = gr.Button(value = "Send",size="lg",variant = "primary",)clear = gr.ClearButton([msg, chatbot])with gr.Accordion(label="⚙️ Parameters", open=True,):tools = gr.Textbox(value = tools_schema,lable = "Tools schema",)temperature = gr.Slider(minimum=0,maximum=1,step=0.1,value=0.3,label="Temperature",),max_tokens = gr.Slider(minimum=128,maximum=8192,step=1,value=1024,label="Max new tokens",)msg.submit(fn = stream_chat, inputs = [msg, chatbot, tools, temperature, max_tokens], outputs = [chatbot])send.click(fn = stream_chat, inputs = [msg, chatbot, tools, temperature, max_tokens], outputs = [chatbot])if __name__ == "__main__":demo.launch()
app.py+84-40