File size: 6,052 Bytes
54fb4ed
3cb7919
 
 
54fb4ed
3cb7919
 
d6ec3c9
3cb7919
 
 
 
d6ec3c9
3cb7919
 
f313c28
 
3cb7919
f313c28
 
3cb7919
f313c28
 
3cb7919
f313c28
 
3cb7919
f313c28
 
3cb7919
f313c28
3cb7919
 
f313c28
 
3cb7919
 
f313c28
 
 
3cb7919
 
f313c28
 
 
 
 
3cb7919
f313c28
 
 
 
 
 
 
3cb7919
 
 
 
 
3941904
3cb7919
 
3941904
3cb7919
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f313c28
3cb7919
 
f313c28
 
3cb7919
 
 
 
3941904
3cb7919
 
 
f313c28
3cb7919
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import os
import gradio as gr
from llama_cloud import LlamaCloud
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Initialize LlamaCloud client
client = LlamaCloud(
    api_key=os.getenv("LLAMA_CLOUD_API_KEY")
)

class DocumentChatbot:
    def __init__(self):
        self.pipeline = None
        self.load_pipeline()
    
    def load_pipeline(self):
        """Load the pipeline from LlamaCloud"""
        try:
            # Replace with your actual pipeline ID from LlamaCloud
            pipeline_id = os.getenv("LLAMA_CLOUD_PIPELINE_ID")
            
            if not pipeline_id:
                raise ValueError("LLAMA_CLOUD_PIPELINE_ID not found in environment variables")
            
            # Get the pipeline from LlamaCloud
            self.pipeline = client.pipelines.get(pipeline_id)
            
            print("βœ… Successfully connected to LlamaCloud pipeline")
            
        except Exception as e:
            print(f"❌ Error loading pipeline: {str(e)}")
            self.pipeline = None
    
    def chat(self, message, history):
        """Process chat message using LlamaCloud pipeline directly"""
        if not self.pipeline:
            return "❌ Error: Could not connect to LlamaCloud pipeline. Please check your configuration."
        
        try:
            # Query using LlamaCloud pipeline directly
            response = client.pipelines.run(
                pipeline_id=self.pipeline.id,
                input={"query": message}
            )
            
            # Extract the response text
            if hasattr(response, 'output') and 'response' in response.output:
                response_text = response.output['response']
            elif hasattr(response, 'response'):
                response_text = str(response.response)
            else:
                response_text = str(response)
            
            return response_text
            
        except Exception as e:
            return f"❌ Error processing your question: {str(e)}"

# Initialize the chatbot
chatbot = DocumentChatbot()

# Create Gradio interface
def create_interface():
    with gr.Blocks(
        title="Chat with Your Documents",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 800px !important;
            margin: auto !important;
        }
        """
    ) as iface:
        
        gr.Markdown(
            """
            # πŸ“š Chat with Your Documents
            
            Ask questions about your uploaded documents. The AI will search through your document index and provide relevant answers with sources.
            
            **Example questions:**
            - "What are the main topics covered in the documents?"
            - "Summarize the key findings"
            - "What does the document say about [specific topic]?"
            """
        )
        
        # Chat interface
        chatbot_ui = gr.Chatbot(
            height=400,
            placeholder="Your conversation will appear here...",
            show_copy_button=True
        )
        
        msg = gr.Textbox(
            placeholder="Type your question here...",
            label="Your Question",
            lines=2
        )
        
        # Button row
        with gr.Row():
            submit_btn = gr.Button("Send", variant="primary", scale=2)
            clear_btn = gr.Button("Clear Chat", scale=1)
        
        # Example questions
        gr.Examples(
            examples=[
                ["What are the main topics discussed in the documents?"],
                ["Can you provide a summary of the key points?"],
                ["What are the most important findings?"],
                ["Tell me about the methodology used"],
                ["What conclusions were drawn?"]
            ],
            inputs=msg,
            label="Example Questions"
        )
        
        # Event handlers
        def respond(message, chat_history):
            if not message.strip():
                return chat_history, ""
            
            # Add user message to history
            chat_history.append([message, None])
            
            # Get bot response
            bot_response = chatbot.chat(message, chat_history)
            
            # Update history with bot response
            chat_history[-1][1] = bot_response
            
            return chat_history, ""
        
        def clear_chat():
            return [], ""
        
        # Wire up events
        submit_btn.click(
            respond,
            inputs=[msg, chatbot_ui],
            outputs=[chatbot_ui, msg]
        )
        
        msg.submit(
            respond,
            inputs=[msg, chatbot_ui],
            outputs=[chatbot_ui, msg]
        )
        
        clear_btn.click(clear_chat, outputs=[chatbot_ui, msg])
        
        # Status information
        with gr.Accordion("ℹ️ System Information", open=False):
            status_text = "βœ… Connected to LlamaCloud pipeline" if chatbot.pipeline else "❌ Failed to connect to pipeline"
            gr.Markdown(f"**Status:** {status_text}")
            
            if chatbot.pipeline:
                gr.Markdown("**Configuration:** Using LlamaCloud pipeline directly (no external LLM needed)")
            else:
                gr.Markdown("**Error:** Please check your environment variables and LlamaCloud configuration")
    
    return iface

# Launch the app
if __name__ == "__main__":
    # Check required environment variables
    required_vars = ["LLAMA_CLOUD_API_KEY", "LLAMA_CLOUD_PIPELINE_ID"]
    missing_vars = [var for var in required_vars if not os.getenv(var)]
    
    if missing_vars:
        print(f"❌ Missing required environment variables: {', '.join(missing_vars)}")
        print("Please set them in your Hugging Face Space secrets or .env file")
    
    # Create and launch interface
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )