Spaces:
Sleeping
Sleeping
cuizhanming
commited on
Commit
·
af9a32a
1
Parent(s):
086669e
Update agent file
Browse files- README.md +65 -15
- agent.py +55 -50
- app.py +1 -1
- code_interpreter.py +0 -281
- explore_metadata.ipynb +0 -336
- image_processing.py +0 -26
- supabase_docs.csv +0 -0
- system_prompt.txt +1 -1
- test.ipynb +459 -0
README.md
CHANGED
|
@@ -1,15 +1,65 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
## 1. Setup Supabase for Vector Store, following [run this SQL Editor](https://supabase.com/dashboard/project/upkfycxsetvrlochkrti/sql/c412918f-ec41-4030-9261-80bc415e247e)
|
| 4 |
+
|
| 5 |
+
- enable `vector` extension;
|
| 6 |
+
- create `documents` table;
|
| 7 |
+
- create `match_documents_langchain` function.
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
-- Enable the pgvector extension to work with embedding vectors
|
| 11 |
+
create extension vector;
|
| 12 |
+
|
| 13 |
+
-- Create a table to store your documents
|
| 14 |
+
create table documents (
|
| 15 |
+
id bigserial primary key,
|
| 16 |
+
content text, -- corresponds to Document.pageContent
|
| 17 |
+
metadata jsonb, -- corresponds to Document.metadata
|
| 18 |
+
embedding vector -- 1536 works for OpenAI embeddings, change if needed
|
| 19 |
+
);
|
| 20 |
+
|
| 21 |
+
-- Create a function to search for documents
|
| 22 |
+
create function match_documents_langchain (
|
| 23 |
+
query_embedding vector,
|
| 24 |
+
match_count int default null,
|
| 25 |
+
filter jsonb DEFAULT '{}'
|
| 26 |
+
) returns table (
|
| 27 |
+
id bigint,
|
| 28 |
+
content text,
|
| 29 |
+
metadata jsonb,
|
| 30 |
+
similarity float
|
| 31 |
+
)
|
| 32 |
+
language plpgsql
|
| 33 |
+
as $$
|
| 34 |
+
#variable_conflict use_column
|
| 35 |
+
begin
|
| 36 |
+
return query
|
| 37 |
+
select
|
| 38 |
+
id,
|
| 39 |
+
content,
|
| 40 |
+
metadata,
|
| 41 |
+
1 - (documents.embedding <=> query_embedding) as similarity
|
| 42 |
+
from documents
|
| 43 |
+
where metadata @> filter
|
| 44 |
+
order by documents.embedding <=> query_embedding
|
| 45 |
+
limit match_count;
|
| 46 |
+
end;
|
| 47 |
+
$$;
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## 2. Setup Supabase API Key
|
| 51 |
+
|
| 52 |
+
```shell
|
| 53 |
+
export SUPABASE_URL=https://upkfycxsetvrlochkrti.supabase.co
|
| 54 |
+
export SUPABASE_SERVICE_KEY=
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
## 3. Setup Google Gemini API Key, or Groq Cloud
|
| 58 |
+
|
| 59 |
+
```shell
|
| 60 |
+
# Google Gemini
|
| 61 |
+
export GOOGLE_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxx_xxxxxxxx
|
| 62 |
+
# Groq Cloud
|
| 63 |
+
export GROQ_API_KEY=gsk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
| 64 |
+
```
|
| 65 |
+
|
agent.py
CHANGED
|
@@ -18,9 +18,11 @@ from supabase.client import Client, create_client
|
|
| 18 |
|
| 19 |
load_dotenv()
|
| 20 |
|
|
|
|
| 21 |
@tool
|
| 22 |
def multiply(a: int, b: int) -> int:
|
| 23 |
"""Multiply two numbers.
|
|
|
|
| 24 |
Args:
|
| 25 |
a: first int
|
| 26 |
b: second int
|
|
@@ -30,7 +32,7 @@ def multiply(a: int, b: int) -> int:
|
|
| 30 |
@tool
|
| 31 |
def add(a: int, b: int) -> int:
|
| 32 |
"""Add two numbers.
|
| 33 |
-
|
| 34 |
Args:
|
| 35 |
a: first int
|
| 36 |
b: second int
|
|
@@ -40,7 +42,7 @@ def add(a: int, b: int) -> int:
|
|
| 40 |
@tool
|
| 41 |
def subtract(a: int, b: int) -> int:
|
| 42 |
"""Subtract two numbers.
|
| 43 |
-
|
| 44 |
Args:
|
| 45 |
a: first int
|
| 46 |
b: second int
|
|
@@ -50,7 +52,7 @@ def subtract(a: int, b: int) -> int:
|
|
| 50 |
@tool
|
| 51 |
def divide(a: int, b: int) -> int:
|
| 52 |
"""Divide two numbers.
|
| 53 |
-
|
| 54 |
Args:
|
| 55 |
a: first int
|
| 56 |
b: second int
|
|
@@ -62,7 +64,7 @@ def divide(a: int, b: int) -> int:
|
|
| 62 |
@tool
|
| 63 |
def modulus(a: int, b: int) -> int:
|
| 64 |
"""Get the modulus of two numbers.
|
| 65 |
-
|
| 66 |
Args:
|
| 67 |
a: first int
|
| 68 |
b: second int
|
|
@@ -72,7 +74,7 @@ def modulus(a: int, b: int) -> int:
|
|
| 72 |
@tool
|
| 73 |
def wiki_search(query: str) -> str:
|
| 74 |
"""Search Wikipedia for a query and return maximum 2 results.
|
| 75 |
-
|
| 76 |
Args:
|
| 77 |
query: The search query."""
|
| 78 |
search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
|
@@ -86,7 +88,7 @@ def wiki_search(query: str) -> str:
|
|
| 86 |
@tool
|
| 87 |
def web_search(query: str) -> str:
|
| 88 |
"""Search Tavily for a query and return maximum 3 results.
|
| 89 |
-
|
| 90 |
Args:
|
| 91 |
query: The search query."""
|
| 92 |
search_docs = TavilySearchResults(max_results=3).invoke(query=query)
|
|
@@ -100,7 +102,7 @@ def web_search(query: str) -> str:
|
|
| 100 |
@tool
|
| 101 |
def arvix_search(query: str) -> str:
|
| 102 |
"""Search Arxiv for a query and return maximum 3 result.
|
| 103 |
-
|
| 104 |
Args:
|
| 105 |
query: The search query."""
|
| 106 |
search_docs = ArxivLoader(query=query, load_max_docs=3).load()
|
|
@@ -111,31 +113,36 @@ def arvix_search(query: str) -> str:
|
|
| 111 |
])
|
| 112 |
return {"arvix_results": formatted_search_docs}
|
| 113 |
|
|
|
|
|
|
|
|
|
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
# load the system prompt from the file
|
| 117 |
-
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
| 118 |
-
system_prompt = f.read()
|
| 119 |
-
|
| 120 |
-
# System message
|
| 121 |
-
sys_msg = SystemMessage(content=system_prompt)
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
supabase: Client = create_client(
|
| 126 |
-
|
| 127 |
-
os.environ.get("SUPABASE_SERVICE_KEY"))
|
| 128 |
vector_store = SupabaseVectorStore(
|
| 129 |
client=supabase,
|
| 130 |
embedding= embeddings,
|
| 131 |
table_name="documents",
|
| 132 |
query_name="match_documents_langchain",
|
| 133 |
)
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
)
|
| 139 |
|
| 140 |
tools = [
|
| 141 |
multiply,
|
|
@@ -145,36 +152,26 @@ tools = [
|
|
| 145 |
modulus,
|
| 146 |
wiki_search,
|
| 147 |
web_search,
|
| 148 |
-
arvix_search
|
| 149 |
]
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
# TODO: Add huggingface endpoint
|
| 163 |
-
llm = ChatHuggingFace(
|
| 164 |
-
llm=HuggingFaceEndpoint(
|
| 165 |
-
url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
|
| 166 |
-
temperature=0,
|
| 167 |
-
),
|
| 168 |
-
)
|
| 169 |
-
else:
|
| 170 |
-
raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
|
| 171 |
-
# Bind tools to LLM
|
| 172 |
llm_with_tools = llm.bind_tools(tools)
|
| 173 |
|
| 174 |
# Node
|
| 175 |
def assistant(state: MessagesState):
|
| 176 |
"""Assistant node"""
|
| 177 |
-
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
| 178 |
|
| 179 |
def retriever(state: MessagesState):
|
| 180 |
"""Retriever node"""
|
|
@@ -184,6 +181,7 @@ def build_graph(provider: str = "groq"):
|
|
| 184 |
)
|
| 185 |
return {"messages": [sys_msg] + state["messages"] + [example_msg]}
|
| 186 |
|
|
|
|
| 187 |
builder = StateGraph(MessagesState)
|
| 188 |
builder.add_node("retriever", retriever)
|
| 189 |
builder.add_node("assistant", assistant)
|
|
@@ -192,20 +190,27 @@ def build_graph(provider: str = "groq"):
|
|
| 192 |
builder.add_edge("retriever", "assistant")
|
| 193 |
builder.add_conditional_edges(
|
| 194 |
"assistant",
|
|
|
|
|
|
|
| 195 |
tools_condition,
|
| 196 |
)
|
| 197 |
builder.add_edge("tools", "assistant")
|
| 198 |
|
| 199 |
# Compile graph
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
# test
|
| 203 |
if __name__ == "__main__":
|
| 204 |
question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
|
| 205 |
# Build the graph
|
| 206 |
-
graph = build_graph(
|
| 207 |
# Run the graph
|
| 208 |
messages = [HumanMessage(content=question)]
|
| 209 |
messages = graph.invoke({"messages": messages})
|
| 210 |
for m in messages["messages"]:
|
| 211 |
-
m.pretty_print()
|
|
|
|
| 18 |
|
| 19 |
load_dotenv()
|
| 20 |
|
| 21 |
+
|
| 22 |
@tool
|
| 23 |
def multiply(a: int, b: int) -> int:
|
| 24 |
"""Multiply two numbers.
|
| 25 |
+
|
| 26 |
Args:
|
| 27 |
a: first int
|
| 28 |
b: second int
|
|
|
|
| 32 |
@tool
|
| 33 |
def add(a: int, b: int) -> int:
|
| 34 |
"""Add two numbers.
|
| 35 |
+
|
| 36 |
Args:
|
| 37 |
a: first int
|
| 38 |
b: second int
|
|
|
|
| 42 |
@tool
|
| 43 |
def subtract(a: int, b: int) -> int:
|
| 44 |
"""Subtract two numbers.
|
| 45 |
+
|
| 46 |
Args:
|
| 47 |
a: first int
|
| 48 |
b: second int
|
|
|
|
| 52 |
@tool
|
| 53 |
def divide(a: int, b: int) -> int:
|
| 54 |
"""Divide two numbers.
|
| 55 |
+
|
| 56 |
Args:
|
| 57 |
a: first int
|
| 58 |
b: second int
|
|
|
|
| 64 |
@tool
|
| 65 |
def modulus(a: int, b: int) -> int:
|
| 66 |
"""Get the modulus of two numbers.
|
| 67 |
+
|
| 68 |
Args:
|
| 69 |
a: first int
|
| 70 |
b: second int
|
|
|
|
| 74 |
@tool
|
| 75 |
def wiki_search(query: str) -> str:
|
| 76 |
"""Search Wikipedia for a query and return maximum 2 results.
|
| 77 |
+
|
| 78 |
Args:
|
| 79 |
query: The search query."""
|
| 80 |
search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
|
|
|
| 88 |
@tool
|
| 89 |
def web_search(query: str) -> str:
|
| 90 |
"""Search Tavily for a query and return maximum 3 results.
|
| 91 |
+
|
| 92 |
Args:
|
| 93 |
query: The search query."""
|
| 94 |
search_docs = TavilySearchResults(max_results=3).invoke(query=query)
|
|
|
|
| 102 |
@tool
|
| 103 |
def arvix_search(query: str) -> str:
|
| 104 |
"""Search Arxiv for a query and return maximum 3 result.
|
| 105 |
+
|
| 106 |
Args:
|
| 107 |
query: The search query."""
|
| 108 |
search_docs = ArxivLoader(query=query, load_max_docs=3).load()
|
|
|
|
| 113 |
])
|
| 114 |
return {"arvix_results": formatted_search_docs}
|
| 115 |
|
| 116 |
+
@tool
|
| 117 |
+
def similar_question_search(question: str) -> str:
|
| 118 |
+
"""Search the vector database for similar questions and return the first results.
|
| 119 |
|
| 120 |
+
Args:
|
| 121 |
+
question: the question human provided."""
|
| 122 |
+
matched_docs = vector_store.similarity_search(query, 3)
|
| 123 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
| 124 |
+
[
|
| 125 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
|
| 126 |
+
for doc in matched_docs
|
| 127 |
+
])
|
| 128 |
+
return {"similar_questions": formatted_search_docs}
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
supabase_url = os.environ.get("SUPABASE_URL")
|
| 132 |
+
supabase_key = os.environ.get("SUPABASE_SERVICE_KEY")
|
| 133 |
+
supabase: Client = create_client(supabase_url, supabase_key)
|
| 134 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
|
|
|
| 135 |
vector_store = SupabaseVectorStore(
|
| 136 |
client=supabase,
|
| 137 |
embedding= embeddings,
|
| 138 |
table_name="documents",
|
| 139 |
query_name="match_documents_langchain",
|
| 140 |
)
|
| 141 |
+
# question_retrieve_tool = create_retriever_tool(
|
| 142 |
+
# vector_store.as_retriever(),
|
| 143 |
+
# "Question Retriever",
|
| 144 |
+
# "Find similar questions in the vector database for the given question.",
|
| 145 |
+
# )
|
| 146 |
|
| 147 |
tools = [
|
| 148 |
multiply,
|
|
|
|
| 152 |
modulus,
|
| 153 |
wiki_search,
|
| 154 |
web_search,
|
| 155 |
+
arvix_search
|
| 156 |
]
|
| 157 |
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# load the system prompt from the file
|
| 161 |
+
with open('system_prompt.txt', 'r') as f:
|
| 162 |
+
system_prompt = f.read()
|
| 163 |
+
# System message
|
| 164 |
+
sys_msg = SystemMessage(content=system_prompt)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def build_graph():
|
| 168 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash-preview-05-20")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
llm_with_tools = llm.bind_tools(tools)
|
| 170 |
|
| 171 |
# Node
|
| 172 |
def assistant(state: MessagesState):
|
| 173 |
"""Assistant node"""
|
| 174 |
+
return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}
|
| 175 |
|
| 176 |
def retriever(state: MessagesState):
|
| 177 |
"""Retriever node"""
|
|
|
|
| 181 |
)
|
| 182 |
return {"messages": [sys_msg] + state["messages"] + [example_msg]}
|
| 183 |
|
| 184 |
+
# Build graph
|
| 185 |
builder = StateGraph(MessagesState)
|
| 186 |
builder.add_node("retriever", retriever)
|
| 187 |
builder.add_node("assistant", assistant)
|
|
|
|
| 190 |
builder.add_edge("retriever", "assistant")
|
| 191 |
builder.add_conditional_edges(
|
| 192 |
"assistant",
|
| 193 |
+
# If the latest message (result) from assistant is a tool call -> tools_condition routes to tools
|
| 194 |
+
# If the latest message (result) from assistant is a not a tool call -> tools_condition routes to END
|
| 195 |
tools_condition,
|
| 196 |
)
|
| 197 |
builder.add_edge("tools", "assistant")
|
| 198 |
|
| 199 |
# Compile graph
|
| 200 |
+
graph = builder.compile()
|
| 201 |
+
|
| 202 |
+
# from IPython.display import Image, display
|
| 203 |
+
# display(Image(graph.get_graph(xray=True).draw_mermaid_png()))
|
| 204 |
+
|
| 205 |
+
return graph
|
| 206 |
+
|
| 207 |
|
|
|
|
| 208 |
if __name__ == "__main__":
|
| 209 |
question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
|
| 210 |
# Build the graph
|
| 211 |
+
graph = build_graph()
|
| 212 |
# Run the graph
|
| 213 |
messages = [HumanMessage(content=question)]
|
| 214 |
messages = graph.invoke({"messages": messages})
|
| 215 |
for m in messages["messages"]:
|
| 216 |
+
m.pretty_print()
|
app.py
CHANGED
|
@@ -21,7 +21,7 @@ class BasicAgent:
|
|
| 21 |
"""A langgraph agent."""
|
| 22 |
def __init__(self):
|
| 23 |
print("BasicAgent initialized.")
|
| 24 |
-
self.graph = build_graph(
|
| 25 |
|
| 26 |
def __call__(self, question: str) -> str:
|
| 27 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
|
|
|
| 21 |
"""A langgraph agent."""
|
| 22 |
def __init__(self):
|
| 23 |
print("BasicAgent initialized.")
|
| 24 |
+
self.graph = build_graph()
|
| 25 |
|
| 26 |
def __call__(self, question: str) -> str:
|
| 27 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
code_interpreter.py
DELETED
|
@@ -1,281 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import io
|
| 3 |
-
import sys
|
| 4 |
-
import uuid
|
| 5 |
-
import base64
|
| 6 |
-
import traceback
|
| 7 |
-
import contextlib
|
| 8 |
-
import tempfile
|
| 9 |
-
import subprocess
|
| 10 |
-
import sqlite3
|
| 11 |
-
from typing import Dict, List, Any, Optional, Union
|
| 12 |
-
import numpy as np
|
| 13 |
-
import pandas as pd
|
| 14 |
-
import matplotlib.pyplot as plt
|
| 15 |
-
from PIL import Image
|
| 16 |
-
|
| 17 |
-
class CodeInterpreter:
|
| 18 |
-
def __init__(self, allowed_modules=None, max_execution_time=30, working_directory=None):
|
| 19 |
-
"""Initialize the code interpreter with safety measures."""
|
| 20 |
-
self.allowed_modules = allowed_modules or [
|
| 21 |
-
"numpy", "pandas", "matplotlib", "scipy", "sklearn",
|
| 22 |
-
"math", "random", "statistics", "datetime", "collections",
|
| 23 |
-
"itertools", "functools", "operator", "re", "json",
|
| 24 |
-
"sympy", "networkx", "nltk", "PIL", "pytesseract",
|
| 25 |
-
"cmath", "uuid", "tempfile", "requests", "urllib"
|
| 26 |
-
]
|
| 27 |
-
self.max_execution_time = max_execution_time
|
| 28 |
-
self.working_directory = working_directory or os.path.join(os.getcwd())
|
| 29 |
-
if not os.path.exists(self.working_directory):
|
| 30 |
-
os.makedirs(self.working_directory)
|
| 31 |
-
|
| 32 |
-
self.globals = {
|
| 33 |
-
"__builtins__": __builtins__,
|
| 34 |
-
"np": np,
|
| 35 |
-
"pd": pd,
|
| 36 |
-
"plt": plt,
|
| 37 |
-
"Image": Image,
|
| 38 |
-
}
|
| 39 |
-
self.temp_sqlite_db = os.path.join(tempfile.gettempdir(), "code_exec.db")
|
| 40 |
-
|
| 41 |
-
def execute_code(self, code: str, language: str = "python") -> Dict[str, Any]:
|
| 42 |
-
"""Execute the provided code in the selected programming language."""
|
| 43 |
-
language = language.lower()
|
| 44 |
-
execution_id = str(uuid.uuid4())
|
| 45 |
-
|
| 46 |
-
result = {
|
| 47 |
-
"execution_id": execution_id,
|
| 48 |
-
"status": "error",
|
| 49 |
-
"stdout": "",
|
| 50 |
-
"stderr": "",
|
| 51 |
-
"result": None,
|
| 52 |
-
"plots": [],
|
| 53 |
-
"dataframes": []
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
try:
|
| 57 |
-
if language == "python":
|
| 58 |
-
return self._execute_python(code, execution_id)
|
| 59 |
-
elif language == "bash":
|
| 60 |
-
return self._execute_bash(code, execution_id)
|
| 61 |
-
elif language == "sql":
|
| 62 |
-
return self._execute_sql(code, execution_id)
|
| 63 |
-
elif language == "c":
|
| 64 |
-
return self._execute_c(code, execution_id)
|
| 65 |
-
elif language == "java":
|
| 66 |
-
return self._execute_java(code, execution_id)
|
| 67 |
-
else:
|
| 68 |
-
result["stderr"] = f"Unsupported language: {language}"
|
| 69 |
-
except Exception as e:
|
| 70 |
-
result["stderr"] = str(e)
|
| 71 |
-
|
| 72 |
-
return result
|
| 73 |
-
|
| 74 |
-
def _execute_python(self, code: str, execution_id: str) -> dict:
|
| 75 |
-
output_buffer = io.StringIO()
|
| 76 |
-
error_buffer = io.StringIO()
|
| 77 |
-
result = {
|
| 78 |
-
"execution_id": execution_id,
|
| 79 |
-
"status": "error",
|
| 80 |
-
"stdout": "",
|
| 81 |
-
"stderr": "",
|
| 82 |
-
"result": None,
|
| 83 |
-
"plots": [],
|
| 84 |
-
"dataframes": []
|
| 85 |
-
}
|
| 86 |
-
|
| 87 |
-
try:
|
| 88 |
-
exec_dir = os.path.join(self.working_directory, execution_id)
|
| 89 |
-
os.makedirs(exec_dir, exist_ok=True)
|
| 90 |
-
plt.switch_backend('Agg')
|
| 91 |
-
|
| 92 |
-
with contextlib.redirect_stdout(output_buffer), contextlib.redirect_stderr(error_buffer):
|
| 93 |
-
exec_result = exec(code, self.globals)
|
| 94 |
-
|
| 95 |
-
if plt.get_fignums():
|
| 96 |
-
for i, fig_num in enumerate(plt.get_fignums()):
|
| 97 |
-
fig = plt.figure(fig_num)
|
| 98 |
-
img_path = os.path.join(exec_dir, f"plot_{i}.png")
|
| 99 |
-
fig.savefig(img_path)
|
| 100 |
-
with open(img_path, "rb") as img_file:
|
| 101 |
-
img_data = base64.b64encode(img_file.read()).decode('utf-8')
|
| 102 |
-
result["plots"].append({
|
| 103 |
-
"figure_number": fig_num,
|
| 104 |
-
"data": img_data
|
| 105 |
-
})
|
| 106 |
-
|
| 107 |
-
for var_name, var_value in self.globals.items():
|
| 108 |
-
if isinstance(var_value, pd.DataFrame) and len(var_value) > 0:
|
| 109 |
-
result["dataframes"].append({
|
| 110 |
-
"name": var_name,
|
| 111 |
-
"head": var_value.head().to_dict(),
|
| 112 |
-
"shape": var_value.shape,
|
| 113 |
-
"dtypes": str(var_value.dtypes)
|
| 114 |
-
})
|
| 115 |
-
|
| 116 |
-
result["status"] = "success"
|
| 117 |
-
result["stdout"] = output_buffer.getvalue()
|
| 118 |
-
result["result"] = exec_result
|
| 119 |
-
|
| 120 |
-
except Exception as e:
|
| 121 |
-
result["status"] = "error"
|
| 122 |
-
result["stderr"] = f"{error_buffer.getvalue()}\n{traceback.format_exc()}"
|
| 123 |
-
|
| 124 |
-
return result
|
| 125 |
-
|
| 126 |
-
def _execute_bash(self, code: str, execution_id: str) -> dict:
|
| 127 |
-
try:
|
| 128 |
-
completed = subprocess.run(
|
| 129 |
-
code, shell=True, capture_output=True, text=True, timeout=self.max_execution_time
|
| 130 |
-
)
|
| 131 |
-
return {
|
| 132 |
-
"execution_id": execution_id,
|
| 133 |
-
"status": "success" if completed.returncode == 0 else "error",
|
| 134 |
-
"stdout": completed.stdout,
|
| 135 |
-
"stderr": completed.stderr,
|
| 136 |
-
"result": None,
|
| 137 |
-
"plots": [],
|
| 138 |
-
"dataframes": []
|
| 139 |
-
}
|
| 140 |
-
except subprocess.TimeoutExpired:
|
| 141 |
-
return {
|
| 142 |
-
"execution_id": execution_id,
|
| 143 |
-
"status": "error",
|
| 144 |
-
"stdout": "",
|
| 145 |
-
"stderr": "Execution timed out.",
|
| 146 |
-
"result": None,
|
| 147 |
-
"plots": [],
|
| 148 |
-
"dataframes": []
|
| 149 |
-
}
|
| 150 |
-
|
| 151 |
-
def _execute_sql(self, code: str, execution_id: str) -> dict:
|
| 152 |
-
result = {
|
| 153 |
-
"execution_id": execution_id,
|
| 154 |
-
"status": "error",
|
| 155 |
-
"stdout": "",
|
| 156 |
-
"stderr": "",
|
| 157 |
-
"result": None,
|
| 158 |
-
"plots": [],
|
| 159 |
-
"dataframes": []
|
| 160 |
-
}
|
| 161 |
-
try:
|
| 162 |
-
conn = sqlite3.connect(self.temp_sqlite_db)
|
| 163 |
-
cur = conn.cursor()
|
| 164 |
-
cur.execute(code)
|
| 165 |
-
if code.strip().lower().startswith("select"):
|
| 166 |
-
columns = [description[0] for description in cur.description]
|
| 167 |
-
rows = cur.fetchall()
|
| 168 |
-
df = pd.DataFrame(rows, columns=columns)
|
| 169 |
-
result["dataframes"].append({
|
| 170 |
-
"name": "query_result",
|
| 171 |
-
"head": df.head().to_dict(),
|
| 172 |
-
"shape": df.shape,
|
| 173 |
-
"dtypes": str(df.dtypes)
|
| 174 |
-
})
|
| 175 |
-
else:
|
| 176 |
-
conn.commit()
|
| 177 |
-
|
| 178 |
-
result["status"] = "success"
|
| 179 |
-
result["stdout"] = "Query executed successfully."
|
| 180 |
-
|
| 181 |
-
except Exception as e:
|
| 182 |
-
result["stderr"] = str(e)
|
| 183 |
-
finally:
|
| 184 |
-
conn.close()
|
| 185 |
-
|
| 186 |
-
return result
|
| 187 |
-
|
| 188 |
-
def _execute_c(self, code: str, execution_id: str) -> dict:
|
| 189 |
-
temp_dir = tempfile.mkdtemp()
|
| 190 |
-
source_path = os.path.join(temp_dir, "program.c")
|
| 191 |
-
binary_path = os.path.join(temp_dir, "program")
|
| 192 |
-
|
| 193 |
-
try:
|
| 194 |
-
with open(source_path, "w") as f:
|
| 195 |
-
f.write(code)
|
| 196 |
-
|
| 197 |
-
compile_proc = subprocess.run(
|
| 198 |
-
["gcc", source_path, "-o", binary_path],
|
| 199 |
-
capture_output=True, text=True, timeout=self.max_execution_time
|
| 200 |
-
)
|
| 201 |
-
if compile_proc.returncode != 0:
|
| 202 |
-
return {
|
| 203 |
-
"execution_id": execution_id,
|
| 204 |
-
"status": "error",
|
| 205 |
-
"stdout": compile_proc.stdout,
|
| 206 |
-
"stderr": compile_proc.stderr,
|
| 207 |
-
"result": None,
|
| 208 |
-
"plots": [],
|
| 209 |
-
"dataframes": []
|
| 210 |
-
}
|
| 211 |
-
|
| 212 |
-
run_proc = subprocess.run(
|
| 213 |
-
[binary_path],
|
| 214 |
-
capture_output=True, text=True, timeout=self.max_execution_time
|
| 215 |
-
)
|
| 216 |
-
return {
|
| 217 |
-
"execution_id": execution_id,
|
| 218 |
-
"status": "success" if run_proc.returncode == 0 else "error",
|
| 219 |
-
"stdout": run_proc.stdout,
|
| 220 |
-
"stderr": run_proc.stderr,
|
| 221 |
-
"result": None,
|
| 222 |
-
"plots": [],
|
| 223 |
-
"dataframes": []
|
| 224 |
-
}
|
| 225 |
-
except Exception as e:
|
| 226 |
-
return {
|
| 227 |
-
"execution_id": execution_id,
|
| 228 |
-
"status": "error",
|
| 229 |
-
"stdout": "",
|
| 230 |
-
"stderr": str(e),
|
| 231 |
-
"result": None,
|
| 232 |
-
"plots": [],
|
| 233 |
-
"dataframes": []
|
| 234 |
-
}
|
| 235 |
-
|
| 236 |
-
def _execute_java(self, code: str, execution_id: str) -> dict:
|
| 237 |
-
temp_dir = tempfile.mkdtemp()
|
| 238 |
-
source_path = os.path.join(temp_dir, "Main.java")
|
| 239 |
-
|
| 240 |
-
try:
|
| 241 |
-
with open(source_path, "w") as f:
|
| 242 |
-
f.write(code)
|
| 243 |
-
|
| 244 |
-
compile_proc = subprocess.run(
|
| 245 |
-
["javac", source_path],
|
| 246 |
-
capture_output=True, text=True, timeout=self.max_execution_time
|
| 247 |
-
)
|
| 248 |
-
if compile_proc.returncode != 0:
|
| 249 |
-
return {
|
| 250 |
-
"execution_id": execution_id,
|
| 251 |
-
"status": "error",
|
| 252 |
-
"stdout": compile_proc.stdout,
|
| 253 |
-
"stderr": compile_proc.stderr,
|
| 254 |
-
"result": None,
|
| 255 |
-
"plots": [],
|
| 256 |
-
"dataframes": []
|
| 257 |
-
}
|
| 258 |
-
|
| 259 |
-
run_proc = subprocess.run(
|
| 260 |
-
["java", "-cp", temp_dir, "Main"],
|
| 261 |
-
capture_output=True, text=True, timeout=self.max_execution_time
|
| 262 |
-
)
|
| 263 |
-
return {
|
| 264 |
-
"execution_id": execution_id,
|
| 265 |
-
"status": "success" if run_proc.returncode == 0 else "error",
|
| 266 |
-
"stdout": run_proc.stdout,
|
| 267 |
-
"stderr": run_proc.stderr,
|
| 268 |
-
"result": None,
|
| 269 |
-
"plots": [],
|
| 270 |
-
"dataframes": []
|
| 271 |
-
}
|
| 272 |
-
except Exception as e:
|
| 273 |
-
return {
|
| 274 |
-
"execution_id": execution_id,
|
| 275 |
-
"status": "error",
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
explore_metadata.ipynb
DELETED
|
@@ -1,336 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"cells": [
|
| 3 |
-
{
|
| 4 |
-
"cell_type": "code",
|
| 5 |
-
"id": "a600d7fc",
|
| 6 |
-
"metadata": {
|
| 7 |
-
"jupyter": {
|
| 8 |
-
"is_executing": true
|
| 9 |
-
}
|
| 10 |
-
},
|
| 11 |
-
"source": [
|
| 12 |
-
"import json \n",
|
| 13 |
-
"with open('metadata.jsonl', 'r') as f: \n",
|
| 14 |
-
" json_list = list(f)\n",
|
| 15 |
-
"\n",
|
| 16 |
-
"json_QA = []\n",
|
| 17 |
-
"for json_str in json_list: \n",
|
| 18 |
-
" json_data = json.loads(json_str)\n",
|
| 19 |
-
" json_QA.append(json_data)"
|
| 20 |
-
],
|
| 21 |
-
"outputs": [],
|
| 22 |
-
"execution_count": null
|
| 23 |
-
},
|
| 24 |
-
{
|
| 25 |
-
"cell_type": "code",
|
| 26 |
-
"execution_count": 10,
|
| 27 |
-
"id": "fa5d8eb8",
|
| 28 |
-
"metadata": {},
|
| 29 |
-
"outputs": [
|
| 30 |
-
{
|
| 31 |
-
"name": "stdout",
|
| 32 |
-
"output_type": "stream",
|
| 33 |
-
"text": [
|
| 34 |
-
"==================================================\n",
|
| 35 |
-
"Task ID: d1af70ea-a9a4-421a-b9cc-94b5e02f1788\n",
|
| 36 |
-
"Question: As of the 2020 census, what was the population difference between the largest county seat and smallest county seat, by land area of the county seat, in Washington state? For population figures, please use the official data from data.census.gov. Please report the integer difference.\n",
|
| 37 |
-
"Level: 2\n",
|
| 38 |
-
"Final Answer: 736455\n",
|
| 39 |
-
"Annotator Metadata: \n",
|
| 40 |
-
" ├── Steps: \n",
|
| 41 |
-
" │ ├── Step 1: Using a web browser, access a search engine and conduct a search, \"Washington cities by area\"\n",
|
| 42 |
-
" │ ├── Step 2: Navigate to the second search result, https://en.wikipedia.org/wiki/List_of_municipalities_in_Washington\n",
|
| 43 |
-
" │ ├── Step 3: Evaluate the page contents, finding the largest and smallest county seats by land area, Seattle and Cathlamet\n",
|
| 44 |
-
" │ ├── Step 4: Using a web browser, navigate to https://data.census.gov/\n",
|
| 45 |
-
" │ ├── Step 5: Using the website's search area, conduct a search, Seattle, Washington\n",
|
| 46 |
-
" │ ├── Step 6: Record the reported 2020 Decennial Census population of Seattle, Washington, 737,015\n",
|
| 47 |
-
" │ ├── Step 7: Using the website's search area, conduct a search, Cathlamet, Washington\n",
|
| 48 |
-
" │ ├── Step 8: Record the reported 2020 Decennial Census population of Cathlamet, Washington, 560\n",
|
| 49 |
-
" │ ├── Step 9: Using a calculator, find the difference in populations,\n",
|
| 50 |
-
" │ ├── \n",
|
| 51 |
-
" │ ├── 737,015 - 560\n",
|
| 52 |
-
" │ ├── 736,455\n",
|
| 53 |
-
" │ ├── Step 10: Report the correct answer to my user in the requested format, \"736,455\"\n",
|
| 54 |
-
" ├── Number of steps: 10\n",
|
| 55 |
-
" ├── How long did this take?: 5 minutes\n",
|
| 56 |
-
" ├── Tools:\n",
|
| 57 |
-
" │ ├── 1. A web browser\n",
|
| 58 |
-
" │ ├── 2. A search engine\n",
|
| 59 |
-
" │ ├── 3. A calculator\n",
|
| 60 |
-
" └── Number of tools: 3\n",
|
| 61 |
-
"==================================================\n"
|
| 62 |
-
]
|
| 63 |
-
}
|
| 64 |
-
],
|
| 65 |
-
"source": [
|
| 66 |
-
"import random\n",
|
| 67 |
-
"random_samples = random.sample(json_QA, 1)\n",
|
| 68 |
-
"for sample in random_samples:\n",
|
| 69 |
-
" print(\"=\" * 50)\n",
|
| 70 |
-
" print(f\"Task ID: {sample['task_id']}\")\n",
|
| 71 |
-
" print(f\"Question: {sample['Question']}\")\n",
|
| 72 |
-
" print(f\"Level: {sample['Level']}\")\n",
|
| 73 |
-
" print(f\"Final Answer: {sample['Final answer']}\")\n",
|
| 74 |
-
" print(f\"Annotator Metadata: \")\n",
|
| 75 |
-
" print(f\" ├── Steps: \")\n",
|
| 76 |
-
" for step in sample['Annotator Metadata']['Steps'].split('\\n'):\n",
|
| 77 |
-
" print(f\" │ ├── {step}\")\n",
|
| 78 |
-
" print(f\" ├── Number of steps: {sample['Annotator Metadata']['Number of steps']}\")\n",
|
| 79 |
-
" print(f\" ├── How long did this take?: {sample['Annotator Metadata']['How long did this take?']}\")\n",
|
| 80 |
-
" print(f\" ├── Tools:\")\n",
|
| 81 |
-
" for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
|
| 82 |
-
" print(f\" │ ├── {tool}\")\n",
|
| 83 |
-
" print(f\" └── Number of tools: {sample['Annotator Metadata']['Number of tools']}\")\n",
|
| 84 |
-
"print(\"=\" * 50)"
|
| 85 |
-
]
|
| 86 |
-
},
|
| 87 |
-
{
|
| 88 |
-
"cell_type": "code",
|
| 89 |
-
"execution_count": 11,
|
| 90 |
-
"id": "05076516",
|
| 91 |
-
"metadata": {},
|
| 92 |
-
"outputs": [],
|
| 93 |
-
"source": [
|
| 94 |
-
"import os\n",
|
| 95 |
-
"from dotenv import load_dotenv\n",
|
| 96 |
-
"from langchain_huggingface import HuggingFaceEmbeddings\n",
|
| 97 |
-
"from langchain_community.vectorstores import SupabaseVectorStore\n",
|
| 98 |
-
"from supabase.client import Client, create_client\n",
|
| 99 |
-
"\n",
|
| 100 |
-
"\n",
|
| 101 |
-
"load_dotenv()\n",
|
| 102 |
-
"embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") # dim=768\n",
|
| 103 |
-
"\n",
|
| 104 |
-
"supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
|
| 105 |
-
"supabase_key = os.environ.get(\"SUPABASE_SERVICE_ROLE_KEY\")\n",
|
| 106 |
-
"supabase: Client = create_client(supabase_url, supabase_key)"
|
| 107 |
-
]
|
| 108 |
-
},
|
| 109 |
-
{
|
| 110 |
-
"cell_type": "code",
|
| 111 |
-
"execution_count": 20,
|
| 112 |
-
"id": "aa1402e3",
|
| 113 |
-
"metadata": {},
|
| 114 |
-
"outputs": [],
|
| 115 |
-
"source": [
|
| 116 |
-
"from langchain.schema import Document\n",
|
| 117 |
-
"docs = []\n",
|
| 118 |
-
"cnt = 0 \n",
|
| 119 |
-
"for sample in json_QA:\n",
|
| 120 |
-
" content = f\"Question : {sample['Question']}\\n\\nFinal answer : {sample['Final answer']}\"\n",
|
| 121 |
-
" doc = {\n",
|
| 122 |
-
" \"id\" : cnt,\n",
|
| 123 |
-
" \"content\" : content,\n",
|
| 124 |
-
" \"metadata\" : {\n",
|
| 125 |
-
" \"source\" : sample['task_id']\n",
|
| 126 |
-
" },\n",
|
| 127 |
-
" \"embedding\" : embeddings.embed_query(content),\n",
|
| 128 |
-
" }\n",
|
| 129 |
-
" docs.append(doc)\n",
|
| 130 |
-
" cnt += 1\n",
|
| 131 |
-
"\n",
|
| 132 |
-
"# upload the documents to the vector database\n",
|
| 133 |
-
"try:\n",
|
| 134 |
-
" response = (\n",
|
| 135 |
-
" supabase.table(\"documents2\")\n",
|
| 136 |
-
" .insert(docs)\n",
|
| 137 |
-
" .execute()\n",
|
| 138 |
-
" )\n",
|
| 139 |
-
"except Exception as exception:\n",
|
| 140 |
-
" print(\"Error inserting data into Supabase:\", exception)\n",
|
| 141 |
-
"\n",
|
| 142 |
-
"# # Save the documents (a list of dict) into a csv file, and manually upload it to Supabase\n",
|
| 143 |
-
"# import pandas as pd\n",
|
| 144 |
-
"# df = pd.DataFrame(docs)\n",
|
| 145 |
-
"# df.to_csv('supabase_docs.csv',index=False)"
|
| 146 |
-
]
|
| 147 |
-
},
|
| 148 |
-
{
|
| 149 |
-
"cell_type": "code",
|
| 150 |
-
"execution_count": 41,
|
| 151 |
-
"id": "9aa7eb5e",
|
| 152 |
-
"metadata": {},
|
| 153 |
-
"outputs": [],
|
| 154 |
-
"source": [
|
| 155 |
-
"# add items to vector database\n",
|
| 156 |
-
"vector_store = SupabaseVectorStore(\n",
|
| 157 |
-
" client=supabase,\n",
|
| 158 |
-
" embedding= embeddings,\n",
|
| 159 |
-
" table_name=\"documents2\",\n",
|
| 160 |
-
" query_name=\"match_documents_2\",\n",
|
| 161 |
-
")\n",
|
| 162 |
-
"retriever = vector_store.as_retriever()"
|
| 163 |
-
]
|
| 164 |
-
},
|
| 165 |
-
{
|
| 166 |
-
"cell_type": "code",
|
| 167 |
-
"execution_count": 42,
|
| 168 |
-
"id": "9eecafd1",
|
| 169 |
-
"metadata": {},
|
| 170 |
-
"outputs": [],
|
| 171 |
-
"source": [
|
| 172 |
-
"query = \"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?\"\n",
|
| 173 |
-
"# matched_docs = vector_store.similarity_search(query, k=2)\n",
|
| 174 |
-
"docs = retriever.invoke(query)"
|
| 175 |
-
]
|
| 176 |
-
},
|
| 177 |
-
{
|
| 178 |
-
"cell_type": "code",
|
| 179 |
-
"execution_count": 43,
|
| 180 |
-
"id": "ff917840",
|
| 181 |
-
"metadata": {},
|
| 182 |
-
"outputs": [
|
| 183 |
-
{
|
| 184 |
-
"data": {
|
| 185 |
-
"text/plain": [
|
| 186 |
-
"Document(metadata={'source': '840bfca7-4f7b-481a-8794-c560c340185d'}, page_content='Question : On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?\\n\\nFinal answer : 80GSFC21M0002')"
|
| 187 |
-
]
|
| 188 |
-
},
|
| 189 |
-
"execution_count": 43,
|
| 190 |
-
"metadata": {},
|
| 191 |
-
"output_type": "execute_result"
|
| 192 |
-
}
|
| 193 |
-
],
|
| 194 |
-
"source": [
|
| 195 |
-
"docs[0]"
|
| 196 |
-
]
|
| 197 |
-
},
|
| 198 |
-
{
|
| 199 |
-
"cell_type": "code",
|
| 200 |
-
"execution_count": 44,
|
| 201 |
-
"id": "01c8f337",
|
| 202 |
-
"metadata": {},
|
| 203 |
-
"outputs": [
|
| 204 |
-
{
|
| 205 |
-
"name": "stdout",
|
| 206 |
-
"output_type": "stream",
|
| 207 |
-
"text": [
|
| 208 |
-
"List of tools used in all samples:\n",
|
| 209 |
-
"Total number of tools used: 83\n",
|
| 210 |
-
" ├── web browser: 107\n",
|
| 211 |
-
" ├── image recognition tools (to identify and parse a figure with three axes): 1\n",
|
| 212 |
-
" ├── search engine: 101\n",
|
| 213 |
-
" ├── calculator: 34\n",
|
| 214 |
-
" ├── unlambda compiler (optional): 1\n",
|
| 215 |
-
" ├── a web browser.: 2\n",
|
| 216 |
-
" ├── a search engine.: 2\n",
|
| 217 |
-
" ├── a calculator.: 1\n",
|
| 218 |
-
" ├── microsoft excel: 5\n",
|
| 219 |
-
" ├── google search: 1\n",
|
| 220 |
-
" ├── ne: 9\n",
|
| 221 |
-
" ├── pdf access: 7\n",
|
| 222 |
-
" ├── file handling: 2\n",
|
| 223 |
-
" ├── python: 3\n",
|
| 224 |
-
" ├── image recognition tools: 12\n",
|
| 225 |
-
" ├── jsonld file access: 1\n",
|
| 226 |
-
" ├── video parsing: 1\n",
|
| 227 |
-
" ├── python compiler: 1\n",
|
| 228 |
-
" ├── video recognition tools: 3\n",
|
| 229 |
-
" ├── pdf viewer: 7\n",
|
| 230 |
-
" ├── microsoft excel / google sheets: 3\n",
|
| 231 |
-
" ├── word document access: 1\n",
|
| 232 |
-
" ├── tool to extract text from images: 1\n",
|
| 233 |
-
" ├── a word reversal tool / script: 1\n",
|
| 234 |
-
" ├── counter: 1\n",
|
| 235 |
-
" ├── excel: 3\n",
|
| 236 |
-
" ├── image recognition: 5\n",
|
| 237 |
-
" ├── color recognition: 3\n",
|
| 238 |
-
" ├── excel file access: 3\n",
|
| 239 |
-
" ├── xml file access: 1\n",
|
| 240 |
-
" ├── access to the internet archive, web.archive.org: 1\n",
|
| 241 |
-
" ├── text processing/diff tool: 1\n",
|
| 242 |
-
" ├── gif parsing tools: 1\n",
|
| 243 |
-
" ├── a web browser: 7\n",
|
| 244 |
-
" ├── a search engine: 7\n",
|
| 245 |
-
" ├── a speech-to-text tool: 2\n",
|
| 246 |
-
" ├── code/data analysis tools: 1\n",
|
| 247 |
-
" ├── audio capability: 2\n",
|
| 248 |
-
" ├── pdf reader: 1\n",
|
| 249 |
-
" ├── markdown: 1\n",
|
| 250 |
-
" ├── a calculator: 5\n",
|
| 251 |
-
" ├── access to wikipedia: 3\n",
|
| 252 |
-
" ├── image recognition/ocr: 3\n",
|
| 253 |
-
" ├── google translate access: 1\n",
|
| 254 |
-
" ├── ocr: 4\n",
|
| 255 |
-
" ├── bass note data: 1\n",
|
| 256 |
-
" ├── text editor: 1\n",
|
| 257 |
-
" ├── xlsx file access: 1\n",
|
| 258 |
-
" ├── powerpoint viewer: 1\n",
|
| 259 |
-
" ├── csv file access: 1\n",
|
| 260 |
-
" ├── calculator (or use excel): 1\n",
|
| 261 |
-
" ├── computer algebra system: 1\n",
|
| 262 |
-
" ├── video processing software: 1\n",
|
| 263 |
-
" ├── audio processing software: 1\n",
|
| 264 |
-
" ├── computer vision: 1\n",
|
| 265 |
-
" ├── google maps: 1\n",
|
| 266 |
-
" ├── access to excel files: 1\n",
|
| 267 |
-
" ├── calculator (or ability to count): 1\n",
|
| 268 |
-
" ├── a file interface: 3\n",
|
| 269 |
-
" ├── a python ide: 1\n",
|
| 270 |
-
" ├── spreadsheet editor: 1\n",
|
| 271 |
-
" ├── tools required: 1\n",
|
| 272 |
-
" ├── b browser: 1\n",
|
| 273 |
-
" ├── image recognition and processing tools: 1\n",
|
| 274 |
-
" ├── computer vision or ocr: 1\n",
|
| 275 |
-
" ├── c++ compiler: 1\n",
|
| 276 |
-
" ├── access to google maps: 1\n",
|
| 277 |
-
" ├── youtube player: 1\n",
|
| 278 |
-
" ├── natural language processor: 1\n",
|
| 279 |
-
" ├── graph interaction tools: 1\n",
|
| 280 |
-
" ├── bablyonian cuniform -> arabic legend: 1\n",
|
| 281 |
-
" ├── access to youtube: 1\n",
|
| 282 |
-
" ├── image search tools: 1\n",
|
| 283 |
-
" ├── calculator or counting function: 1\n",
|
| 284 |
-
" ├── a speech-to-text audio processing tool: 1\n",
|
| 285 |
-
" ├── access to academic journal websites: 1\n",
|
| 286 |
-
" ├── pdf reader/extracter: 1\n",
|
| 287 |
-
" ├── rubik's cube model: 1\n",
|
| 288 |
-
" ├── wikipedia: 1\n",
|
| 289 |
-
" ├── video capability: 1\n",
|
| 290 |
-
" ├── image processing tools: 1\n",
|
| 291 |
-
" ├── age recognition software: 1\n",
|
| 292 |
-
" ├── youtube: 1\n"
|
| 293 |
-
]
|
| 294 |
-
}
|
| 295 |
-
],
|
| 296 |
-
"source": [
|
| 297 |
-
"# list of the tools used in all the samples\n",
|
| 298 |
-
"from collections import Counter, OrderedDict\n",
|
| 299 |
-
"\n",
|
| 300 |
-
"tools = []\n",
|
| 301 |
-
"for sample in json_QA:\n",
|
| 302 |
-
" for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
|
| 303 |
-
" tool = tool[2:].strip().lower()\n",
|
| 304 |
-
" if tool.startswith(\"(\"):\n",
|
| 305 |
-
" tool = tool[11:].strip()\n",
|
| 306 |
-
" tools.append(tool)\n",
|
| 307 |
-
"tools_counter = OrderedDict(Counter(tools))\n",
|
| 308 |
-
"print(\"List of tools used in all samples:\")\n",
|
| 309 |
-
"print(\"Total number of tools used:\", len(tools_counter))\n",
|
| 310 |
-
"for tool, count in tools_counter.items():\n",
|
| 311 |
-
" print(f\" ├── {tool}: {count}\")"
|
| 312 |
-
]
|
| 313 |
-
}
|
| 314 |
-
],
|
| 315 |
-
"metadata": {
|
| 316 |
-
"kernelspec": {
|
| 317 |
-
"display_name": "env",
|
| 318 |
-
"language": "python",
|
| 319 |
-
"name": "python3"
|
| 320 |
-
},
|
| 321 |
-
"language_info": {
|
| 322 |
-
"codemirror_mode": {
|
| 323 |
-
"name": "ipython",
|
| 324 |
-
"version": 3
|
| 325 |
-
},
|
| 326 |
-
"file_extension": ".py",
|
| 327 |
-
"mimetype": "text/x-python",
|
| 328 |
-
"name": "python",
|
| 329 |
-
"nbconvert_exporter": "python",
|
| 330 |
-
"pygments_lexer": "ipython3",
|
| 331 |
-
"version": "3.11.9"
|
| 332 |
-
}
|
| 333 |
-
},
|
| 334 |
-
"nbformat": 4,
|
| 335 |
-
"nbformat_minor": 5
|
| 336 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
-
from PIL import Image
|
| 6 |
-
|
| 7 |
-
# Helper functions for image processing
|
| 8 |
-
def encode_image(image_path: str) -> str:
|
| 9 |
-
"""Convert an image file to base64 string."""
|
| 10 |
-
with open(image_path, "rb") as image_file:
|
| 11 |
-
return base64.b64encode(image_file.read()).decode("utf-8")
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
def decode_image(base64_string: str) -> Image.Image:
|
| 15 |
-
"""Convert a base64 string to a PIL Image."""
|
| 16 |
-
image_data = base64.b64decode(base64_string)
|
| 17 |
-
return Image.open(io.BytesIO(image_data))
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def save_image(image: Image.Image, directory: str = "image_outputs") -> str:
|
| 21 |
-
"""Save a PIL Image to disk and return the path."""
|
| 22 |
-
os.makedirs(directory, exist_ok=True)
|
| 23 |
-
image_id = str(uuid.uuid4())
|
| 24 |
-
image_path = os.path.join(directory, f"{image_id}.png")
|
| 25 |
-
image.save(image_path)
|
| 26 |
-
return image_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
supabase_docs.csv
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
system_prompt.txt
CHANGED
|
@@ -14,4 +14,4 @@ Examples:
|
|
| 14 |
- FINAL ANSWER: Paris
|
| 15 |
- FINAL ANSWER: 128
|
| 16 |
|
| 17 |
-
If you do not follow this format exactly, your response will be considered incorrect.
|
|
|
|
| 14 |
- FINAL ANSWER: Paris
|
| 15 |
- FINAL ANSWER: 128
|
| 16 |
|
| 17 |
+
If you do not follow this format exactly, your response will be considered incorrect.
|
test.ipynb
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"id": "initial_id",
|
| 6 |
+
"metadata": {
|
| 7 |
+
"collapsed": true
|
| 8 |
+
},
|
| 9 |
+
"source": [
|
| 10 |
+
"# Load metadata.jsonl\n",
|
| 11 |
+
"import json\n",
|
| 12 |
+
"# Load the metadata.jsonl file\n",
|
| 13 |
+
"with open('metadata.jsonl', 'r') as jsonl_file:\n",
|
| 14 |
+
" json_list = list(jsonl_file)\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"json_QA = []\n",
|
| 17 |
+
"for json_str in json_list:\n",
|
| 18 |
+
" json_data = json.loads(json_str)\n",
|
| 19 |
+
" json_QA.append(json_data)"
|
| 20 |
+
],
|
| 21 |
+
"outputs": [],
|
| 22 |
+
"execution_count": null
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"metadata": {},
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"source": [
|
| 28 |
+
"# randomly select 3 samples\n",
|
| 29 |
+
"# {\"task_id\": \"c61d22de-5f6c-4958-a7f6-5e9707bd3466\", \"Question\": \"A paper about AI regulation that was originally submitted to arXiv.org in June 2022 shows a figure with three axes, where each axis has a label word at both ends. Which of these words is used to describe a type of society in a Physics and Society article submitted to arXiv.org on August 11, 2016?\", \"Level\": 2, \"Final answer\": \"egalitarian\", \"file_name\": \"\", \"Annotator Metadata\": {\"Steps\": \"1. Go to arxiv.org and navigate to the Advanced Search page.\\n2. Enter \\\"AI regulation\\\" in the search box and select \\\"All fields\\\" from the dropdown.\\n3. Enter 2022-06-01 and 2022-07-01 into the date inputs, select \\\"Submission date (original)\\\", and submit the search.\\n4. Go through the search results to find the article that has a figure with three axes and labels on each end of the axes, titled \\\"Fairness in Agreement With European Values: An Interdisciplinary Perspective on AI Regulation\\\".\\n5. Note the six words used as labels: deontological, egalitarian, localized, standardized, utilitarian, and consequential.\\n6. Go back to arxiv.org\\n7. Find \\\"Physics and Society\\\" and go to the page for the \\\"Physics and Society\\\" category.\\n8. Note that the tag for this category is \\\"physics.soc-ph\\\".\\n9. Go to the Advanced Search page.\\n10. Enter \\\"physics.soc-ph\\\" in the search box and select \\\"All fields\\\" from the dropdown.\\n11. Enter 2016-08-11 and 2016-08-12 into the date inputs, select \\\"Submission date (original)\\\", and submit the search.\\n12. Search for instances of the six words in the results to find the paper titled \\\"Phase transition from egalitarian to hierarchical societies driven by competition between cognitive and social constraints\\\", indicating that \\\"egalitarian\\\" is the correct answer.\", \"Number of steps\": \"12\", \"How long did this take?\": \"8 minutes\", \"Tools\": \"1. Web browser\\n2. Image recognition tools (to identify and parse a figure with three axes)\", \"Number of tools\": \"2\"}}\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"import random\n",
|
| 32 |
+
"# random.seed(42)\n",
|
| 33 |
+
"random_samples = random.sample(json_QA, 1)\n",
|
| 34 |
+
"for sample in random_samples:\n",
|
| 35 |
+
" print(\"=\" * 50)\n",
|
| 36 |
+
" print(f\"Task ID: {sample['task_id']}\")\n",
|
| 37 |
+
" print(f\"Question: {sample['Question']}\")\n",
|
| 38 |
+
" print(f\"Level: {sample['Level']}\")\n",
|
| 39 |
+
" print(f\"Final Answer: {sample['Final answer']}\")\n",
|
| 40 |
+
" print(f\"Annotator Metadata: \")\n",
|
| 41 |
+
" print(f\" ├── Steps: \")\n",
|
| 42 |
+
" for step in sample['Annotator Metadata']['Steps'].split('\\n'):\n",
|
| 43 |
+
" print(f\" │ ├── {step}\")\n",
|
| 44 |
+
" print(f\" ├── Number of steps: {sample['Annotator Metadata']['Number of steps']}\")\n",
|
| 45 |
+
" print(f\" ├── How long did this take?: {sample['Annotator Metadata']['How long did this take?']}\")\n",
|
| 46 |
+
" print(f\" ├── Tools:\")\n",
|
| 47 |
+
" for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
|
| 48 |
+
" print(f\" │ ├── {tool}\")\n",
|
| 49 |
+
" print(f\" └── Number of tools: {sample['Annotator Metadata']['Number of tools']}\")\n",
|
| 50 |
+
"print(\"=\" * 50)"
|
| 51 |
+
],
|
| 52 |
+
"id": "fcf876fdfc43c154",
|
| 53 |
+
"outputs": [],
|
| 54 |
+
"execution_count": null
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"source": [
|
| 60 |
+
"### build a vector database based on the metadata.jsonl\n",
|
| 61 |
+
"# https://python.langchain.com/docs/integrations/vectorstores/supabase/\n",
|
| 62 |
+
"import os\n",
|
| 63 |
+
"from dotenv import load_dotenv\n",
|
| 64 |
+
"from langchain_huggingface import HuggingFaceEmbeddings\n",
|
| 65 |
+
"from langchain_community.vectorstores import SupabaseVectorStore\n",
|
| 66 |
+
"from supabase.client import Client, create_client\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"load_dotenv()\n",
|
| 70 |
+
"embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") # dim=768\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
|
| 73 |
+
"supabase_key = os.environ.get(\"SUPABASE_SERVICE_KEY\")\n",
|
| 74 |
+
"supabase: Client = create_client(supabase_url, supabase_key)"
|
| 75 |
+
],
|
| 76 |
+
"id": "9be49655bf7b1506",
|
| 77 |
+
"outputs": [],
|
| 78 |
+
"execution_count": null
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"source": [
|
| 84 |
+
"# wrap the metadata.jsonl's questions and answers into a list of document\n",
|
| 85 |
+
"from langchain.schema import Document\n",
|
| 86 |
+
"docs = []\n",
|
| 87 |
+
"for sample in json_QA:\n",
|
| 88 |
+
" content = f\"Question : {sample['Question']}\\n\\nFinal answer : {sample['Final answer']}\"\n",
|
| 89 |
+
" doc = {\n",
|
| 90 |
+
" \"content\" : content,\n",
|
| 91 |
+
" \"metadata\" : { # meatadata的格式必须时source键,否则会报错\n",
|
| 92 |
+
" \"source\" : sample['task_id']\n",
|
| 93 |
+
" },\n",
|
| 94 |
+
" \"embedding\" : embeddings.embed_query(content),\n",
|
| 95 |
+
" }\n",
|
| 96 |
+
" docs.append(doc)\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"# upload the documents to the vector database\n",
|
| 99 |
+
"try:\n",
|
| 100 |
+
" response = (\n",
|
| 101 |
+
" supabase.table(\"documents\")\n",
|
| 102 |
+
" .insert(docs)\n",
|
| 103 |
+
" .execute()\n",
|
| 104 |
+
" )\n",
|
| 105 |
+
"except Exception as exception:\n",
|
| 106 |
+
" print(\"Error inserting data into Supabase:\", exception)\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"# ALTERNATIVE : Save the documents (a list of dict) into a csv file, and manually upload it to Supabase\n",
|
| 109 |
+
"# import pandas as pd\n",
|
| 110 |
+
"# df = pd.DataFrame(docs)\n",
|
| 111 |
+
"# df.to_csv('supabase_docs.csv', index=False)"
|
| 112 |
+
],
|
| 113 |
+
"id": "3a8f1a5fef11a6a0",
|
| 114 |
+
"outputs": [],
|
| 115 |
+
"execution_count": null
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"source": [
|
| 121 |
+
"# add items to vector database\n",
|
| 122 |
+
"vector_store = SupabaseVectorStore(\n",
|
| 123 |
+
" client=supabase,\n",
|
| 124 |
+
" embedding= embeddings,\n",
|
| 125 |
+
" table_name=\"documents\",\n",
|
| 126 |
+
" query_name=\"match_documents_langchain\",\n",
|
| 127 |
+
")\n",
|
| 128 |
+
"retriever = vector_store.as_retriever()"
|
| 129 |
+
],
|
| 130 |
+
"id": "b1b720c17d34d0dc",
|
| 131 |
+
"outputs": [],
|
| 132 |
+
"execution_count": null
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"source": [
|
| 138 |
+
"query = \"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?\"\n",
|
| 139 |
+
"# matched_docs = vector_store.similarity_search(query, 2)\n",
|
| 140 |
+
"docs = retriever.invoke(query)\n",
|
| 141 |
+
"docs[0]"
|
| 142 |
+
],
|
| 143 |
+
"id": "49b8420a90e4dd76",
|
| 144 |
+
"outputs": [],
|
| 145 |
+
"execution_count": null
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"source": [
|
| 151 |
+
"# list of the tools used in all the samples\n",
|
| 152 |
+
"from collections import Counter, OrderedDict\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"tools = []\n",
|
| 155 |
+
"for sample in json_QA:\n",
|
| 156 |
+
" for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
|
| 157 |
+
" tool = tool[2:].strip().lower()\n",
|
| 158 |
+
" if tool.startswith(\"(\"):\n",
|
| 159 |
+
" tool = tool[11:].strip()\n",
|
| 160 |
+
" tools.append(tool)\n",
|
| 161 |
+
"tools_counter = OrderedDict(Counter(tools))\n",
|
| 162 |
+
"print(\"List of tools used in all samples:\")\n",
|
| 163 |
+
"print(\"Total number of tools used:\", len(tools_counter))\n",
|
| 164 |
+
"for tool, count in tools_counter.items():\n",
|
| 165 |
+
" print(f\" ├── {tool}: {count}\")"
|
| 166 |
+
],
|
| 167 |
+
"id": "6280689c6bf3255e",
|
| 168 |
+
"outputs": [],
|
| 169 |
+
"execution_count": null
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"metadata": {},
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"source": [
|
| 175 |
+
"system_prompt = \"\"\"\n",
|
| 176 |
+
"You are a helpful assistant tasked with answering questions using a set of tools.\n",
|
| 177 |
+
"If the tool is not available, you can try to find the information online. You can also use your own knowledge to answer the question.\n",
|
| 178 |
+
"You need to provide a step-by-step explanation of how you arrived at the answer.\n",
|
| 179 |
+
"==========================\n",
|
| 180 |
+
"Here is a few examples showing you how to answer the question step by step.\n",
|
| 181 |
+
"\"\"\"\n",
|
| 182 |
+
"for i, samples in enumerate(random_samples):\n",
|
| 183 |
+
" system_prompt += f\"\\nQuestion {i+1}: {samples['Question']}\\nSteps:\\n{samples['Annotator Metadata']['Steps']}\\nTools:\\n{samples['Annotator Metadata']['Tools']}\\nFinal Answer: {samples['Final answer']}\\n\"\n",
|
| 184 |
+
"system_prompt += \"\\n==========================\\n\"\n",
|
| 185 |
+
"system_prompt += \"Now, please answer the following question step by step.\\n\"\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"# save the system_prompt to a file\n",
|
| 188 |
+
"with open('system_prompt.txt', 'w') as f:\n",
|
| 189 |
+
" f.write(system_prompt)"
|
| 190 |
+
],
|
| 191 |
+
"id": "d850bbc4a908a98b",
|
| 192 |
+
"outputs": [],
|
| 193 |
+
"execution_count": null
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"cell_type": "code",
|
| 198 |
+
"source": [
|
| 199 |
+
"# load the system prompt from the file\n",
|
| 200 |
+
"with open('system_prompt.txt', 'r') as f:\n",
|
| 201 |
+
" system_prompt = f.read()\n",
|
| 202 |
+
"print(system_prompt)"
|
| 203 |
+
],
|
| 204 |
+
"id": "85fce16b57c00eaa",
|
| 205 |
+
"outputs": [],
|
| 206 |
+
"execution_count": null
|
| 207 |
+
},
|
| 208 |
+
{
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"source": [
|
| 212 |
+
"import os\n",
|
| 213 |
+
"from dotenv import load_dotenv\n",
|
| 214 |
+
"from langgraph.graph import MessagesState, START, StateGraph\n",
|
| 215 |
+
"from langgraph.prebuilt import tools_condition\n",
|
| 216 |
+
"from langgraph.prebuilt import ToolNode\n",
|
| 217 |
+
"from langchain_google_genai import ChatGoogleGenerativeAI\n",
|
| 218 |
+
"from langchain_groq import ChatGroq\n",
|
| 219 |
+
"from langchain_huggingface import HuggingFaceEmbeddings\n",
|
| 220 |
+
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
| 221 |
+
"from langchain_community.document_loaders import WikipediaLoader\n",
|
| 222 |
+
"from langchain_community.document_loaders import ArxivLoader\n",
|
| 223 |
+
"from langchain_community.vectorstores import SupabaseVectorStore\n",
|
| 224 |
+
"from langchain.tools.retriever import create_retriever_tool\n",
|
| 225 |
+
"from langchain_core.messages import HumanMessage, SystemMessage\n",
|
| 226 |
+
"from langchain_core.tools import tool\n",
|
| 227 |
+
"from supabase.client import Client, create_client\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"# Define the retriever from supabase\n",
|
| 230 |
+
"load_dotenv()\n",
|
| 231 |
+
"embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") # dim=768\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
|
| 234 |
+
"supabase_key = os.environ.get(\"SUPABASE_SERVICE_KEY\")\n",
|
| 235 |
+
"supabase: Client = create_client(supabase_url, supabase_key)\n",
|
| 236 |
+
"vector_store = SupabaseVectorStore(\n",
|
| 237 |
+
" client=supabase,\n",
|
| 238 |
+
" embedding= embeddings,\n",
|
| 239 |
+
" table_name=\"documents\",\n",
|
| 240 |
+
" query_name=\"match_documents_langchain\",\n",
|
| 241 |
+
")\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"question_retrieve_tool = create_retriever_tool(\n",
|
| 244 |
+
" vector_store.as_retriever(),\n",
|
| 245 |
+
" \"Question Retriever\",\n",
|
| 246 |
+
" \"Find similar questions in the vector database for the given question.\",\n",
|
| 247 |
+
")\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"@tool\n",
|
| 250 |
+
"def multiply(a: int, b: int) -> int:\n",
|
| 251 |
+
" \"\"\"Multiply two numbers.\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" Args:\n",
|
| 254 |
+
" a: first int\n",
|
| 255 |
+
" b: second int\n",
|
| 256 |
+
" \"\"\"\n",
|
| 257 |
+
" return a * b\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"@tool\n",
|
| 260 |
+
"def add(a: int, b: int) -> int:\n",
|
| 261 |
+
" \"\"\"Add two numbers.\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" Args:\n",
|
| 264 |
+
" a: first int\n",
|
| 265 |
+
" b: second int\n",
|
| 266 |
+
" \"\"\"\n",
|
| 267 |
+
" return a + b\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"@tool\n",
|
| 270 |
+
"def subtract(a: int, b: int) -> int:\n",
|
| 271 |
+
" \"\"\"Subtract two numbers.\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" Args:\n",
|
| 274 |
+
" a: first int\n",
|
| 275 |
+
" b: second int\n",
|
| 276 |
+
" \"\"\"\n",
|
| 277 |
+
" return a - b\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"@tool\n",
|
| 280 |
+
"def divide(a: int, b: int) -> int:\n",
|
| 281 |
+
" \"\"\"Divide two numbers.\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" Args:\n",
|
| 284 |
+
" a: first int\n",
|
| 285 |
+
" b: second int\n",
|
| 286 |
+
" \"\"\"\n",
|
| 287 |
+
" if b == 0:\n",
|
| 288 |
+
" raise ValueError(\"Cannot divide by zero.\")\n",
|
| 289 |
+
" return a / b\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"@tool\n",
|
| 292 |
+
"def modulus(a: int, b: int) -> int:\n",
|
| 293 |
+
" \"\"\"Get the modulus of two numbers.\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" Args:\n",
|
| 296 |
+
" a: first int\n",
|
| 297 |
+
" b: second int\n",
|
| 298 |
+
" \"\"\"\n",
|
| 299 |
+
" return a % b\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"@tool\n",
|
| 302 |
+
"def wiki_search(query: str) -> str:\n",
|
| 303 |
+
" \"\"\"Search Wikipedia for a query and return maximum 2 results.\n",
|
| 304 |
+
"\n",
|
| 305 |
+
" Args:\n",
|
| 306 |
+
" query: The search query.\"\"\"\n",
|
| 307 |
+
" search_docs = WikipediaLoader(query=query, load_max_docs=2).load()\n",
|
| 308 |
+
" formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
|
| 309 |
+
" [\n",
|
| 310 |
+
" f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content}\\n</Document>'\n",
|
| 311 |
+
" for doc in search_docs\n",
|
| 312 |
+
" ])\n",
|
| 313 |
+
" return {\"wiki_results\": formatted_search_docs}\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"@tool\n",
|
| 316 |
+
"def web_search(query: str) -> str:\n",
|
| 317 |
+
" \"\"\"Search Tavily for a query and return maximum 3 results.\n",
|
| 318 |
+
"\n",
|
| 319 |
+
" Args:\n",
|
| 320 |
+
" query: The search query.\"\"\"\n",
|
| 321 |
+
" search_docs = TavilySearchResults(max_results=3).invoke(query=query)\n",
|
| 322 |
+
" formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
|
| 323 |
+
" [\n",
|
| 324 |
+
" f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content}\\n</Document>'\n",
|
| 325 |
+
" for doc in search_docs\n",
|
| 326 |
+
" ])\n",
|
| 327 |
+
" return {\"web_results\": formatted_search_docs}\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"@tool\n",
|
| 330 |
+
"def arvix_search(query: str) -> str:\n",
|
| 331 |
+
" \"\"\"Search Arxiv for a query and return maximum 3 result.\n",
|
| 332 |
+
"\n",
|
| 333 |
+
" Args:\n",
|
| 334 |
+
" query: The search query.\"\"\"\n",
|
| 335 |
+
" search_docs = ArxivLoader(query=query, load_max_docs=3).load()\n",
|
| 336 |
+
" formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
|
| 337 |
+
" [\n",
|
| 338 |
+
" f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content[:1000]}\\n</Document>'\n",
|
| 339 |
+
" for doc in search_docs\n",
|
| 340 |
+
" ])\n",
|
| 341 |
+
" return {\"arvix_results\": formatted_search_docs}\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"@tool\n",
|
| 344 |
+
"def similar_question_search(question: str) -> str:\n",
|
| 345 |
+
" \"\"\"Search the vector database for similar questions and return the first results.\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" Args:\n",
|
| 348 |
+
" question: the question human provided.\"\"\"\n",
|
| 349 |
+
" matched_docs = vector_store.similarity_search(query, 3)\n",
|
| 350 |
+
" formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
|
| 351 |
+
" [\n",
|
| 352 |
+
" f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content[:1000]}\\n</Document>'\n",
|
| 353 |
+
" for doc in matched_docs\n",
|
| 354 |
+
" ])\n",
|
| 355 |
+
" return {\"similar_questions\": formatted_search_docs}\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"tools = [\n",
|
| 358 |
+
" multiply,\n",
|
| 359 |
+
" add,\n",
|
| 360 |
+
" subtract,\n",
|
| 361 |
+
" divide,\n",
|
| 362 |
+
" modulus,\n",
|
| 363 |
+
" wiki_search,\n",
|
| 364 |
+
" web_search,\n",
|
| 365 |
+
" arvix_search,\n",
|
| 366 |
+
" question_retrieve_tool\n",
|
| 367 |
+
"]\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"llm = ChatGoogleGenerativeAI(model=\"gemini-2.0-flash\")\n",
|
| 370 |
+
"# llm = ChatGroq(model=\"qwen-qwq-32b\", temperature=0)\n",
|
| 371 |
+
"llm_with_tools = llm.bind_tools(tools)"
|
| 372 |
+
],
|
| 373 |
+
"id": "2d049ca6773dd05e",
|
| 374 |
+
"outputs": [],
|
| 375 |
+
"execution_count": null
|
| 376 |
+
},
|
| 377 |
+
{
|
| 378 |
+
"metadata": {},
|
| 379 |
+
"cell_type": "code",
|
| 380 |
+
"source": [
|
| 381 |
+
"# load the system prompt from the file\n",
|
| 382 |
+
"with open('system_prompt.txt', 'r') as f:\n",
|
| 383 |
+
" system_prompt = f.read()\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"\n",
|
| 386 |
+
"# System message\n",
|
| 387 |
+
"sys_msg = SystemMessage(content=system_prompt)\n",
|
| 388 |
+
"\n",
|
| 389 |
+
"# Node\n",
|
| 390 |
+
"def assistant(state: MessagesState):\n",
|
| 391 |
+
" \"\"\"Assistant node\"\"\"\n",
|
| 392 |
+
" return {\"messages\": [llm_with_tools.invoke([sys_msg] + state[\"messages\"])]}\n",
|
| 393 |
+
"\n",
|
| 394 |
+
"# Build graph\n",
|
| 395 |
+
"builder = StateGraph(MessagesState)\n",
|
| 396 |
+
"builder.add_node(\"assistant\", assistant)\n",
|
| 397 |
+
"builder.add_node(\"tools\", ToolNode(tools))\n",
|
| 398 |
+
"builder.add_edge(START, \"assistant\")\n",
|
| 399 |
+
"builder.add_conditional_edges(\n",
|
| 400 |
+
" \"assistant\",\n",
|
| 401 |
+
" # If the latest message (result) from assistant is a tool call -> tools_condition routes to tools\n",
|
| 402 |
+
" # If the latest message (result) from assistant is a not a tool call -> tools_condition routes to END\n",
|
| 403 |
+
" tools_condition,\n",
|
| 404 |
+
")\n",
|
| 405 |
+
"builder.add_edge(\"tools\", \"assistant\")\n",
|
| 406 |
+
"\n",
|
| 407 |
+
"# Compile graph\n",
|
| 408 |
+
"graph = builder.compile()\n",
|
| 409 |
+
"\n",
|
| 410 |
+
"from IPython.display import Image, display\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"display(Image(graph.get_graph(xray=True).draw_mermaid_png()))"
|
| 413 |
+
],
|
| 414 |
+
"id": "f1d17cb6cac71a7a",
|
| 415 |
+
"outputs": [],
|
| 416 |
+
"execution_count": null
|
| 417 |
+
},
|
| 418 |
+
{
|
| 419 |
+
"metadata": {
|
| 420 |
+
"jupyter": {
|
| 421 |
+
"is_executing": true
|
| 422 |
+
}
|
| 423 |
+
},
|
| 424 |
+
"cell_type": "code",
|
| 425 |
+
"source": [
|
| 426 |
+
"question = \"What are the EC numbers of the two most commonly used chemicals for the virus testing method in the paper about SPFMV and SPCSV in the Pearl Of Africa from 2016? Return the semicolon-separated numbers in the order of the alphabetized chemicals.\"\n",
|
| 427 |
+
"messages = [HumanMessage(content=question)]\n",
|
| 428 |
+
"messages = graph.invoke({\"messages\": messages})\n",
|
| 429 |
+
"\n",
|
| 430 |
+
"for m in messages['messages']:\n",
|
| 431 |
+
" m.pretty_print()"
|
| 432 |
+
],
|
| 433 |
+
"id": "a1a5be38e7e98476",
|
| 434 |
+
"outputs": [],
|
| 435 |
+
"execution_count": null
|
| 436 |
+
}
|
| 437 |
+
],
|
| 438 |
+
"metadata": {
|
| 439 |
+
"kernelspec": {
|
| 440 |
+
"display_name": "Python 3",
|
| 441 |
+
"language": "python",
|
| 442 |
+
"name": "python3"
|
| 443 |
+
},
|
| 444 |
+
"language_info": {
|
| 445 |
+
"codemirror_mode": {
|
| 446 |
+
"name": "ipython",
|
| 447 |
+
"version": 2
|
| 448 |
+
},
|
| 449 |
+
"file_extension": ".py",
|
| 450 |
+
"mimetype": "text/x-python",
|
| 451 |
+
"name": "python",
|
| 452 |
+
"nbconvert_exporter": "python",
|
| 453 |
+
"pygments_lexer": "ipython2",
|
| 454 |
+
"version": "2.7.6"
|
| 455 |
+
}
|
| 456 |
+
},
|
| 457 |
+
"nbformat": 4,
|
| 458 |
+
"nbformat_minor": 5
|
| 459 |
+
}
|