Просмотр исходного кода

#884 code review and some simplifications

Falko Schindler 2 лет назад
Родитель
Сommit
8d65f717c6
2 измененных файлов с 19 добавлено и 30 удалено
  1. 17 29
      examples/chat_with_ai_app/main.py
  2. 2 1
      examples/chat_with_ai_app/requirements.txt

+ 17 - 29
examples/chat_with_ai_app/main.py

@@ -1,66 +1,54 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
-import os
-from datetime import datetime
 from typing import List, Tuple
 from typing import List, Tuple
 
 
 from langchain.llms import OpenAI
 from langchain.llms import OpenAI
 
 
 from nicegui import Client, ui
 from nicegui import Client, ui
 
 
-os.environ['OPENAI_API_KEY'] = 'not-set'
+OPENAI_API_KEY = 'not-set'  # TODO: set your OpenAI API key here
 
 
-llm = OpenAI(model_name='gpt-3.5-turbo')
+llm = OpenAI(model_name='gpt-3.5-turbo', openai_api_key=OPENAI_API_KEY)
 
 
 messages: List[Tuple[str, str, str]] = []
 messages: List[Tuple[str, str, str]] = []
+thinking: bool = False
 
 
 
 
 @ui.refreshable
 @ui.refreshable
 async def chat_messages() -> None:
 async def chat_messages() -> None:
-    for name, text, stamp in messages:
-        ui.chat_message(text=text,
-                        name=name,
-                        stamp=stamp,
-                        avatar=f'https://robohash.org/{name or "You"}?bgset=bg2',
-                        sent=name == "You")
+    for name, text in messages:
+        ui.chat_message(text=text, name=name, sent=name == 'You')
+    if thinking:
+        ui.spinner(size='3rem').classes('self-center')
     await ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)', respond=False)
     await ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)', respond=False)
 
 
 
 
 @ui.page('/')
 @ui.page('/')
 async def main(client: Client):
 async def main(client: Client):
     async def send() -> None:
     async def send() -> None:
-        stamp = datetime.utcnow().strftime('%X')
+        global thinking
         message = text.value
         message = text.value
-        messages.append(('You', text.value, stamp))
-        messages.append(('Bot', 'Thinking...', stamp))
-        text.value = ""
+        messages.append(('You', text.value))
+        thinking = True
+        text.value = ''
         chat_messages.refresh()
         chat_messages.refresh()
 
 
-        await query(message)
-        await ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)', respond=False)
-
-    async def query(user_message: str) -> None:
-        response = await llm.agenerate([user_message])
-
-        # replace last message ('Thinking....') with response
-        messages[-1] = ('Bot', response.generations[0][0].text, datetime.now().strftime('%H:%M'))
+        response = await llm.agenerate([message])
+        messages.append(('Bot', response.generations[0][0].text))
+        thinking = False
         chat_messages.refresh()
         chat_messages.refresh()
 
 
-        await ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)', respond=False)
-
     anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
     anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
     ui.add_head_html(f'<style>{anchor_style}</style>')
     ui.add_head_html(f'<style>{anchor_style}</style>')
     await client.connected()
     await client.connected()
 
 
-    # chatbox
     with ui.column().classes('w-full max-w-2xl mx-auto items-stretch'):
     with ui.column().classes('w-full max-w-2xl mx-auto items-stretch'):
         await chat_messages()
         await chat_messages()
 
 
-    # footer
     with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
     with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
         with ui.row().classes('w-full no-wrap items-center'):
         with ui.row().classes('w-full no-wrap items-center'):
-            _placeholder = 'message' if os.environ['OPENAI_API_KEY'] != 'not-set' else \
-                'please provide your OPENAI key in the Python script first!'
-            text = ui.input(placeholder=_placeholder).props('rounded outlined input-class=mx-3') \
+            placeholder = 'message' if OPENAI_API_KEY != 'not-set' else \
+                'Please provide your OPENAI key in the Python script first!'
+            text = ui.input(placeholder=placeholder).props('rounded outlined input-class=mx-3') \
                 .classes('w-full self-center').on('keydown.enter', send)
                 .classes('w-full self-center').on('keydown.enter', send)
         ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
         ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
             .classes('text-xs self-end mr-8 m-[-1em] text-primary')
             .classes('text-xs self-end mr-8 m-[-1em] text-primary')

+ 2 - 1
examples/chat_with_ai_app/requirements.txt

@@ -1,2 +1,3 @@
+langchain
 nicegui
 nicegui
-langchain
+openai