main.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python3
  2. from langchain_openai import ChatOpenAI
  3. from log_callback_handler import NiceGuiLogElementCallbackHandler
  4. from nicegui import ui
  5. OPENAI_API_KEY = 'not-set' # TODO: set your OpenAI API key here
  6. @ui.page('/')
  7. def main():
  8. llm = ChatOpenAI(model_name='gpt-3.5-turbo', streaming=True, openai_api_key=OPENAI_API_KEY)
  9. async def send() -> None:
  10. question = text.value
  11. text.value = ''
  12. with message_container:
  13. ui.chat_message(text=question, name='You', sent=True)
  14. response_message = ui.chat_message(name='Bot', sent=False)
  15. spinner = ui.spinner(type='dots')
  16. response = ''
  17. async for chunk in llm.astream(question, config={'callbacks': [NiceGuiLogElementCallbackHandler(log)]}):
  18. response += chunk.content
  19. response_message.clear()
  20. with response_message:
  21. ui.html(response)
  22. ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)')
  23. message_container.remove(spinner)
  24. ui.add_css(r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}')
  25. # the queries below are used to expand the contend down to the footer (content can then use flex-grow to expand)
  26. ui.query('.q-page').classes('flex')
  27. ui.query('.nicegui-content').classes('w-full')
  28. with ui.tabs().classes('w-full') as tabs:
  29. chat_tab = ui.tab('Chat')
  30. logs_tab = ui.tab('Logs')
  31. with ui.tab_panels(tabs, value=chat_tab).classes('w-full max-w-2xl mx-auto flex-grow items-stretch'):
  32. message_container = ui.tab_panel(chat_tab).classes('items-stretch')
  33. with ui.tab_panel(logs_tab):
  34. log = ui.log().classes('w-full h-full')
  35. with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
  36. with ui.row().classes('w-full no-wrap items-center'):
  37. placeholder = 'message' if OPENAI_API_KEY != 'not-set' else \
  38. 'Please provide your OPENAI key in the Python script first!'
  39. text = ui.input(placeholder=placeholder).props('rounded outlined input-class=mx-3') \
  40. .classes('w-full self-center').on('keydown.enter', send)
  41. ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
  42. .classes('text-xs self-end mr-8 m-[-1em] text-primary')
  43. ui.run(title='Chat with GPT-3 (example)')