import spaces import gradio as gr import torch from transformers import AutoModelForCausalLM, AutoTokenizer # 定义系统提示语 system_prompt = """You are Skywork-o1, a thinking model developed by Skywork AI, specializing in solving complex problems involving mathematics, coding, and logical reasoning through deep thought. When faced with a user's request, you first engage in a lengthy and in-depth thinking process to explore possible solutions to the problem. After completing your thoughts, you then provide a detailed explanation of the solution process in your response.""" # 初始化模型和分词器 model_name = "Skywork/Skywork-o1-Open-Llama-3.1-8B" model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype="auto", device_map="auto" ) tokenizer = AutoTokenizer.from_pretrained(model_name) # 定义生成回复的函数 @spaces.GPU def respond( message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, ): # 构造对话历史 conversation = [{"role": "system", "content": system_message}] for user_msg, assistant_msg in history: if user_msg: conversation.append({"role": "user", "content": user_msg}) if assistant_msg: conversation.append({"role": "assistant", "content": assistant_msg}) conversation.append({"role": "user", "content": message}) # 构造输入 input_ids = tokenizer.apply_chat_template( conversation, tokenize=True, add_generation_prompt=True, return_tensors="pt" ).to(model.device) # 模型生成 generation = model.generate( input_ids=input_ids, max_new_tokens=max_tokens, do_sample=True, temperature=temperature, top_p=top_p, pad_token_id=tokenizer.pad_token_id, ) # 解码生成内容 completion = tokenizer.decode( generation[0][len(input_ids[0]):], skip_special_tokens=True, clean_up_tokenization_spaces=True ) return completion # 定义Gradio界面 demo = gr.ChatInterface( fn=respond, additional_inputs=[ gr.Textbox(value=system_prompt, label="System message"), gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)" ), ], # chatbot_style="default" ) if __name__ == "__main__": demo.launch()