NaderAfshar commited on
Commit
d0d12cc
·
1 Parent(s): e925362

Added csv_agent files

Browse files
Files changed (4) hide show
  1. .env +1 -0
  2. Sample_Data.csv +13 -0
  3. csv_agent_with_chart.py +113 -0
  4. requirements.txt +8 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ COHERE_API_KEY=p9Qnpw98wKgjWBBgiCW3JWBmskTkd6AL3kkutDYA
Sample_Data.csv ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ usecase,run,score,temperature,tokens,latency
2
+ extract_names,A,0.5,0.3,103,1.12
3
+ draft_email,A,0.6,0.3,252,2.5
4
+ summarize_article,A,0.8,0.3,350,4.2
5
+ extract_names,B,0.2,0.3,101,2.85
6
+ draft_email,B,0.4,0.3,230,3.2
7
+ summarize_article,B,0.6,0.3,370,4.2
8
+ extract_names,C,0.7,0.3,101,2.22
9
+ draft_email,C,0.5,0.3,221,2.5
10
+ summarize_article,C,0.1,0.3,361,3.9
11
+ extract_names,D,0.7,0.5,120,3.2
12
+ draft_email,D,0.8,0.5,280,3.4
13
+ summarize_article,D,0.9,0.5,342,4.8
csv_agent_with_chart.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import tempfile
4
+ import pandas as pd
5
+ import gradio as gr
6
+ from dotenv import load_dotenv
7
+ from PIL import Image
8
+ from langchain_cohere import ChatCohere, create_csv_agent
9
+
10
+ # Load environment variables
11
+ load_dotenv()
12
+ COHERE_API_KEY = os.getenv("COHERE_API_KEY")
13
+ os.environ['COHERE_API_KEY'] = COHERE_API_KEY
14
+
15
+ # Initialize the Cohere LLM
16
+ llm = ChatCohere(cohere_api_key=COHERE_API_KEY,
17
+ model="command-r-plus-08-2024",
18
+ temperature=0)
19
+
20
+ # Placeholders
21
+ agent_executor = None
22
+ uploaded_df = None
23
+
24
+ # Upload CSV
25
+ def upload_csv(file):
26
+ global agent_executor, uploaded_df
27
+ try:
28
+ uploaded_df = pd.read_csv(file.name)
29
+ temp_csv_path = os.path.join(tempfile.gettempdir(), "temp.csv")
30
+ uploaded_df.to_csv(temp_csv_path, index=False)
31
+ agent_executor = create_csv_agent(llm, temp_csv_path)
32
+ return "✅ CSV uploaded successfully!", uploaded_df.head(), gr.update(visible=False)
33
+ except Exception as e:
34
+ return f"❌ Error uploading CSV: {e}", None, gr.update(visible=False)
35
+
36
+ # Handle User Questions
37
+ def ask_question(question):
38
+ global agent_executor
39
+
40
+ if not agent_executor:
41
+ return "❗ Please upload a CSV file first.", gr.update(visible=False)
42
+
43
+ try:
44
+ # Agent Response
45
+ response = agent_executor.invoke({"input": question})
46
+ response_message = response.get("output")
47
+
48
+ # Detect Markdown-style image reference
49
+ image_match = re.search(r'!\[.*?\]\("(?P<filename>[^"]+\.png)"\)', response_message)
50
+ if image_match:
51
+ image_path = image_match.group("filename")
52
+
53
+ # Remove the Markdown image reference from the response
54
+ response_message = re.sub(r'!\[.*?\]\("[^"]+\.png"\)', '', response_message).strip()
55
+
56
+ # Check if the image exists and load it
57
+ if os.path.exists(image_path):
58
+ return response_message, gr.update(value=image_path, visible=True)
59
+
60
+ return response_message, gr.update(visible=False)
61
+
62
+ except Exception as e:
63
+ return f"⚠️ Failed to process the question: {e}", gr.update(visible=False)
64
+
65
+ # Reset Agent
66
+ def reset_agent():
67
+ global agent_executor, uploaded_df
68
+ agent_executor = None
69
+ uploaded_df = None
70
+ return gr.update(value="🔄 Agent reset. You can upload a new CSV."), None, gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)
71
+
72
+ # Gradio Interface
73
+ with gr.Blocks(css="""
74
+ .gr-input, .gr-output, textarea, .gr-dataframe, .gr-image {
75
+ background-color: #e6f7ff !important;
76
+ border: 2px solid #007acc !important;
77
+ padding: 10px !important;
78
+ border-radius: 8px !important;
79
+ }
80
+ label, .gr-box label {
81
+ color: #003366 !important;
82
+ font-weight: bold !important;
83
+ font-size: 14px !important;
84
+ }
85
+ """) as demo:
86
+ gr.Markdown("# 📊 CSV Agent with Cohere LLM \n ### Nader Afshar")
87
+
88
+ # File Upload Section
89
+ with gr.Row():
90
+ file_input = gr.File(label="Upload CSV", file_types=['.csv'])
91
+ upload_button = gr.Button("Upload")
92
+
93
+ upload_status = gr.Textbox(label="Upload Status", interactive=False)
94
+ df_head_output = gr.Dataframe(label="CSV Preview (Head)", interactive=False)
95
+
96
+ # Question Section
97
+ question_input = gr.Textbox(label="Ask a Question", placeholder="Type your question here...")
98
+ submit_button = gr.Button("Submit Question")
99
+
100
+ # Output Section
101
+ response_output = gr.Textbox(label="Response", interactive=False)
102
+ image_output = gr.Image(label="Generated Chart", visible=False)
103
+
104
+ # Reset Button
105
+ reset_button = gr.Button("Reset Agent")
106
+
107
+ # Event Handlers
108
+ upload_button.click(upload_csv, inputs=file_input, outputs=[upload_status, df_head_output, image_output])
109
+ submit_button.click(ask_question, inputs=question_input, outputs=[response_output, image_output])
110
+ reset_button.click(reset_agent, outputs=[upload_status, df_head_output, image_output, file_input, upload_button])
111
+
112
+ # Launch the Gradio App
113
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ pandas==2.2.2 # For CSV file handling
3
+ python-dotenv==1.0.1 # For loading environment variables
4
+ langchain==0.3.11 # Core LangChain library
5
+ langchain-experimental==0.3.3 # For experimental LangChain features
6
+ cohere==5.13.3 # Cohere LLM
7
+ langchain-cohere==0.3.3 # Cohere extensions for langchain
8
+ python-multipart==0.0.6 # For file upload handling in FastAPI