pvanand commited on
Commit
d0c153c
·
verified ·
1 Parent(s): d88f68d

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +9 -42
main.py CHANGED
@@ -19,9 +19,6 @@ import requests
19
  import uvicorn
20
  import re
21
  from fastapi.staticfiles import StaticFiles
22
- from langchain_core.runnables import RunnableConfig
23
- from langchain_core.prompts import ChatPromptTemplate
24
- from datetime import datetime
25
 
26
  app = FastAPI()
27
 
@@ -43,15 +40,18 @@ class CodeExecutionResult:
43
  API_URL = "https://pvanand-code-execution-files-v5.hf.space"
44
 
45
  @tool
46
- def execute_python(code: str):
47
  """Execute Python code in an IPython interactiveshell and return the output.
48
  The returned artifacts (if present) are automatically rendered in the UI and visible to the user.
49
  Args:
50
- code: Valid Python code with correct indentation and syntax including necessary imports.
51
-
52
  Available Libraries:
53
  # Use plotly as the default charting library
54
-
 
 
 
 
55
  matplotlib
56
  pandas
57
  plotly
@@ -96,22 +96,10 @@ def execute_python(code: str):
96
  # Configure the memory and model"
97
  memory = MemorySaver()
98
  model = ChatOpenAI(model="gpt-4o-mini", streaming=True)
99
- prompt = ChatPromptTemplate.from_messages([
100
- ("system", f"You are a Data Visualization assistant.You have access to a jupyter client with access to internet for python code execution. Your taks is to assist users with your data analysis and visualization expertise. Today's date is {datetime.now().strftime('%Y-%m-%d')}. The current folder contains the following files: {{collection_files}}"),
101
- ("placeholder", "{messages}"),
102
- ])
103
 
104
  def state_modifier(state) -> list[BaseMessage]:
105
- collection_files = "None"
106
- # Format the prompt with the current state
107
- formatted_prompt = prompt.invoke({
108
- "collection_files": collection_files,
109
- "messages": state["messages"]
110
- })
111
-
112
- # Trim the messages
113
  return trim_messages(
114
- formatted_prompt,
115
  token_counter=len,
116
  max_tokens=16000,
117
  strategy="last",
@@ -162,28 +150,7 @@ async def chat(input_data: ChatInput):
162
  yield f"{json.dumps({'type': 'tool_start', 'tool': event['name'], 'input': tool_input})}\n"
163
 
164
  elif kind == "on_tool_end":
165
- tool_output = event['data'].get('output', '').content
166
- #print(type(tool_output))
167
- #print(dir(tool_output))
168
- #print the keys
169
- pattern = r'data: (.*?)\ndata:'
170
- match = re.search(pattern, tool_output)
171
- print(tool_output)
172
-
173
- if match:
174
- tool_output_json = match.group(1).strip()
175
- try:
176
- tool_output = json.loads(tool_output_json)
177
- if "artifacts" in tool_output:
178
- for artifact in tool_output["artifacts"]:
179
- artifact_content = requests.get(f"{API_URL}/artifact/{artifact['artifact_id']}").content
180
- print(artifact_content)
181
- tool_output["artifacts"][artifact["artifact_id"]] = artifact_content
182
- except Exception as e:
183
- print(e)
184
- print("Error parsing tool output as json: ", tool_output)
185
- else:
186
- print("No match found in tool output")
187
  yield f"{json.dumps({'type': 'tool_end', 'tool': event['name'], 'output': tool_output})}\n"
188
  return EventSourceResponse(
189
  generate(),
 
19
  import uvicorn
20
  import re
21
  from fastapi.staticfiles import StaticFiles
 
 
 
22
 
23
  app = FastAPI()
24
 
 
40
  API_URL = "https://pvanand-code-execution-files-v5.hf.space"
41
 
42
  @tool
43
+ def execute_python(code: str) -> str:
44
  """Execute Python code in an IPython interactiveshell and return the output.
45
  The returned artifacts (if present) are automatically rendered in the UI and visible to the user.
46
  Args:
47
+ code: The Python code to execute
 
48
  Available Libraries:
49
  # Use plotly as the default charting library
50
+ # While using yfinance to pull stock data, Always clean the multiindex columns as this might cause issues in plotting plotly charts
51
+ # Remove the ticker level from columns if it exists
52
+ yf_data = yf.download(symbol, start=start_date, end=end_date)
53
+ if isinstance(yf_data.columns, pd.MultiIndex):
54
+ yf_data.columns = yf_data.columns.get_level_values(0)
55
  matplotlib
56
  pandas
57
  plotly
 
96
  # Configure the memory and model"
97
  memory = MemorySaver()
98
  model = ChatOpenAI(model="gpt-4o-mini", streaming=True)
 
 
 
 
99
 
100
  def state_modifier(state) -> list[BaseMessage]:
 
 
 
 
 
 
 
 
101
  return trim_messages(
102
+ state["messages"],
103
  token_counter=len,
104
  max_tokens=16000,
105
  strategy="last",
 
150
  yield f"{json.dumps({'type': 'tool_start', 'tool': event['name'], 'input': tool_input})}\n"
151
 
152
  elif kind == "on_tool_end":
153
+ tool_output = event['data'].get('output', '').content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  yield f"{json.dumps({'type': 'tool_end', 'tool': event['name'], 'output': tool_output})}\n"
155
  return EventSourceResponse(
156
  generate(),