from fastapi import FastAPI from pydantic import BaseModel from transformers import AutoTokenizer, AutoModelForCausalLM import os model_name = "meta-llama/Llama-3.1-8B-Instruct" # Use the Hugging Face token from the environment variable hf_token = os.getenv("HF_TOKEN") tokenizer = AutoTokenizer.from_pretrained(model_name, token=hf_token) model = AutoModelForCausalLM.from_pretrained(model_name, token=hf_token) app = FastAPI() class Prompt(BaseModel): text: str @app.post("/generate") def generate_text(prompt: Prompt): inputs = tokenizer(prompt.text, return_tensors="pt") outputs = model.generate(**inputs, max_length=100) generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True) return {"generated_text": generated_text}