jackllll1312 / test2

0 stars 0 forks source link

ok #1

Open jackllll1312 opened 4 months ago

jackllll1312 commented 4 months ago

import toga from toga.style import Pack from toga.style.pack import COLUMN, ROW, RIGHT, LEFT from datetime import datetime from openai import AzureOpenAI

class ChatApp(toga.App): def init(self, *args, *kwargs): super().init(args, **kwargs) self.client = AzureOpenAI( api_key=("77a0ca4ac2524d5f97a937bf4b69e305"), api_version="2023-12-01-preview", azure_endpoint=("https://azure-openai-ais-poc.openai.azure.com/") ) self.conversation = [] self.system_message = {"role": "system", "content": "你是個非常有幫助的PWC AI助理,講中文"}

def startup(self):
    self.main_window = toga.MainWindow(title=self.formal_name, size=(600, 400))

    # Create conversation history boxes with a scrollbar
    self.assistant_history = toga.Box(style=Pack(direction=COLUMN, padding=5))
    self.user_history = toga.Box(style=Pack(direction=COLUMN, padding=5))
    self.user_messages = []  # 用戶對話歷史列表

    # Create user input box with a send button
    self.user_input = toga.TextInput(style=Pack(flex=1, padding=5))
    self.send_button = toga.Button('Send', on_press=self.send_message, style=Pack(padding=(0, 5)))

    # Create conversation and input boxes
    # Create conversation history boxes with a scrollbar
    self.conversation_history = toga.Box(style=Pack(direction=COLUMN, padding=5))

Create conversation and input boxes

    conversation_box = toga.Box(
        children=[self.conversation_history],
        style=Pack(direction=COLUMN, padding=5)

)

    input_box = toga.Box(
        children=[self.user_input, self.send_button],
        style=Pack(direction=ROW, padding=5)
    )

    # Create the main layout box
    main_box = toga.Box(

children=[conversation_box, input_box], style=Pack(direction=COLUMN, background_color='#131313') # Dark background )

    self.main_window.content = main_box
    self.main_window.show()

def send_message(self, widget):
    user_input = self.user_input.value
    if user_input:
        current_time = datetime.now().strftime("%H:%M")

    # Append user message to the conversation
        user_message = {"role": "user", "content": user_input, "timestamp": current_time}
        self.conversation.append(user_message)

    # Generate reply from OpenAI Chat API
        response = self.client.chat.completions.create(
            model="TestPOC35Turbo",
            messages=[{"role": msg["role"], "content": msg["content"]} for msg in self.conversation]
    )

    # Extract assistant's reply from the response
        assistant_reply = response.choices[0].message.content

    # Append assistant's reply to the conversation
        assistant_message = {"role": "assistant", "content": assistant_reply, "timestamp": current_time}
        self.conversation.append(assistant_message)

    # Update conversation history with speech bubble-like display
        # Update conversation history with speech bubble-like display
        user_chat_bubble = self.create_chat_bubble('User', user_input)
        user_chat_bubble.style.justify = RIGHT
        assistant_chat_bubble = self.create_chat_bubble('Assistant', assistant_reply)
        assistant_chat_bubble.style.justify = LEFT

Add both user and assistant messages to the conversation history

        self.conversation_history.add(user_chat_bubble)
        self.conversation_history.add(assistant_chat_bubble)

    # Save user message for history with timestamp
        self.user_messages.append((current_time, user_chat_bubble))

    # Sort user messages based on timestamp
        self.user_messages.sort(key=lambda x: x[0])

    # Clear user input
        self.user_input.value = ''

def create_chat_bubble(self, sender, content):
# Create a chat bubble widget
    chat_bubble = toga.Box(style=Pack(padding=5, background_color='#0084ff' if sender == 'User' else '#e0e0e0'))

# Add a label with sender and content
    label = toga.Label(f'{sender}: {content}', style=Pack(color='white' if sender == 'User' else 'black'))

# Adjust border-radius using the Pack properties
    if sender == 'User':
        label.style.padding = 10
        label.style.background_color = '#007AFF'
        label.style.border_radius = 12  # Adjust the border-radius here
    else:
        label.style.padding = 10
        label.style.background_color = '#F0F0F0'

    chat_bubble.add(label)

    return chat_bubble

def main(): return ChatApp('Chat App', 'org.beeware.chatapp')

if name == 'main': app = main() app.main_loop()

jackllll1312 commented 4 months ago

from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.scrollview import ScrollView from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.label import Label from datetime import datetime from openai import AzureOpenAI

class ChatApp(App): def build(self): self.client = AzureOpenAI( api_key="77a0ca4ac2524d5f97a937bf4b69e305", api_version="2023-12-01-preview", azure_endpoint="https://azure-openai-ais-poc.openai.azure.com/" ) self.conversation = []

    # Main layout
    main_layout = BoxLayout(orientation='vertical', padding=10)

    # Conversation history (scrollable)
    self.conversation_history = BoxLayout(orientation='vertical', size_hint_y=None)
    scroll_view = ScrollView(size_hint=(1, 0.9))
    scroll_view.add_widget(self.conversation_history)

    # User input and send button
    input_layout = BoxLayout(orientation='horizontal', size_hint_y=None, height=50)
    self.user_input = TextInput(size_hint_x=0.8, multiline=False)
    send_button = Button(text='Send', size_hint_x=0.2)
    send_button.bind(on_press=self.send_message)

    input_layout.add_widget(self.user_input)
    input_layout.add_widget(send_button)

    main_layout.add_widget(scroll_view)
    main_layout.add_widget(input_layout)

    return main_layout

def send_message(self, instance):
    user_input = self.user_input.text.strip()
    if user_input:
        current_time = datetime.now().strftime("%H:%M")
        self.add_chat_bubble('User', user_input, current_time)

        # Simulate API call and response
        response = self.client.chat.completions.create(
            model="TestPOC35Turbo",
            messages=[{"role": "user", "content": user_input}]
        )
        assistant_reply = response.choices[0].message.content
        self.add_chat_bubble('Assistant', assistant_reply, current_time)

        self.user_input.text = ''  # Clear input field

def add_chat_bubble(self, sender, content, timestamp):
    # Create a chat bubble (label) and add it to the conversation history
    chat_bubble = Label(text=f'{sender} ({timestamp}): {content}', size_hint_y=None, markup=True)
    if sender == 'User':
        chat_bubble.color = (0, 0.5, 1, 1)
    else:
        chat_bubble.color = (0, 0, 0, 1)
    self.conversation_history.add_widget(chat_bubble)

if name == 'main': ChatApp().run()