sunnyday910 commited on
Commit
2ab9c09
·
verified ·
1 Parent(s): 4160cb5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -5
app.py CHANGED
@@ -3,21 +3,133 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
 
 
 
 
 
 
 
6
 
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
 
 
 
 
 
 
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
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
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -40,7 +152,7 @@ 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
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from langchain_google_genai import ChatGoogleGenerativeAI
7
+ from langgraph.graph import StateGraph, MessagesState, START
8
+ from langchain_core.messages import SystemMessage, HumanMessage
9
+ from langchain_community.document_loaders import WikipediaLoader
10
+ from langchain_community.tools import TavilySearchResults, DuckDuckGoSearchRun
11
+ from dotenv import load_dotenv
12
+ import operator
13
+ from typing import Annotated
14
+ from typing_extensions import TypedDict
15
 
16
+ load_dotenv()
17
  # (Keep Constants as is)
18
  # --- Constants ---
19
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
20
 
21
+ SYSTEM_MESSAGE = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:[YOUR FINAL ANSWER].
22
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
23
+ If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
24
+ If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
25
+ If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
26
+ """
27
+
28
  # --- Basic Agent Definition ---
29
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
30
  class BasicAgent:
31
+ def __init__(self, graph):
32
+ self.graph = graph
33
  print("BasicAgent initialized.")
34
  def __call__(self, question: str) -> str:
35
  print(f"Agent received question (first 50 chars): {question[:50]}...")
36
+ input_state = {"question": question}
37
+ # Run the graph
38
+ answer = self.graph.invoke(input_state)
39
+ print(f"Agent returning fixed answer: {answer}")
40
+ return answer
41
+
42
+ class State(TypedDict):
43
+ question: str
44
+ answer: str
45
+ context: Annotated[list, operator.add]
46
+
47
+ def search_tavily(state):
48
+
49
+ """ Retrieve docs from web search """
50
+
51
+ # Search
52
+ tavily_search = TavilySearchResults(max_results=2)
53
+ search_docs = tavily_search.invoke(state['question'])
54
+
55
+ # Format
56
+ formatted_search_docs = "\n\n---\n\n".join(
57
+ [
58
+ f'<Document href="{doc["url"]}"/>\n{doc["content"]}\n</Document>'
59
+ for doc in search_docs
60
+ ]
61
+ )
62
+
63
+ return {"context": [formatted_search_docs]}
64
+
65
+ def search_wikipedia(state):
66
+
67
+ """ Retrieve docs from wikipedia """
68
+
69
+ # Search
70
+ search_docs = WikipediaLoader(query=state['question'],
71
+ load_max_docs=2).load()
72
+
73
+ # Format
74
+ formatted_search_docs = "\n\n---\n\n".join(
75
+ [
76
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
77
+ for doc in search_docs
78
+ ]
79
+ )
80
+
81
+ return {"context": [formatted_search_docs]}
82
+
83
+ def search_DuckDuckGo(state):
84
+
85
+ """ Retrive answer from DuckDuckGoSearch."""
86
+
87
+ ddg_search = DuckDuckGoSearchRun(max_results=2)
88
+ search_docs = ddg_search.invoke(state['question'])
89
+
90
+ # Format
91
+ formatted_search_docs = "\n\n---\n\n".join(
92
+ [
93
+ f'<Document href="{doc["url"]}"/>\n{doc["content"]}\n</Document>'
94
+ for doc in search_docs
95
+ ]
96
+ )
97
+
98
+ return {"context": [formatted_search_docs]}
99
+
100
+ def generate_answer(state):
101
+
102
+ """Node to give answer to the question"""
103
+
104
+ context = state["context"]
105
+ question = state["question"]
106
+
107
+ additional_context_template = """Here are some contexts about the question you can use if you find it helpful: {context}"""
108
+ additional_context = additional_context_template.format(context=context)
109
+ final_instruction = SYSTEM_MESSAGE + additional_context
110
+
111
+ #answer
112
+ answer = llm.invoke([SystemMessage(content=final_instruction)] + [HumanMessage(content=f"Answer the question: {question}")])
113
+
114
+ # Append it to state
115
+ return {"answer": answer}
116
+
117
+
118
+ builder = StateGraph(State)
119
+
120
+ builder.add_node("search_tavily",search_tavily)
121
+ builder.add_node("search_wikipedia", search_wikipedia)
122
+ builder.add_node("search_DuckDuckGo", search_DuckDuckGo)
123
+ builder.add_node("generate_answer", generate_answer)
124
+
125
+ builder.add_edge(START, "search_wikipedia")
126
+ builder.add_edge(START, "search_tavily")
127
+ builder.add_edge(START, "search_DuckDuckGo")
128
+ builder.add_edge("search_wikipedia", "generate_answer")
129
+ builder.add_edge("search_tavily", "generate_answer")
130
+ builder.add_edge("search_DuckDuckGo", "generate_answer")
131
+ graph = builder.compile()
132
+
133
 
134
  def run_and_submit_all( profile: gr.OAuthProfile | None):
135
  """
 
152
 
153
  # 1. Instantiate Agent ( modify this part to create your agent)
154
  try:
155
+ agent = BasicAgent(graph)
156
  except Exception as e:
157
  print(f"Error instantiating agent: {e}")
158
  return f"Error initializing agent: {e}", None