main.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python3
  2. from typing import List, Tuple
  3. from langchain.chains import ConversationChain
  4. from langchain.chat_models import ChatOpenAI
  5. from log_callback_handler import NiceGuiLogElementCallbackHandler
  6. import nicegui.globals
  7. from nicegui import Client, ui
  8. OPENAI_API_KEY = 'not-set' # TODO: set your OpenAI API key here
  9. llm = ConversationChain(llm=ChatOpenAI(model_name='gpt-3.5-turbo', openai_api_key=OPENAI_API_KEY))
  10. messages: List[Tuple[str, str]] = []
  11. thinking: bool = False
  12. @ui.refreshable
  13. def chat_messages() -> None:
  14. for name, text in messages:
  15. ui.chat_message(text=text, name=name, sent=name == 'You')
  16. if thinking:
  17. ui.spinner(size='3rem').classes('self-center')
  18. if nicegui.globals.get_client().has_socket_connection:
  19. ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)')
  20. @ui.page('/')
  21. async def main():
  22. async def send() -> None:
  23. global thinking
  24. message = text.value
  25. messages.append(('You', text.value))
  26. thinking = True
  27. text.value = ''
  28. chat_messages.refresh()
  29. response = await llm.arun(message, callbacks=[NiceGuiLogElementCallbackHandler(log)])
  30. messages.append(('Bot', response))
  31. thinking = False
  32. chat_messages.refresh()
  33. anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
  34. ui.add_head_html(f'<style>{anchor_style}</style>')
  35. # the queries below are used to expand the contend down to the footer (content can then use flex-grow to expand)
  36. ui.query('.q-page').classes('flex')
  37. ui.query('.nicegui-content').classes('w-full')
  38. with ui.tabs().classes('w-full') as tabs:
  39. chat_tab = ui.tab('Chat')
  40. logs_tab = ui.tab('Logs')
  41. with ui.tab_panels(tabs, value=chat_tab).classes('w-full max-w-2xl mx-auto flex-grow items-stretch'):
  42. with ui.tab_panel(chat_tab):
  43. with ui.column().classes('w-full'):
  44. chat_messages()
  45. with ui.tab_panel(logs_tab):
  46. log = ui.log().classes('w-full h-full')
  47. with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
  48. with ui.row().classes('w-full no-wrap items-center'):
  49. placeholder = 'message' if OPENAI_API_KEY != 'not-set' else \
  50. 'Please provide your OPENAI key in the Python script first!'
  51. text = ui.input(placeholder=placeholder).props('rounded outlined input-class=mx-3') \
  52. .classes('w-full self-center').on('keydown.enter', send)
  53. ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
  54. .classes('text-xs self-end mr-8 m-[-1em] text-primary')
  55. ui.run(title='Chat with GPT-3 (example)')