zauberzeug / nicegui

Create web-based user interfaces with Python. The nice way.
https://nicegui.io
MIT License
8.26k stars 492 forks source link

Using chatai, enter the question carriage return did not respond #3227

Closed 52phm closed 3 weeks ago

52phm commented 3 weeks ago

Description

code

#!/usr/bin/env python3
from nicegui import ui
import requests
from uuid import uuid4
@ui.page('/')
def main():
    async def send() -> None:
        question = text.value
        text.value = ''

        with message_container:
            ui.chat_message(text=question, name='You', sent=True,
                            # avatar=avatar
                            )
            response_message = ui.chat_message(name='Bot', sent=False)
            spinner = ui.spinner(type='dots')

        # 流式响应
        # response = ''
        # async for chunk in llm.astream():
        #     response += chunk.content
        #     response_message.clear()
        #     with response_message:
        #         ui.html(response)
        #     ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)')
        # 普通模式
        response = ''
        llm = requests.post(
            url="http://172.xx.xx.xx:21001/api/chat",
            json={'prompt': question}
        )
        if llm.status_code == 200:
            response = llm.json()['response']
            print(response)
        response_message.clear()
        with response_message:
            ui.html(response)
        ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)')

        message_container.remove(spinner)

    ui.add_css(r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}')

    user_id = str(uuid4())
    avatar = f'https://robohash.org/{user_id}?bgset=bg2'

    # the queries below are used to expand the contend down to the footer (content can then use flex-grow to expand)
    ui.query('.q-page').classes('flex')
    ui.query('.nicegui-content').classes('w-full')

    with ui.tabs().classes('w-full') as tabs:
        chat_tab = ui.tab('Chat')
        logs_tab = ui.tab('Logs')
    with ui.tab_panels(tabs, value=chat_tab).classes('w-full max-w-2xl mx-auto flex-grow items-stretch'):
        message_container = ui.tab_panel(chat_tab).classes('items-stretch')
        with ui.tab_panel(logs_tab):
            log = ui.log().classes('w-full h-full')

    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 OPENAI_API_KEY != 'not-set' else \
            #     'Please provide your OPENAI key in the Python script first!'
            with ui.avatar().on('click', lambda: ui.navigate.to(main)):
                ui.image(avatar)
            placeholder = 'message'
            text = ui.input(placeholder=placeholder).props('rounded outlined input-class=mx-2') \
                .classes('w-full self-center').on('keydown.enter', send)
        ui.markdown('AI助手 [NiceGUI](https://nicegui.io)') \
            .classes('text-xs self-end mr-8 m-[-1em] text-primary')

ui.run(title='Chat with QWEN (example)')

Type "Who are you", press enter, and the user input question can be displayed above the chat box. But enter "How to learn python" press enter, The problem entered by the user is not displayed on the chat box, and it does not respond like it is stuck. The background runs normally and the large model has content output

I am a large language model created by Alibaba Cloud. I am called Qwen.

Learning Python can be a fun and rewarding experience. Here's a step-by-step guide to help you get started:

1. **Get familiar with the basics**: Start by understanding what Python is, its syntax, and its advantages. You can find plenty of beginner-friendly resources online, such as articles, videos, or tutorials.

2. **Install Python**: Download and install the latest version of Python from the official website (<https://www.python.org/downloads/>). Follow the installation instructions for your operating system (Windows, macOS, or Linux).

3. **Choose a code editor**: A code editor is a tool that helps you write and save your Python code. Some popular choices include Visual Studio Code, PyCharm, Sublime Text, Atom, or IDLE (Integrated Development Environment), which comes pre-installed with Python.

4. **Learn the syntax**: Start with the fundamentals of Python, like variables, data types, operators, control flow (if-else statements, loops), and functions. Practice writing simple programs to reinforce your understanding.

5. **Practice coding**: As you learn new concepts, practice by writing small programs and exercises. Websites like LeetCode, HackerRank, or CodeWars offer coding challenges to improve your skills.

6. **Object-Oriented Programming (OOP)**: Once you're comfortable with basic programming, dive into OOP concepts like classes, objects, inheritance, and polymorphism. These are essential for building more complex applications.

7. **Explore libraries and frameworks**: Python has a vast ecosystem of libraries and frameworks for various purposes. Some popular ones are NumPy for scientific computing, Pandas for data analysis, Matplotlib for data visualization, Django or Flask for web development, and TensorFlow or PyTorch for machine learning. Pick one based on your interests and start exploring it.

8. **Read code written by others**: Look at open-source projects on GitHub or other platforms to understand how experienced developers structure their code. This will give you insights into best practices and common patterns.

9. **Online courses and tutorials**: Enroll in an online course or follow a structured tutorial series. Websites like Coursera, Udemy, Codecademy, or edX offer comprehensive courses for beginners and intermediate learners.

10. **Join a community**: Engage with other Python learners and professionals through forums, communities, or meetups. Websites like Reddit (r/learnpython), Stack Overflow, or Python Discord can provide support and opportunities to collaborate.

11. **Build projects**: Apply your knowledge by working
52phm commented 3 weeks ago

Any question that takes a little longer to generate an answer will not display properly on the chat page, so has this problem not been discovered? Or I wrote something wrong, please help solve, thank you

falkoschindler commented 3 weeks ago

I'm not sure if I understand your problem correctly, since your example isn't minimal nor executable. But I suspect the problem is requests.post not being async, so the request blocks the UI while waiting for the result. See this FAQ for more information.