main.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 nicegui import Client, ui
  6. OPENAI_API_KEY = 'not-set' # TODO: set your OpenAI API key here
  7. llm = ConversationChain(llm=ChatOpenAI(model_name='gpt-3.5-turbo', openai_api_key=OPENAI_API_KEY))
  8. messages: List[Tuple[str, str]] = []
  9. thinking: bool = False
  10. @ui.refreshable
  11. async def chat_messages() -> None:
  12. for name, text in messages:
  13. ui.chat_message(text=text, name=name, sent=name == 'You')
  14. if thinking:
  15. ui.spinner(size='3rem').classes('self-center')
  16. await ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)', respond=False)
  17. @ui.page('/')
  18. async def main(client: Client):
  19. async def send() -> None:
  20. global thinking
  21. message = text.value
  22. messages.append(('You', text.value))
  23. thinking = True
  24. text.value = ''
  25. chat_messages.refresh()
  26. response = await llm.arun(message)
  27. messages.append(('Bot', response))
  28. thinking = False
  29. chat_messages.refresh()
  30. anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
  31. ui.add_head_html(f'<style>{anchor_style}</style>')
  32. await client.connected()
  33. with ui.column().classes('w-full max-w-2xl mx-auto items-stretch'):
  34. await chat_messages()
  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)')