Update app.py
Browse files123456789101112131415161718192 unmodified lines22232425262728293031323334353637383940414243444546474849505152535455565758import torchfrom flask import Flask, request, Response, render_templatefrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamerfrom threading import Threadapp = Flask(__name__)# 1. Load the Model and Tokenizer# The sources highlight that the LLM serves as the cognitive core or "brain" [5, 6].model_id = "AshokGakr/model-tiny"tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained(model_id,torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,device_map="auto")@app.route('/')def index():2 unmodified lines@app.route('/chat', methods=['POST'])def chat():data = request.jsonuser_messages = data.get("messages", [])# 2. Apply Chat Template# Using the specific Jinja template from the model repo to format the prompt.# This ensures the model follows the intended "Thought-Action-Observation" cycle [7].input_ids = tokenizer.apply_chat_template(user_messages,add_generation_prompt=True,return_tensors="pt").to(model.device)# 3. Setup Streaming# Context engineering involves curating the optimal set of tokens for inference [8].streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)generation_kwargs = dict(input_ids=input_ids,streamer=streamer,max_new_tokens=512,do_sample=True,temperature=0.7)# Run generation in a separate thread to allow the Flask response to streamthread = Thread(target=model.generate, kwargs=generation_kwargs)thread.start()def generate():for new_text in streamer:yield new_textreturn Response(generate(), mimetype='text/plain')if __name__ == '__main__':app.run(host='0.0.0.0', port=7860) # Standard HF Space port123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051522 unmodified lines555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import torchimport jsonimport reimport datetimefrom flask import Flask, request, Response, render_templatefrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamerfrom threading import Threadapp = Flask(__name__)# 1. TOOL DEFINITIONSdef get_current_datetime(query: str = ""):"""Returns the current date and time."""return f"Observation: The current date and time is {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}."def simple_calculator(expression: str):"""An easy-to-construct tool for basic math (add, sub, mult, div)."""try:# Source 351: Calculators are essential tools for deterministic results.# Note: In production, use a safer math parser instead of eval.result = eval(expression, {"__builtins__": None}, {})return f"Observation: The calculation result is {result}."except Exception as e:return f"Observation: Error in calculation: {str(e)}."# Tool Registrytools = {"get_current_datetime": get_current_datetime,"simple_calculator": simple_calculator}# Load Modelmodel_id = "AshokGakr/model-tiny"tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")SYSTEM_PROMPT = """ROLE: You are a ReAct Agent. You solve tasks using this loop:Thought: (Reasoning about what to do)Action: (Tool name: 'get_current_datetime' or 'simple_calculator')Action Input: (Parameter for the tool)Observation: (Result from the tool - provided to you)... (Repeat Thought/Action/Observation if needed)Final Answer: (The final response to the user)AVAILABLE TOOLS:- get_current_datetime: Use this for any questions about the current date or time. No input needed.- simple_calculator: Use this for any math calculations. Input should be a math expression (e.g., '10 + 5')."""@app.route('/')def index():2 unmodified lines@app.route('/chat', methods=['POST'])def chat():data = request.jsonuser_query = data.get("message", "")def generate_agent_response():# Source 13: Episodic memory maintains the conversation trajectory.history = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_query}]for i in range(5): # Limit iterations to prevent infinite loops [5]input_ids = tokenizer.apply_chat_template(history, add_generation_prompt=True, return_tensors="pt").to(model.device)streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)thread = Thread(target=model.generate, kwargs={"input_ids": input_ids, "streamer": streamer, "max_new_tokens": 256})thread.start()full_turn_output = ""for new_text in streamer:full_turn_output += new_textyield new_text # Stream thoughts to the UI [6]# Check for Action [7]action_match = re.search(r"Action:\s*(\w+)", full_turn_output)input_match = re.search(r"Action Input:\s*(.*)", full_turn_output)if action_match and input_match:tool_name = action_match.group(1).strip()tool_input = input_match.group(1).strip()if tool_name in tools:obs = tools[tool_name](tool_input)yield f"\n{obs}\n"# Feed observation back into history [8, 9]history.append({"role": "assistant", "content": full_turn_output})history.append({"role": "user", "content": obs})else:breakelif "Final Answer:" in full_turn_output:breakelse:breakreturn Response(generate_agent_response(), mimetype='text/plain')if __name__ == '__main__':app.run(host='0.0.0.0', port=7860)
app.py+81-39