Commit ·
9df9926
1
Parent(s): 991b74a
fixed agent
Browse files
agent.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
from textwrap import dedent
|
| 2 |
from typing import TypedDict, List, Dict, Any, Optional, Annotated
|
|
|
|
| 3 |
import os
|
|
|
|
| 4 |
|
| 5 |
# from langchain_openai import ChatOpenAI
|
| 6 |
# from langchain_huggingface.llms import HuggingFaceEndpoint
|
|
@@ -13,8 +15,6 @@ from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
|
|
| 13 |
from langfuse.langchain import CallbackHandler
|
| 14 |
from langfuse import get_client
|
| 15 |
|
| 16 |
-
from tools import fetch_website, get_wiki_full, youtube_transcript, python_repl_tool, duckduckgo_search_results
|
| 17 |
-
|
| 18 |
os.environ["LANGFUSE_PUBLIC_KEY"] = os.getenv("LANGFUSE_PUBLIC_KEY", "pk-lf-***") # Public key is safe to expose in client-side code
|
| 19 |
os.environ["LANGFUSE_SECRET_KEY"] = os.getenv("LANGFUSE_SECRET_KEY", "sk-lf-***")
|
| 20 |
os.environ["LANGFUSE_BASE_URL"] = os.getenv("LANGFUSE_BASE_URL", "https://us.cloud.langfuse.com") # 🇺🇸 US region
|
|
@@ -27,32 +27,32 @@ else:
|
|
| 27 |
print("Authentication failed. Please check your credentials and host.")
|
| 28 |
langfuse_handler = CallbackHandler()
|
| 29 |
|
| 30 |
-
# Initialize the Hugging Face model
|
| 31 |
-
hf_model_name = "openai/gpt-oss-120b" # "Qwen/Qwen2.5-72B-Instruct"
|
| 32 |
-
hf_model_provider = "nscale" # "hf-inference"
|
| 33 |
-
|
| 34 |
-
llm = HuggingFaceEndpoint(
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
)
|
| 41 |
-
|
| 42 |
-
chat_model = ChatHuggingFace(llm=llm)
|
| 43 |
-
|
| 44 |
-
# Equip llm with tools
|
| 45 |
-
tools_list = [
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
]
|
| 52 |
-
|
| 53 |
-
llm_with_tools = chat_model.bind_tools(
|
| 54 |
-
|
| 55 |
-
)
|
| 56 |
|
| 57 |
# Define Agent Workflow
|
| 58 |
|
|
@@ -60,7 +60,7 @@ class AgentState(TypedDict):
|
|
| 60 |
messages: Annotated[list[AnyMessage], add_messages]
|
| 61 |
|
| 62 |
|
| 63 |
-
def assistant(state: AgentState):
|
| 64 |
# System message
|
| 65 |
textual_description_of_tool = dedent(
|
| 66 |
"""
|
|
@@ -111,27 +111,27 @@ def assistant(state: AgentState):
|
|
| 111 |
)
|
| 112 |
|
| 113 |
return {
|
| 114 |
-
"messages": [
|
| 115 |
}
|
| 116 |
|
| 117 |
-
# Build the StateGraph for the agent
|
| 118 |
-
# The graph
|
| 119 |
-
builder = StateGraph(AgentState)
|
| 120 |
-
|
| 121 |
-
# Define nodes: these do the work
|
| 122 |
-
builder.add_node("assistant", assistant)
|
| 123 |
-
builder.add_node("tools", ToolNode(tools_list))
|
| 124 |
-
|
| 125 |
-
# Define edges: these determine how the control flow moves
|
| 126 |
-
builder.add_edge(START, "assistant")
|
| 127 |
-
builder.add_conditional_edges(
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
)
|
| 133 |
-
builder.add_edge("tools", "assistant")
|
| 134 |
-
agent_graph = builder.compile()
|
| 135 |
|
| 136 |
def extract_answer(text):
|
| 137 |
match = re.search(r'<answer>(.*?)</answer>', text, re.DOTALL)
|
|
@@ -140,14 +140,60 @@ def extract_answer(text):
|
|
| 140 |
return 'None'
|
| 141 |
|
| 142 |
class BasicAgent:
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
print("BasicAgent initialized.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
async def __call__(self, question: str) -> str:
|
| 146 |
print(f"Agent received question (first 100 chars): {question[:100]}...")
|
| 147 |
# fixed_answer = "This is a default answer."
|
| 148 |
# print(f"Agent returning fixed answer: {fixed_answer}")
|
| 149 |
# Create agent with all the tools
|
| 150 |
-
|
| 151 |
# Example query agent might receive
|
| 152 |
# fixed_answer = await agent.run(question)
|
| 153 |
messages = [
|
|
|
|
| 1 |
from textwrap import dedent
|
| 2 |
from typing import TypedDict, List, Dict, Any, Optional, Annotated
|
| 3 |
+
from functools import partial
|
| 4 |
import os
|
| 5 |
+
import re
|
| 6 |
|
| 7 |
# from langchain_openai import ChatOpenAI
|
| 8 |
# from langchain_huggingface.llms import HuggingFaceEndpoint
|
|
|
|
| 15 |
from langfuse.langchain import CallbackHandler
|
| 16 |
from langfuse import get_client
|
| 17 |
|
|
|
|
|
|
|
| 18 |
os.environ["LANGFUSE_PUBLIC_KEY"] = os.getenv("LANGFUSE_PUBLIC_KEY", "pk-lf-***") # Public key is safe to expose in client-side code
|
| 19 |
os.environ["LANGFUSE_SECRET_KEY"] = os.getenv("LANGFUSE_SECRET_KEY", "sk-lf-***")
|
| 20 |
os.environ["LANGFUSE_BASE_URL"] = os.getenv("LANGFUSE_BASE_URL", "https://us.cloud.langfuse.com") # 🇺🇸 US region
|
|
|
|
| 27 |
print("Authentication failed. Please check your credentials and host.")
|
| 28 |
langfuse_handler = CallbackHandler()
|
| 29 |
|
| 30 |
+
# # Initialize the Hugging Face model
|
| 31 |
+
# hf_model_name = "openai/gpt-oss-120b" # "Qwen/Qwen2.5-72B-Instruct"
|
| 32 |
+
# hf_model_provider = "nscale" # "hf-inference"
|
| 33 |
+
|
| 34 |
+
# llm = HuggingFaceEndpoint(
|
| 35 |
+
# repo_id=hf_model_name,
|
| 36 |
+
# provider=hf_model_provider,
|
| 37 |
+
# max_new_tokens=8192,
|
| 38 |
+
# do_sample=False,
|
| 39 |
+
# # temperature=0.,
|
| 40 |
+
# )
|
| 41 |
+
|
| 42 |
+
# chat_model = ChatHuggingFace(llm=llm)
|
| 43 |
+
|
| 44 |
+
# # Equip llm with tools
|
| 45 |
+
# tools_list = [
|
| 46 |
+
# fetch_website,
|
| 47 |
+
# get_wiki_full,
|
| 48 |
+
# youtube_transcript,
|
| 49 |
+
# python_repl_tool,
|
| 50 |
+
# duckduckgo_search_results
|
| 51 |
+
# ]
|
| 52 |
+
|
| 53 |
+
# llm_with_tools = chat_model.bind_tools(
|
| 54 |
+
# tools_list
|
| 55 |
+
# )
|
| 56 |
|
| 57 |
# Define Agent Workflow
|
| 58 |
|
|
|
|
| 60 |
messages: Annotated[list[AnyMessage], add_messages]
|
| 61 |
|
| 62 |
|
| 63 |
+
def assistant(state: AgentState, llm) -> Dict[str, Any]:
|
| 64 |
# System message
|
| 65 |
textual_description_of_tool = dedent(
|
| 66 |
"""
|
|
|
|
| 111 |
)
|
| 112 |
|
| 113 |
return {
|
| 114 |
+
"messages": [llm.invoke([sys_msg] + state["messages"])],
|
| 115 |
}
|
| 116 |
|
| 117 |
+
# # Build the StateGraph for the agent
|
| 118 |
+
# # The graph
|
| 119 |
+
# builder = StateGraph(AgentState)
|
| 120 |
+
|
| 121 |
+
# # Define nodes: these do the work
|
| 122 |
+
# builder.add_node("assistant", assistant)
|
| 123 |
+
# builder.add_node("tools", ToolNode(tools_list))
|
| 124 |
+
|
| 125 |
+
# # Define edges: these determine how the control flow moves
|
| 126 |
+
# builder.add_edge(START, "assistant")
|
| 127 |
+
# builder.add_conditional_edges(
|
| 128 |
+
# "assistant",
|
| 129 |
+
# # If the latest message requires a tool, route to tools
|
| 130 |
+
# # Otherwise, provide a direct response
|
| 131 |
+
# tools_condition,
|
| 132 |
+
# )
|
| 133 |
+
# builder.add_edge("tools", "assistant")
|
| 134 |
+
# agent_graph = builder.compile()
|
| 135 |
|
| 136 |
def extract_answer(text):
|
| 137 |
match = re.search(r'<answer>(.*?)</answer>', text, re.DOTALL)
|
|
|
|
| 140 |
return 'None'
|
| 141 |
|
| 142 |
class BasicAgent:
|
| 143 |
+
|
| 144 |
+
def __init__(self, hf_model_name, hf_model_provider, tools_list):
|
| 145 |
+
self.hf_model_name = hf_model_name
|
| 146 |
+
self.hf_model_provider = hf_model_provider
|
| 147 |
+
self.tools_list = tools_list
|
| 148 |
print("BasicAgent initialized.")
|
| 149 |
+
|
| 150 |
+
def build_llm_with_tools(self):
|
| 151 |
+
print("Building Hugging Face model and tools...")
|
| 152 |
+
# Initialize the Hugging Face model
|
| 153 |
+
llm = HuggingFaceEndpoint(
|
| 154 |
+
repo_id=self.hf_model_name,
|
| 155 |
+
provider=self.hf_model_provider,
|
| 156 |
+
max_new_tokens=8192,
|
| 157 |
+
do_sample=False,
|
| 158 |
+
temperature=0.4,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
chat_model = ChatHuggingFace(llm=llm)
|
| 162 |
+
|
| 163 |
+
# Equip llm with tools
|
| 164 |
+
|
| 165 |
+
llm_with_tools = chat_model.bind_tools(
|
| 166 |
+
self.tools_list
|
| 167 |
+
)
|
| 168 |
+
print("Agent built successfully.")
|
| 169 |
+
return llm_with_tools
|
| 170 |
+
|
| 171 |
+
def build_agent_graph(self):
|
| 172 |
+
llm_with_tools = self.build_llm_with_tools()
|
| 173 |
+
# Build the StateGraph for the agent
|
| 174 |
+
builder = StateGraph(AgentState)
|
| 175 |
+
|
| 176 |
+
# Define nodes: these do the work
|
| 177 |
+
builder.add_node("assistant", partial(assistant, llm=llm_with_tools))
|
| 178 |
+
builder.add_node("tools", ToolNode(self.tools_list))
|
| 179 |
+
|
| 180 |
+
# Define edges: these determine how the control flow moves
|
| 181 |
+
builder.add_edge(START, "assistant")
|
| 182 |
+
builder.add_conditional_edges(
|
| 183 |
+
"assistant",
|
| 184 |
+
# If the latest message requires a tool, route to tools
|
| 185 |
+
# Otherwise, provide a direct response
|
| 186 |
+
tools_condition,
|
| 187 |
+
)
|
| 188 |
+
builder.add_edge("tools", "assistant")
|
| 189 |
+
return builder.compile()
|
| 190 |
+
|
| 191 |
async def __call__(self, question: str) -> str:
|
| 192 |
print(f"Agent received question (first 100 chars): {question[:100]}...")
|
| 193 |
# fixed_answer = "This is a default answer."
|
| 194 |
# print(f"Agent returning fixed answer: {fixed_answer}")
|
| 195 |
# Create agent with all the tools
|
| 196 |
+
agent_graph = self.build_agent_graph()
|
| 197 |
# Example query agent might receive
|
| 198 |
# fixed_answer = await agent.run(question)
|
| 199 |
messages = [
|
app.py
CHANGED
|
@@ -7,6 +7,8 @@ import inspect
|
|
| 7 |
import pandas as pd
|
| 8 |
import re
|
| 9 |
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# (Keep Constants as is)
|
| 12 |
# --- Constants ---
|
|
@@ -18,6 +20,18 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 18 |
# offloaded to agent.py for better modularity and readability
|
| 19 |
from agent import BasicAgent
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
async def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
|
@@ -40,7 +54,7 @@ async def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 40 |
|
| 41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
| 43 |
-
agent = BasicAgent()
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 7 |
import pandas as pd
|
| 8 |
import re
|
| 9 |
|
| 10 |
+
from tools import fetch_website, get_wiki_full, youtube_transcript, python_repl_tool, duckduckgo_search_results
|
| 11 |
+
|
| 12 |
|
| 13 |
# (Keep Constants as is)
|
| 14 |
# --- Constants ---
|
|
|
|
| 20 |
# offloaded to agent.py for better modularity and readability
|
| 21 |
from agent import BasicAgent
|
| 22 |
|
| 23 |
+
# Initialize the Hugging Face model
|
| 24 |
+
hf_model_name = "openai/gpt-oss-120b" # "Qwen/Qwen2.5-72B-Instruct"
|
| 25 |
+
hf_model_provider = "nscale" # "hf-inference"
|
| 26 |
+
|
| 27 |
+
# Equip llm with tools
|
| 28 |
+
tools_list = [
|
| 29 |
+
fetch_website,
|
| 30 |
+
get_wiki_full,
|
| 31 |
+
youtube_transcript,
|
| 32 |
+
python_repl_tool,
|
| 33 |
+
duckduckgo_search_results
|
| 34 |
+
]
|
| 35 |
|
| 36 |
async def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 37 |
"""
|
|
|
|
| 54 |
|
| 55 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 56 |
try:
|
| 57 |
+
agent = BasicAgent(hf_model_name, hf_model_provider, tools_list)
|
| 58 |
except Exception as e:
|
| 59 |
print(f"Error instantiating agent: {e}")
|
| 60 |
return f"Error initializing agent: {e}", None
|