瀏覽代碼

#884 code review and some simplifications

Falko Schindler 2 年之前
父節點
當前提交
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
-import os
-from datetime import datetime
 from typing import List, Tuple
 
 from langchain.llms import OpenAI
 
 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]] = []
+thinking: bool = False
 
 
 @ui.refreshable
 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)
 
 
 @ui.page('/')
 async def main(client: Client):
     async def send() -> None:
-        stamp = datetime.utcnow().strftime('%X')
+        global thinking
         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()
 
-        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()
 
-        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}'
     ui.add_head_html(f'<style>{anchor_style}</style>')
     await client.connected()
 
-    # chatbox
     with ui.column().classes('w-full max-w-2xl mx-auto items-stretch'):
         await chat_messages()
 
-    # footer
     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'):
-            _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)
         ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
             .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
-langchain
+openai