File size: 1,518 Bytes
8dd9dba
f8898c0
 
 
ef34ed3
f8898c0
642232a
f71bfa4
ef34ed3
 
 
8dd9dba
d04f77a
ef34ed3
 
 
 
 
 
 
 
 
 
8dd9dba
f8898c0
 
8dd9dba
f8898c0
 
8dd9dba
 
 
 
 
 
 
 
 
 
 
ef34ed3
 
 
 
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
from fastapi import FastAPI, Request
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import os

app = FastAPI()

# Create cache directory
os.makedirs("./model_cache", exist_ok=True)

# Load model and tokenizer once at startup
model_name = "distilgpt2"  # change this to your own model
try:
    # Try to load from local cache first
    tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir="./model_cache", local_files_only=False)
    model = AutoModelForCausalLM.from_pretrained(model_name, cache_dir="./model_cache", local_files_only=False)
except OSError as e:
    print(f"Error loading model: {e}")
    print("Attempting to download model directly...")
    # If that fails, try downloading explicitly
    tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir="./model_cache")
    model = AutoModelForCausalLM.from_pretrained(model_name, cache_dir="./model_cache")

class PromptRequest(BaseModel):
    prompt: str
    max_new_tokens: int = 50

@app.post("/generate")
async def generate_text(req: PromptRequest):
    inputs = tokenizer(req.prompt, return_tensors="pt")
    outputs = model.generate(
        **inputs,
        max_new_tokens=req.max_new_tokens,
        do_sample=True,
        temperature=0.8,
        top_p=0.95,
    )
    generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return {"generated_text": generated}

@app.get("/")
async def root():
    return {"status": "API is running", "model": model_name}