Spaces:
No application file
No application file
Download main.py from nitin1009/local-test: direct link, hf CLI and curl.
- Browser
- Download file 2.2 kB
-
https://huggingface.co/spaces/nitin1009/local-test/resolve/main/main.py
- Command line
-
hf download hf://spaces/nitin1009/local-test/main.py
-
curl -L -o main.py https://huggingface.co/spaces/nitin1009/local-test/resolve/main/main.py
2.2 kB
| import os | |
| import requests | |
| from fastapi import FastAPI, Request | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| HF_API_KEY = os.getenv("HF_API_KEY") | |
| MODEL_ID = os.getenv("MODEL_ID", "mistralai/Mistral-7B-Instruct-v0.2") | |
| HF_API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}" | |
| HEADERS = { | |
| "Authorization": f"Bearer {HF_API_KEY}", | |
| "Content-Type": "application/json", | |
| } | |
| app = FastAPI(title="Local OpenAI-Compatible HF Server") | |
| def messages_to_prompt(messages): | |
| """ | |
| Converts OpenAI chat messages to a clean instruction prompt. | |
| Works well for code generation tools. | |
| """ | |
| system = "" | |
| conversation = "" | |
| for msg in messages: | |
| if msg["role"] == "system": | |
| system += msg["content"] + "\n" | |
| elif msg["role"] == "user": | |
| conversation += f"User:\n{msg['content']}\n" | |
| elif msg["role"] == "assistant": | |
| conversation += f"Assistant:\n{msg['content']}\n" | |
| return f"""<s>[SYSTEM] | |
| {system} | |
| [/SYSTEM] | |
| {conversation} | |
| Assistant: | |
| """ | |
| async def chat_completions(request: Request): | |
| body = await request.json() | |
| messages = body["messages"] | |
| prompt = messages_to_prompt(messages) | |
| payload = { | |
| "inputs": prompt, | |
| "parameters": { | |
| "temperature": body.get("temperature", 0.2), | |
| "max_new_tokens": body.get("max_tokens", 512), | |
| "stop": ["User:", "System:"], | |
| }, | |
| } | |
| response = requests.post( | |
| HF_API_URL, | |
| headers=HEADERS, | |
| json=payload, | |
| timeout=120, | |
| ).json() | |
| text = response[0]["generated_text"].replace(prompt, "").strip() | |
| return { | |
| "id": "chatcmpl-local", | |
| "object": "chat.completion", | |
| "choices": [ | |
| { | |
| "index": 0, | |
| "message": { | |
| "role": "assistant", | |
| "content": text, | |
| }, | |
| "finish_reason": "stop", | |
| } | |
| ], | |
| "usage": { | |
| "prompt_tokens": len(prompt.split()), | |
| "completion_tokens": len(text.split()), | |
| "total_tokens": len(prompt.split()) + len(text.split()), | |
| }, | |
| } | |