Spaces:
Sleeping
Sleeping
Implemented inital agent code
Browse files- .gitignore +2 -0
- agent.py +109 -0
- agent_graph.png +0 -0
- app.py +6 -3
- requirements.txt +5 -1
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
.env
|
2 |
+
.env.*
|
agent.py
CHANGED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import TypedDict, Annotated
|
3 |
+
from langgraph.graph.message import add_messages
|
4 |
+
from langchain_core.messages import AnyMessage, HumanMessage, AIMessage, SystemMessage
|
5 |
+
from langgraph.prebuilt import ToolNode
|
6 |
+
from langchain.tools import Tool
|
7 |
+
from langgraph.graph import START, StateGraph
|
8 |
+
from langgraph.prebuilt import tools_condition
|
9 |
+
from langchain_openai import ChatOpenAI
|
10 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
11 |
+
|
12 |
+
def calculator(operation: str, num1: int, num2: int):
|
13 |
+
if operation == "add":
|
14 |
+
return num1 + num2
|
15 |
+
elif operation == "subtract":
|
16 |
+
return num1 - num2
|
17 |
+
elif operation == "multiply":
|
18 |
+
return num1 * num2
|
19 |
+
elif operation == "divide":
|
20 |
+
return num1 / num2
|
21 |
+
return input
|
22 |
+
|
23 |
+
calculator_tool = Tool(
|
24 |
+
name="calculator",
|
25 |
+
func=calculator,
|
26 |
+
description="Use this tool to perform basic arithmetic operations (add, subtract, multiply, divide) on two numbers"
|
27 |
+
)
|
28 |
+
|
29 |
+
# Initialize the web search tool
|
30 |
+
search_tool = DuckDuckGoSearchRun()
|
31 |
+
|
32 |
+
# System prompt to guide the model's behavior
|
33 |
+
SYSTEM_PROMPT = """You are a genuis AI assistant called TurboNerd.
|
34 |
+
Always provide accurate and helpful responses based on the information you find. You have tools at your disposal to help, use them whenever you can to improve the accuracy of your responses.
|
35 |
+
When you recieve an input from the user, first you will break the input into smaller parts. Then you will one by one use the tools to answer the question. The final should be as short as possible, directly answering the question.
|
36 |
+
"""
|
37 |
+
|
38 |
+
# Generate the chat interface, including the tools
|
39 |
+
llm = ChatOpenAI(
|
40 |
+
model="gpt-4",
|
41 |
+
temperature=0
|
42 |
+
)
|
43 |
+
|
44 |
+
chat = llm
|
45 |
+
tools = [search_tool, calculator_tool]
|
46 |
+
chat_with_tools = chat.bind_tools(tools)
|
47 |
+
|
48 |
+
# Generate the AgentState and Agent graph
|
49 |
+
class AgentState(TypedDict):
|
50 |
+
messages: Annotated[list[AnyMessage], add_messages]
|
51 |
+
|
52 |
+
def assistant(state: AgentState):
|
53 |
+
# Add system message if it's the first message
|
54 |
+
print("Assistant called... \n")
|
55 |
+
if len(state["messages"]) == 1 and isinstance(state["messages"][0], HumanMessage):
|
56 |
+
messages = [SystemMessage(content=SYSTEM_PROMPT)] + state["messages"]
|
57 |
+
else:
|
58 |
+
messages = state["messages"]
|
59 |
+
|
60 |
+
return {
|
61 |
+
"messages": [chat_with_tools.invoke(messages)],
|
62 |
+
}
|
63 |
+
|
64 |
+
# Create the graph
|
65 |
+
def create_agent_graph() -> StateGraph:
|
66 |
+
"""Create the complete agent graph."""
|
67 |
+
builder = StateGraph(AgentState)
|
68 |
+
|
69 |
+
# Define nodes: these do the work
|
70 |
+
builder.add_node("assistant", assistant)
|
71 |
+
builder.add_node("tools", ToolNode(tools))
|
72 |
+
|
73 |
+
# Define edges: these determine how the control flow moves
|
74 |
+
builder.add_edge(START, "assistant")
|
75 |
+
builder.add_conditional_edges(
|
76 |
+
"assistant",
|
77 |
+
# If the latest message requires a tool, route to tools
|
78 |
+
# Otherwise, provide a direct response
|
79 |
+
tools_condition,
|
80 |
+
)
|
81 |
+
builder.add_edge("tools", "assistant")
|
82 |
+
|
83 |
+
return builder.compile()
|
84 |
+
|
85 |
+
# Main agent class that integrates with your existing app.py
|
86 |
+
class TurboNerd:
|
87 |
+
def __init__(self):
|
88 |
+
self.graph = create_agent_graph()
|
89 |
+
self.tools = tools
|
90 |
+
|
91 |
+
def __call__(self, question: str) -> str:
|
92 |
+
"""Process a question and return an answer."""
|
93 |
+
# Initialize the state with the question
|
94 |
+
initial_state = {
|
95 |
+
"messages": [HumanMessage(content=question)],
|
96 |
+
}
|
97 |
+
|
98 |
+
# Run the graph
|
99 |
+
result = self.graph.invoke(initial_state)
|
100 |
+
|
101 |
+
# Extract the final message
|
102 |
+
final_message = result["messages"][-1]
|
103 |
+
return final_message.content
|
104 |
+
|
105 |
+
# Example usage:
|
106 |
+
if __name__ == "__main__":
|
107 |
+
agent = TurboNerd()
|
108 |
+
response = agent("What is the time in Tokyo now?")
|
109 |
+
print(response)
|
agent_graph.png
ADDED
![]() |
app.py
CHANGED
@@ -3,6 +3,7 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
|
|
6 |
|
7 |
# (Keep Constants as is)
|
8 |
# --- Constants ---
|
@@ -13,11 +14,13 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
13 |
class BasicAgent:
|
14 |
def __init__(self):
|
15 |
print("BasicAgent initialized.")
|
|
|
|
|
16 |
def __call__(self, question: str) -> str:
|
17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
18 |
-
|
19 |
-
print(f"Agent returning
|
20 |
-
return
|
21 |
|
22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
23 |
"""
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
from agent import TurboNerd
|
7 |
|
8 |
# (Keep Constants as is)
|
9 |
# --- Constants ---
|
|
|
14 |
class BasicAgent:
|
15 |
def __init__(self):
|
16 |
print("BasicAgent initialized.")
|
17 |
+
self.agent = TurboNerd()
|
18 |
+
|
19 |
def __call__(self, question: str) -> str:
|
20 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
21 |
+
answer = self.agent(question)
|
22 |
+
print(f"Agent returning answer: {answer[:50]}...")
|
23 |
+
return answer
|
24 |
|
25 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
26 |
"""
|
requirements.txt
CHANGED
@@ -1,2 +1,6 @@
|
|
1 |
gradio
|
2 |
-
requests
|
|
|
|
|
|
|
|
|
|
1 |
gradio
|
2 |
+
requests
|
3 |
+
langgraph
|
4 |
+
langchain
|
5 |
+
langchain-openai
|
6 |
+
duckduckgo-search
|