File size: 2,132 Bytes
1251bb0
cce9bd3
3ed6e47
cce9bd3
 
 
 
 
 
 
 
 
 
 
 
 
 
3ed6e47
7ffe937
9aa8344
7ffe937
 
9aa8344
 
7ffe937
 
0865bea
 
7ffe937
0865bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17ff855
 
7ffe937
 
3e76c04
 
7ffe937
 
9aa8344
7ffe937
 
9aa8344
3e5704d
9aa8344
3e76c04
 
cb415e1
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
import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM

# 1. Carrega Tokenizer e Modelo separadamente para garantir o controle do Contexto
model_id = "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Força o tokenizer a entender que aceitamos até 16k tokens (DeepSeek suporta 128k, mas RAM limita)
tokenizer.model_max_length = 16384 

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="cpu",
    torch_dtype="auto",
    max_length=16384
)

pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

def predict(message, history):
    """
    Com type="messages", o 'history' já vem no formato correto:
    [{'role': 'user', 'content': 'oi'}, {'role': 'assistant', 'content': 'olá'}]
    """
    
    # Criamos a lista de mensagens adicionando a mensagem atual ao histórico
    # O history vem do Gradio, o message é o input atual
    if message is None:
        message = ""
    
    print(f"DEBUG INPUT: message={repr(message)}")
    print(f"DEBUG INPUT: history={repr(history)}")

    new_messages = history + [{"role": "user", "content": message}]
    
    # Sanitize messages to ensure no None content
    messages = []
    for msg in new_messages:
        content = msg.get("content")
        if content is None:
            content = ""
        messages.append({"role": msg.get("role"), "content": content})

    print(f"DEBUG FINAL MESSAGES: {messages}")

    # Gera a resposta (Aumentando output para raciocínio longo)
    results = pipe(messages, max_new_tokens=2048, truncation=True)
    
    # Retorna apenas o texto novo gerado
    return results[0]['generated_text'][-1]['content']

# 2. Configuração da Interface
# Adicionamos type="messages" para corrigir o aviso e padronizar com o OpenClaw/MCP
demo = gr.ChatInterface(
    fn=predict,
    type="messages",  # <--- ESTA LINHA CORRIGE O AVISO E MUDA O FORMATO DO HISTÓRICO
    title="Qwen Agent Node",
    description="Bot rodando Qwen 2.5 Coder 1.5B via CPU no Hugging Face."
)

if __name__ == "__main__":
    demo.launch(ssr_mode=False)