File size: 1,597 Bytes
b405fea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb8313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b405fea
 
5eb8313
 
b405fea
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer

# Define the input schema
class ModelInput(BaseModel):
    prompt: str
    max_new_tokens: int = 50  # Optional: Defaults to 50 tokens

# Initialize FastAPI app
app = FastAPI()

# Load your model and tokenizer
model_path = "khurrameycon/SmolLM-135M-Instruct-qa_pairs_converted.json-25epochs"  # Update with your model directory
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path)

# Initialize the pipeline
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)

@app.post("/generate")

def generate_response(model, tokenizer, instruction):
    """Generate a response from the model based on an instruction."""
    messages = [{"role": "user", "content": instruction}]
    input_text = tokenizer.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    inputs = tokenizer.encode(input_text, return_tensors="pt")
    outputs = model.generate(
        inputs, max_new_tokens=128, temperature=0.2, top_p=0.9, do_sample=True
    )
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return response



def generate_text(input: ModelInput):
    try:
        response = generate_response(model, tokenizer, ModelInput)
        return response}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/")
def root():
    return {"message": "Welcome to the Hugging Face Model API!"}