Spaces:
Runtime error
Runtime error
Upload app.py with huggingface_hub
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from langserve import add_routes
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 5 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 6 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 7 |
+
from langchain_huggingface import HuggingFacePipeline
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
app = FastAPI(
|
| 12 |
+
title="Phi-3 Code Explainer API",
|
| 13 |
+
description="Explains Python code using the Phi-3 Mini model and LangChain.",
|
| 14 |
+
version="1.0"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
app.add_middleware(
|
| 18 |
+
CORSMiddleware,
|
| 19 |
+
allow_origins=["*"],
|
| 20 |
+
allow_credentials=True,
|
| 21 |
+
allow_methods=["*"],
|
| 22 |
+
allow_headers=["*"],
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
model_id = "microsoft/phi-3-mini-4k-instruct"
|
| 26 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 27 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 28 |
+
model_id, torch_dtype=torch.float16, device_map="auto"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
generator = pipeline(
|
| 32 |
+
"text-generation",
|
| 33 |
+
model=model,
|
| 34 |
+
tokenizer=tokenizer,
|
| 35 |
+
max_new_tokens=256,
|
| 36 |
+
return_full_text=False,
|
| 37 |
+
do_sample=False
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
llm = HuggingFacePipeline(pipeline=generator)
|
| 41 |
+
|
| 42 |
+
prompt = ChatPromptTemplate.from_template(
|
| 43 |
+
"### Instruction:\nExplain this Python code step-by-step:\nUse code with caution\n{code}\n\n### Explanation:"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
parser = StrOutputParser()
|
| 47 |
+
chain = prompt | llm | parser
|
| 48 |
+
|
| 49 |
+
add_routes(app, chain, path="/explain")
|