Geoeasy commited on
Commit
6155801
·
verified ·
1 Parent(s): 115a243

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -68
app.py CHANGED
@@ -1,18 +1,18 @@
1
  #!/usr/bin/env python3
2
  """
3
- Chatbot FTTH - Demonstração de Engenharia de Fibra Óptica
4
- Interface web com Gradio + Llama 3.3 Instruct via NVIDIA API
5
- Otimizado para RTX 5090
6
  """
7
 
8
  import gradio as gr
9
  import os
10
  from openai import OpenAI
11
 
12
- # Configuração da API NVIDIA
13
  NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY")
14
 
15
- # Inicializar cliente OpenAI com endpoint NVIDIA
16
  if NVIDIA_API_KEY:
17
  client = OpenAI(
18
  base_url="https://integrate.api.nvidia.com/v1",
@@ -21,47 +21,48 @@ if NVIDIA_API_KEY:
21
  else:
22
  client = None
23
 
24
- # Sistema de prompt para o chatbot FTTH
25
- SYSTEM_PROMPT = """Você é um especialista em engenharia de FTTH (Fiber to the Home) - Fibra Óptica até à Casa.
26
 
27
- Sua função é responder perguntas sobre:
28
- - Projetos e implementação de FTTH
29
- - Infraestrutura de fibra óptica
30
- - Tecnologias de acesso à fibra
31
- - Benefícios e características do FTTH
32
- - Desafios técnicos e soluções
33
- - Padrões e regulamentações
34
- - Custos e viabilidade econômica
35
- - Comparação com outras tecnologias (ADSL, VDSL, 4G/5G)
36
- - Instalação e manutenção de redes FTTH
37
- - Componentes de rede (OLT, ONT, splitters, cabos, etc.)
38
 
39
- Responda de forma clara, profissional e educativa, adaptando o nível de detalhe técnico à pergunta.
40
- Quando apropriado, forneça exemplos práticos e recomendações para projetos de engenharia.
41
 
42
- Mantenha as respostas concisas mas informativas, ideais para uma apresentação profissional."""
 
43
 
44
  def chat_ftth_nvidia(message: str, history: list) -> str:
45
  """
46
- Função que processa mensagens sobre FTTH usando Llama 3.3 Instruct via NVIDIA API
47
  """
48
-
49
- # Verificar se o cliente está inicializado
50
  if not client:
51
- return "❌ Erro: NVIDIA_API_KEY não está configurada. Configure nas Settings do Space."
52
-
53
- # Construir histórico de mensagens para a API
54
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
55
-
56
- # Adicionar histórico de conversação
57
  for msg in history:
58
  messages.append(msg)
59
-
60
- # Adicionar mensagem atual
61
  messages.append({"role": "user", "content": message})
62
-
63
  try:
64
- # Chamar API NVIDIA com cliente OpenAI
65
  completion = client.chat.completions.create(
66
  model="meta/llama-3.3-70b-instruct",
67
  messages=messages,
@@ -70,55 +71,55 @@ def chat_ftth_nvidia(message: str, history: list) -> str:
70
  max_tokens=1024,
71
  stream=False
72
  )
73
-
74
  return completion.choices[0].message.content
75
-
76
  except Exception as e:
77
- return f"❌ Erro ao processar sua pergunta: {str(e)}"
78
 
79
 
80
- # Criar interface Gradio
81
- with gr.Blocks(title="Chatbot FTTH") as demo:
82
  gr.Markdown("""
83
- # 🌐 Chatbot FTTH - Engenharia de Fibra Óptica
84
-
85
- Bem-vindo ao assistente especializado em **FTTH (Fiber to the Home)**.
86
-
87
- Faça perguntas sobre projetos de fibra óptica, infraestrutura, tecnologias e implementação.
88
-
89
- **Tecnologia:** Llama 3.3 Instruct (NVIDIA API) + RTX 5090
90
  """)
91
-
92
  chatbot = gr.ChatInterface(
93
  chat_ftth_nvidia,
94
  examples=[
95
- "O que é FTTH e quais são seus principais benefícios?",
96
- "Qual é a diferença entre FTTH, FTTP e FTTC?",
97
- "Quais são os componentes principais de uma rede FTTH?",
98
- "Como é feita a instalação de fibra óptica em uma residência?",
99
- "Qual é a velocidade típica de uma conexão FTTH?",
100
- "Quais são os desafios na implementação de FTTH em áreas rurais?",
101
- "Como funciona um splitter óptico em uma rede FTTH?",
102
- "Qual é o custo aproximado de implementação de FTTH por km?",
103
  ],
104
- title="Assistente FTTH",
105
- description="Faça suas perguntas sobre FTTH e receba respostas especializadas.",
106
  )
107
-
108
  gr.Markdown("""
109
  ---
110
-
111
- **Dicas de uso:**
112
- - Faça perguntas específicas sobre aspectos técnicos do FTTH
113
- - Use exemplos práticos para obter respostas mais detalhadas
114
- - O chatbot mantém o contexto da conversa para respostas mais relevantes
115
-
116
- **Tecnologia:**
117
- - Modelo: Llama 3.3 Instruct (Meta)
118
  - API: NVIDIA Cloud
119
- - GPU: RTX 5090 (otimizada)
120
-
121
- *Desenvolvido para demonstração em reuniões de engenharia*
122
  """)
123
 
124
 
 
1
  #!/usr/bin/env python3
2
  """
3
+ FTTH Chatbot Fiber Optic Engineering Demonstration
4
+ Web interface with Gradio + Llama 3.3 Instruct via NVIDIA API
5
+ Optimized for RTX 5090
6
  """
7
 
8
  import gradio as gr
9
  import os
10
  from openai import OpenAI
11
 
12
+ # NVIDIA API configuration
13
  NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY")
14
 
15
+ # Initialize OpenAI client with NVIDIA endpoint
16
  if NVIDIA_API_KEY:
17
  client = OpenAI(
18
  base_url="https://integrate.api.nvidia.com/v1",
 
21
  else:
22
  client = None
23
 
24
+ # System prompt for the FTTH chatbot
25
+ SYSTEM_PROMPT = """You are an expert in FTTH (Fiber to the Home) engineering Fiber Optics to the Home.
26
 
27
+ Your role is to answer questions about:
28
+ - FTTH project design and implementation
29
+ - Fiber optic infrastructure
30
+ - Fiber access technologies
31
+ - Benefits and characteristics of FTTH
32
+ - Technical challenges and solutions
33
+ - Standards and regulations
34
+ - Costs and economic feasibility
35
+ - Comparison with other technologies (ADSL, VDSL, 4G/5G)
36
+ - Installation and maintenance of FTTH networks
37
+ - Network components (OLT, ONT, splitters, cables, etc.)
38
 
39
+ Respond in a clear, professional, and educational manner, adapting the level of technical detail to the question.
40
+ When appropriate, provide practical examples and engineering recommendations.
41
 
42
+ Keep responses concise but informative, suitable for a professional presentation.
43
+ """
44
 
45
  def chat_ftth_nvidia(message: str, history: list) -> str:
46
  """
47
+ Function that processes FTTH-related messages using Llama 3.3 Instruct via NVIDIA API
48
  """
49
+
50
+ # Check if the client is initialized
51
  if not client:
52
+ return "❌ Error: NVIDIA_API_KEY is not configured. Please set it in the Space settings."
53
+
54
+ # Build message history for the API
55
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
56
+
57
+ # Add conversation history
58
  for msg in history:
59
  messages.append(msg)
60
+
61
+ # Add current user message
62
  messages.append({"role": "user", "content": message})
63
+
64
  try:
65
+ # Call NVIDIA API using OpenAI client
66
  completion = client.chat.completions.create(
67
  model="meta/llama-3.3-70b-instruct",
68
  messages=messages,
 
71
  max_tokens=1024,
72
  stream=False
73
  )
74
+
75
  return completion.choices[0].message.content
76
+
77
  except Exception as e:
78
+ return f"❌ Error while processing your question: {str(e)}"
79
 
80
 
81
+ # Create Gradio interface
82
+ with gr.Blocks(title="FTTH Chatbot") as demo:
83
  gr.Markdown("""
84
+ # 🌐 FTTH Chatbot Fiber Optic Engineering
85
+
86
+ Welcome to the specialized assistant for **FTTH (Fiber to the Home)**.
87
+
88
+ Ask questions about fiber optic projects, infrastructure, technologies, and deployment.
89
+
90
+ **Technology:** Llama 3.3 Instruct (NVIDIA API) + RTX 5090
91
  """)
92
+
93
  chatbot = gr.ChatInterface(
94
  chat_ftth_nvidia,
95
  examples=[
96
+ "What is FTTH and what are its main benefits?",
97
+ "What is the difference between FTTH, FTTP, and FTTC?",
98
+ "What are the main components of an FTTH network?",
99
+ "How is fiber optic installation done in a residential building?",
100
+ "What is the typical speed of an FTTH connection?",
101
+ "What are the challenges of deploying FTTH in rural areas?",
102
+ "How does an optical splitter work in an FTTH network?",
103
+ "What is the approximate cost of FTTH deployment per kilometer?",
104
  ],
105
+ title="FTTH Assistant",
106
+ description="Ask your questions about FTTH and receive expert answers.",
107
  )
108
+
109
  gr.Markdown("""
110
  ---
111
+
112
+ **Usage tips:**
113
+ - Ask specific questions about FTTH technical aspects
114
+ - Use practical examples to get more detailed answers
115
+ - The chatbot keeps conversation context for more relevant responses
116
+
117
+ **Technology stack:**
118
+ - Model: Llama 3.3 Instruct (Meta)
119
  - API: NVIDIA Cloud
120
+ - GPU: RTX 5090 (optimized)
121
+
122
+ *Developed for engineering meeting demonstrations*
123
  """)
124
 
125