jensenwiedler commited on
Commit
3945599
·
1 Parent(s): 81917a3

first agent

Browse files
agent/.DS_Store ADDED
Binary file (6.15 kB). View file
 
agent/__init__.py ADDED
File without changes
agent/__pycache__/tools.cpython-312.pyc ADDED
Binary file (2.86 kB). View file
 
agent/graph.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langgraph.graph import StateGraph, MessagesState, START, END
2
+ from langchain_core.messages import HumanMessage, AIMessage
3
+ from langgraph.prebuilt import ToolNode, tools_condition
4
+
5
+ from tools import TOOLS
6
+
7
+ class State(MessagesState):
8
+ file_name: str
9
+
10
+ def retriever(state: State):
11
+ if state.file_name:
12
+ # Simulate file retrieval
13
+ return {"file_content": f"Retrieved content from {state.file_name}"}
14
+
15
+ def call_model(state: State):
16
+ return {"messages": [AIMessage(content="Hello! How can I assist you today?")]}
17
+
18
+
19
+ def build_agent():
20
+ graph_builder = StateGraph(MessagesState)
21
+
22
+ graph_builder.add_node("call_model", call_model)
23
+ graph_builder.add_node("tools", ToolNode(TOOLS))
24
+ graph_builder.add_edge(START, "call_model")
25
+ graph_builder.add_conditional_edges("call_model", tools_condition)
26
+ graph_builder.add_edge("tools", "call_model")
27
+
28
+ return graph_builder.compile()
29
+
30
+ if __name__ == "__main__":
31
+ # Example usage
32
+ agent = build_agent()
33
+ output = agent.invoke({"messages": [HumanMessage(content="Hello, how are you?")]})
34
+ for msg in output["messages"]:
35
+ msg.pretty_print()
agent/tools.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ from langchain_core.tools import tool
3
+ from langchain_community.document_loaders import WikipediaLoader, YoutubeLoader
4
+ from langchain_community.tools import DuckDuckGoSearchResults
5
+ from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
6
+ @tool
7
+ def wikipedia_search(query: str) -> str:
8
+ """
9
+ Search Wikipedia for a given query and return max 2 results.
10
+
11
+ Args:
12
+ query: The search query.
13
+ """
14
+ # Simulate a search operation
15
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
16
+
17
+ formatted_docs = "\n\n---\n\n".join(
18
+ [
19
+ f'<Document title="{doc.metadata["title"]}"/>\n{doc.page_content}\n</Document>'
20
+ for doc in search_docs
21
+ ])
22
+ return formatted_docs
23
+
24
+ @tool
25
+ def youtube_transcript(url: str) -> str:
26
+ """"Returns the transcript of a YouTube video given its URL.
27
+ Args:
28
+ url: The YouTube video URL.
29
+ """
30
+ try:
31
+ transcripts = YoutubeLoader.from_youtube_url(url, add_video_info=False).load()
32
+ return f"Video Transcript: {transcripts[0].page_content}"
33
+ except Exception as e:
34
+ return "No transcript available for this video. Error: {e}"
35
+
36
+ wrapper = DuckDuckGoSearchAPIWrapper(max_results=5)
37
+
38
+ search = DuckDuckGoSearchResults(output_format="list", api_wrapper=wrapper)
39
+
40
+ @tool
41
+ def web_search(query: str) -> str:
42
+ """
43
+ Perform a web search for the given query and return the results.
44
+ Use this when you need to find current or factual information.
45
+ Args:
46
+ query: The search query.
47
+ """
48
+ # Simulate a web search operation
49
+ query = "obama"
50
+ search_results = search.invoke(query)
51
+ formatted_result = "\n\n---\n\n".join([
52
+ f"- {result['title']}: {result['link']} \n {result['snippet']}"
53
+ for result in search_results
54
+ ])
55
+ return f"Web search results for '{query}'"
56
+
57
+ @tool
58
+ def add_numbers(numbers: List[float]) -> float:
59
+ """
60
+ Add a list of numbers together. E.g [1, 2, 3] -> 6
61
+ Args:
62
+ numbers: A list of numbers to add.
63
+ """
64
+ return sum(numbers)
65
+
66
+ @tool
67
+ def multiply_numbers(numbers: List[float]) -> float:
68
+ """
69
+ Multiply a list of numbers together. E.g [3, 2, 3] -> 18
70
+ Args:
71
+ numbers: A list of numbers to multiply.
72
+ """
73
+ result = 1
74
+ for number in numbers:
75
+ result *= number
76
+ return result
77
+
78
+
79
+
80
+ TOOLS = [wikipedia_search, web_search, youtube_transcript, add_numbers, multiply_numbers]
app.py CHANGED
@@ -1,9 +1,13 @@
 
1
  import os
2
  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"
@@ -12,12 +16,21 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
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
  """
@@ -76,11 +89,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
 
79
  if not task_id or question_text is None:
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
- submitted_answer = agent(question_text)
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
 
1
+ from io import BytesIO
2
  import os
3
  import gradio as gr
4
  import requests
5
  import inspect
6
  import pandas as pd
7
 
8
+ from langchain_core.messages import HumanMessage
9
+ from agent.graph import build_agent
10
+
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
16
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
17
  class BasicAgent:
18
  def __init__(self):
19
+ self.agent = build_agent()
20
+ def __call__(self, question: str, task_id: str, file_name="") -> str:
21
+ messages = [HumanMessage(content=question)]
22
+
23
+ if file_name:
24
+ task_id = "cca530fc-4052-43b2-b130-b30968d8aa44"
25
+ response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=15)
26
+ response.raise_for_status()
27
+ file_data = response.content
28
+ #file_data = BytesIO(file_data)
29
+
30
+
31
+ state = self.agent.invoke({"messages": messages, "file_name": file_name})
32
+ answer = state["messages"][-1].content
33
+ return answer
34
 
35
  def run_and_submit_all( profile: gr.OAuthProfile | None):
36
  """
 
89
  for item in questions_data:
90
  task_id = item.get("task_id")
91
  question_text = item.get("question")
92
+ file_name = item.get("file_name")
93
  if not task_id or question_text is None:
94
  print(f"Skipping item with missing task_id or question: {item}")
95
  continue
96
  try:
97
+ submitted_answer = agent(question_text, file_name=file_name)
98
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
99
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
100
  except Exception as e:
requirements.txt CHANGED
@@ -1,2 +1,9 @@
1
  gradio
2
- requests
 
 
 
 
 
 
 
 
1
  gradio
2
+ requests
3
+ langgraph
4
+ langchain
5
+ langchain-community
6
+ wikipedia
7
+ youtube-transcript-api
8
+ duckduckgo-search
9
+ docling