File size: 2,508 Bytes
9dcffdf
5789637
 
9dcffdf
dfd08bc
5789637
 
9dcffdf
 
 
 
 
 
5789637
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f149cfd
dfd08bc
 
 
 
 
 
f149cfd
5789637
f149cfd
dfd08bc
 
 
 
 
 
f149cfd
5789637
0fbfaed
dfd08bc
0fbfaed
7feb213
5789637
 
 
 
 
 
afdf5fc
5789637
afdf5fc
8c2b443
5789637
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
from fastapi import FastAPI
from pydantic import BaseModel
from openai import OpenAI
import langdetect

app = FastAPI()

client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.environ["HF_TOKEN"],
)

class Query(BaseModel):
    question: str

@app.get("/")
async def root():
    return {"message": "API está rodando!"}

@app.post("/ask")
async def ask_model(query: Query):
    try:
        idioma = langdetect.detect(query.question)
    except:
        idioma = "pt"

    if idioma == "pt":
        system_prompt = (
            "Você é um assistente que responde sempre em texto puro, SEM formatação Markdown, SEM asteriscos, SEM negrito, SEM itálico, SEM listas, SEM códigos.\n\n"
            "Quando responder em japonês, escreva sempre os caracteres japoneses reais (kanji, hiragana e katakana) e, logo após, entre parênteses, a transliteração romaji.\n\n"
            "Não substitua os caracteres japoneses por espaços, asteriscos ou quaisquer símbolos. Use sempre os caracteres reais e mantenha a resposta em texto simples.\n\n"
            "Exemplo de resposta correta:\n\n"
            "こんにちは (Konnichiwa) significa \"Olá\".\n\n"
            "Responda brevemente e de forma direta."
        )
    elif idioma == "en":
        system_prompt = (
            "You are an assistant that always responds in plain text, WITHOUT Markdown formatting, WITHOUT asterisks, bold, italics, lists, or code.\n\n"
            "When responding in Japanese, always write the real Japanese characters (kanji, hiragana, and katakana) followed immediately by the romaji transliteration in parentheses.\n\n"
            "Do not replace Japanese characters with spaces, asterisks, or any symbols. Always use the real characters and keep the response in plain text.\n\n"
            "Example of correct response:\n\n"
            "こんにちは (Konnichiwa) means \"Hello\".\n\n"
            "Respond briefly and directly."
        )
    else:
        system_prompt = (
            "Responda no mesmo idioma da pergunta, de forma direta e curta, sem formatação Markdown."
        )

    completion = client.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct:fireworks-ai",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": query.question}
        ],
        max_tokens=250
    )
    answer = completion.choices[0].message.content.strip()

    return {"answer": answer}