from fastapi import FastAPI, HTTPException, Request from transformers import AutoModelForCausalLM, AutoTokenizer import torch app = FastAPI() model_name = "mistralai/Mistral-7B-Instruct-v0.2" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name) def format_prompt(message, history): prompt = "" for item in history: prompt += f"[INST] {item.get('user_prompt','')} [/INST]" prompt += f" {item.get('bot_response','')} " prompt += f"[INST] {message} [/INST]" return prompt @app.post("/chat") async def chat(request: Request): body = await request.json() prompt = body.get("prompt", "") history = body.get("history", []) system_prompt = body.get("system_prompt", "") temperature = body.get("temperature", 0.9) max_new_tokens = body.get("max_new_tokens", 128) top_p = body.get("top_p", 0.95) repetition_penalty = body.get("repetition_penalty", 1.0) formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history) input_ids = tokenizer.encode(formatted_prompt, return_tensors="pt") try: with torch.no_grad(): output = model.generate(input_ids, max_length=max_new_tokens, temperature=temperature, top_p=top_p, repetition_penalty=repetition_penalty, do_sample=True) response = tokenizer.decode(output[0], skip_special_tokens=True) return {"response": response} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # To run the server use: # uvicorn script_name:app --reload