|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import streamlit as st |
| 5 | +from sdk import ChatClient |
| 6 | +from dotenv import load_dotenv |
| 7 | + |
| 8 | +# Load environment variables |
| 9 | +load_dotenv() |
| 10 | + |
| 11 | +# Initialize Dify client |
| 12 | +client = ChatClient( |
| 13 | + api_key=os.getenv("DIFY_API_KEY"), |
| 14 | + base_url=os.getenv("DIFY_BASE_URL", "https://api.dify.ai/v1") |
| 15 | +) |
| 16 | + |
| 17 | +# File category definitions |
| 18 | +DIFY_FILE_CATEGORY_EXTENSIONS = { |
| 19 | + "document": [ |
| 20 | + "TXT", "MD", "MDX", "MARKDOWN", "PDF", "HTML", "XLSX", "XLS", |
| 21 | + "DOC", "DOCX", "CSV", "EML", "MSG", "PPTX", "PPT", "XML", "EPUB" |
| 22 | + ], |
| 23 | + "image": ["JPG", "JPEG", "PNG", "GIF", "WEBP", "SVG"], |
| 24 | + "audio": ["MP3", "M4A", "WAV", "WEBM", "AMR", "MPGA"], |
| 25 | + "video": ["MP4", "MOV", "MPEG", "MPGA"] |
| 26 | +} |
| 27 | + |
| 28 | +DIFY_FILE_CATEGORIES = list(DIFY_FILE_CATEGORY_EXTENSIONS.keys()) |
| 29 | + |
| 30 | + |
| 31 | +def get_dify_file_category(file_name: str) -> str: |
| 32 | + extension = file_name.split(".")[-1].upper() if "." in file_name else "" |
| 33 | + for category, extensions in DIFY_FILE_CATEGORY_EXTENSIONS.items(): |
| 34 | + if extension in extensions: |
| 35 | + return category |
| 36 | + return "custom" |
| 37 | + |
| 38 | + |
| 39 | +def main(): |
| 40 | + st.title("Dify Chat Interface") |
| 41 | + |
| 42 | + # Initialize chat history |
| 43 | + if "messages" not in st.session_state: |
| 44 | + st.session_state.messages = [] |
| 45 | + |
| 46 | + # Display chat messages |
| 47 | + for message in st.session_state.messages: |
| 48 | + with st.chat_message(message["role"]): |
| 49 | + st.markdown(message["content"]) |
| 50 | + |
| 51 | + response = client.get_application_parameters(user="streamlit-user") |
| 52 | + if response.status_code == 200: |
| 53 | + parameters = response.json() |
| 54 | + _ = """ |
| 55 | + parameters = { |
| 56 | + 'opening_statement': '어떤 도움이 필요하신가요?', |
| 57 | + 'suggested_questions': ['배송상태 조회', '환불/교환 요청'], |
| 58 | + 'suggested_questions_after_answer': {'enabled': False}, |
| 59 | + 'speech_to_text': {'enabled': False}, |
| 60 | + 'text_to_speech': {'enabled': False, 'voice': '', 'language': ''}, |
| 61 | + 'retriever_resource': {'enabled': True}, |
| 62 | + 'annotation_reply': {'enabled': False}, |
| 63 | + 'more_like_this': {'enabled': False}, |
| 64 | + 'user_input_form': [], |
| 65 | + 'sensitive_word_avoidance': {'enabled': False, 'type': '', 'configs': []}, |
| 66 | + 'file_upload': {'image': { |
| 67 | + 'detail': 'high', |
| 68 | + 'enabled': False, |
| 69 | + 'number_limits': 3, |
| 70 | + 'transfer_methods': ['remote_url', 'local_file']}, |
| 71 | + 'enabled': False, |
| 72 | + 'allowed_file_types': [], |
| 73 | + 'allowed_file_extensions': ['.JPG', '.JPEG', '.PNG', '.GIF', '.WEBP', '.SVG', '.MP4', '.MOV', '.MPEG', '.MPGA'], |
| 74 | + 'allowed_file_upload_methods': ['remote_url', 'local_file'], |
| 75 | + 'number_limits': 3}, |
| 76 | + 'system_parameters': { |
| 77 | + 'image_file_size_limit': 10, |
| 78 | + 'video_file_size_limit': 100, |
| 79 | + 'audio_file_size_limit': 50, |
| 80 | + 'file_size_limit': 15, |
| 81 | + 'workflow_file_upload_limit': 10 |
| 82 | + } |
| 83 | + } |
| 84 | + """ |
| 85 | + # print(parameters) |
| 86 | + else: |
| 87 | + st.error(response.text) |
| 88 | + |
| 89 | + # Chat input |
| 90 | + if prompt := st.chat_input(parameters["opening_statement"], accept_file=True, file_type=parameters["file_upload"]["allowed_file_extensions"]): |
| 91 | + # Add user message to chat history |
| 92 | + st.session_state.messages.append( |
| 93 | + {"role": "user", "content": prompt.text}) |
| 94 | + |
| 95 | + uploaded_files = [] |
| 96 | + with st.chat_message("user"): |
| 97 | + st.markdown(prompt.text) |
| 98 | + if prompt.files: |
| 99 | + for file in prompt.files: |
| 100 | + response = client.file_upload( |
| 101 | + user="streamlit-user", files={"file": (file.name, file.read(), file.type)}) |
| 102 | + if response.status_code == 201: |
| 103 | + file_obj = response.json() |
| 104 | + file_category = get_dify_file_category( |
| 105 | + file_obj["name"]) |
| 106 | + uploaded_files.append({ |
| 107 | + "transfer_method": "local_file", |
| 108 | + "name": file_obj["name"], |
| 109 | + "upload_file_id": file_obj["id"], |
| 110 | + "type": file_category, |
| 111 | + }) |
| 112 | + if file_category == "image": |
| 113 | + st.image(file) |
| 114 | + elif file_category == "video": |
| 115 | + st.video(file) |
| 116 | + else: |
| 117 | + st.write(f"File uploaded: {file_obj['name']}") |
| 118 | + else: |
| 119 | + st.error(response.text) |
| 120 | + |
| 121 | + # Get response from Dify |
| 122 | + with st.chat_message("assistant"): |
| 123 | + thoughts_placeholder = st.empty() |
| 124 | + message_placeholder = st.empty() |
| 125 | + response_text = "" |
| 126 | + with st.spinner("Thinking..."): |
| 127 | + response = client.create_chat_message( |
| 128 | + inputs={}, |
| 129 | + query=prompt.text, |
| 130 | + response_mode="streaming", |
| 131 | + user="streamlit-user", |
| 132 | + conversation_id=None, |
| 133 | + files=uploaded_files, |
| 134 | + ) |
| 135 | + agent_thoughts = [] |
| 136 | + if response.status_code == 200: |
| 137 | + for chunk in response.iter_lines(): |
| 138 | + if chunk: |
| 139 | + try: |
| 140 | + data = json.loads( |
| 141 | + chunk.decode("utf-8").strip()[6:]) |
| 142 | + except json.decoder.JSONDecodeError: |
| 143 | + break |
| 144 | + print(data) |
| 145 | + match data["event"]: |
| 146 | + case "message": |
| 147 | + response_text += data["answer"] |
| 148 | + message_placeholder.markdown(response_text) |
| 149 | + case "message_end": |
| 150 | + message_placeholder.markdown(response_text) |
| 151 | + case "agent_message": |
| 152 | + response_text += data["answer"] |
| 153 | + message_placeholder.markdown(response_text) |
| 154 | + case "agent_thought": |
| 155 | + if len(agent_thoughts) == 0: |
| 156 | + agent_thoughts.append(data) |
| 157 | + else: |
| 158 | + last_thought = agent_thoughts[-1] |
| 159 | + if last_thought["id"] == data["id"]: |
| 160 | + agent_thoughts[-1] = data |
| 161 | + else: |
| 162 | + agent_thoughts.append(data) |
| 163 | + |
| 164 | + with thoughts_placeholder: |
| 165 | + for thought in agent_thoughts: |
| 166 | + st.write(thought) |
| 167 | + # for thought in agent_thoughts: |
| 168 | + # status_placeholder = st.empty() # Placeholder to show the tool's status |
| 169 | + # with status_placeholder.status("Thinking...", expanded=True) as s: |
| 170 | + # st.write(thought) |
| 171 | + # s.update(label="Completed Thinking!", expanded=False) # Update the status once done |
| 172 | + |
| 173 | + case "error": |
| 174 | + st.error(data) |
| 175 | + case _: |
| 176 | + pass |
| 177 | + else: |
| 178 | + st.error(response.text) |
| 179 | + |
| 180 | + # Add assistant response to chat history |
| 181 | + st.session_state.messages.append( |
| 182 | + {"role": "assistant", "content": response_text}) |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + main() |
0 commit comments