File size: 4,979 Bytes
9dcffdf
80769a7
 
5789637
9dcffdf
dfd08bc
80769a7
5789637
 
9dcffdf
 
 
 
 
 
5789637
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f149cfd
dfd08bc
 
 
 
 
 
f149cfd
5789637
f149cfd
dfd08bc
 
 
 
 
 
f149cfd
5789637
0fbfaed
dfd08bc
0fbfaed
7feb213
5789637
 
 
 
 
 
afdf5fc
5789637
afdf5fc
8c2b443
5789637
80769a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import os
from fastapi import FastAPI, Request
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel
from openai import OpenAI
import langdetect
from twilio.twiml.messaging_response import MessagingResponse

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}


@app.post("/whatsapp")
async def whatsapp_webhook(request: Request):
    form = await request.form()
    incoming_msg = form.get("Body")

    try:
        idioma = langdetect.detect(incoming_msg)
    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": incoming_msg}
        ],
        max_tokens=250
    )
    answer = completion.choices[0].message.content.strip()

    resp = MessagingResponse()
    msg = resp.message()
    msg.body(answer)

    return PlainTextResponse(str(resp), media_type="application/xml")