Romain Fayoux commited on
Commit
cdf543a
·
1 Parent(s): f087af6

Connecting langchain agent to questions, trying to output the final

Browse files
Files changed (3) hide show
  1. app.py +6 -2
  2. langchain_agent.py +30 -20
  3. requirements.txt +1 -0
app.py CHANGED
@@ -7,8 +7,11 @@ import json
7
  import re
8
  from phoenix.otel import register
9
  from openinference.instrumentation.smolagents import SmolagentsInstrumentor
 
10
  from llm_only_agent import LLMOnlyAgent
11
  from multi_agent import MultiAgent
 
 
12
 
13
  # (Keep Constants as is)
14
  # --- Constants ---
@@ -50,7 +53,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None, limit: int | None):
50
 
51
  # 1. Instantiate Agent ( modify this part to create your agent)
52
  try:
53
- agent = LLMOnlyAgent()
54
  except Exception as e:
55
  print(f"Error instantiating agent: {e}")
56
  return f"Error initializing agent: {e}", None
@@ -113,7 +116,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None, limit: int | None):
113
  results_log = []
114
  answers_payload = []
115
  # Limit and skip youtube for test purposes
116
- limit = None
117
  skip_youtube = False
118
  if limit is not None:
119
  questions_data = questions_data[:limit]
@@ -253,6 +256,7 @@ if __name__ == "__main__":
253
  # Telemetry
254
  tracer_provider = register(project_name="final_assignment_template")
255
  SmolagentsInstrumentor().instrument(tracer_provider=tracer_provider)
 
256
 
257
  # Check for SPACE_HOST and SPACE_ID at startup for information
258
  space_host_startup = os.getenv("SPACE_HOST")
 
7
  import re
8
  from phoenix.otel import register
9
  from openinference.instrumentation.smolagents import SmolagentsInstrumentor
10
+ from openinference.instrumentation.langchain import LangChainInstrumentor
11
  from llm_only_agent import LLMOnlyAgent
12
  from multi_agent import MultiAgent
13
+ from langchain_agent import LangChainAgent
14
+
15
 
16
  # (Keep Constants as is)
17
  # --- Constants ---
 
53
 
54
  # 1. Instantiate Agent ( modify this part to create your agent)
55
  try:
56
+ agent = LangChainAgent()
57
  except Exception as e:
58
  print(f"Error instantiating agent: {e}")
59
  return f"Error initializing agent: {e}", None
 
116
  results_log = []
117
  answers_payload = []
118
  # Limit and skip youtube for test purposes
119
+ limit = 1
120
  skip_youtube = False
121
  if limit is not None:
122
  questions_data = questions_data[:limit]
 
256
  # Telemetry
257
  tracer_provider = register(project_name="final_assignment_template")
258
  SmolagentsInstrumentor().instrument(tracer_provider=tracer_provider)
259
+ LangChainInstrumentor().instrument(tracer_provider=tracer_provider)
260
 
261
  # Check for SPACE_HOST and SPACE_ID at startup for information
262
  space_host_startup = os.getenv("SPACE_HOST")
langchain_agent.py CHANGED
@@ -1,34 +1,44 @@
1
  import os
2
  from dotenv import load_dotenv
3
- from gradio.external import load_blocks_from_huggingface
4
  from langchain.agents import create_agent
5
- from langchain_community.tools.ddg_search.tool import DuckDuckGoSearchResults
6
  from langgraph.checkpoint.memory import InMemorySaver
7
  from langchain_community.tools import DuckDuckGoSearchRun
8
- from google.ai.generativelanguage_v1beta.types import Tool as GenAITool
9
- from langchain.messages import HumanMessage, AIMessage, SystemMessage
10
- from numpy import load
 
 
11
 
12
  load_dotenv()
13
- os.environ["GOOGLE_API_KEY"] = os.getenv("GEMINI_API_KEY")
14
 
15
- system_prompt = """finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
 
 
 
 
 
16
  YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
17
  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.
18
  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.
19
  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."""
20
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- agent = create_agent(
23
- model="google_genai:gemini-2.5-flash",
24
- tools=[DuckDuckGoSearchRun()],
25
- system_prompt=system_prompt,
26
- checkpointer=InMemorySaver(),
27
- )
28
-
29
- response = agent.invoke(
30
- {"messages": [{"role": "user", "content": "what is the weather in sf"}]},
31
- {"configurable": {"thread_id": "1"}},
32
- )
33
-
34
- print(response)
 
1
  import os
2
  from dotenv import load_dotenv
 
3
  from langchain.agents import create_agent
 
4
  from langgraph.checkpoint.memory import InMemorySaver
5
  from langchain_community.tools import DuckDuckGoSearchRun
6
+ from langchain.agents.middleware import (
7
+ ModelCallLimitMiddleware,
8
+ ToolCallLimitMiddleware,
9
+ )
10
+ from langchain.messages import HumanMessage, AIMessage
11
 
12
  load_dotenv()
 
13
 
14
+
15
+ class LangChainAgent:
16
+ def __init__(self):
17
+ os.environ["GOOGLE_API_KEY"] = os.getenv("GEMINI_API_KEY")
18
+
19
+ system_prompt = """finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
20
  YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
21
  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.
22
  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.
23
  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."""
24
 
25
+ self.agent = create_agent(
26
+ model="google_genai:gemini-2.5-flash",
27
+ tools=[DuckDuckGoSearchRun()],
28
+ system_prompt=system_prompt,
29
+ checkpointer=InMemorySaver(),
30
+ middleware=[
31
+ ModelCallLimitMiddleware(run_limit=10, exit_behavior="end"),
32
+ ToolCallLimitMiddleware(run_limit=20, exit_behavior="end"),
33
+ ],
34
+ )
35
 
36
+ def __call__(self, question: str) -> str:
37
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
38
+ response = self.agent.invoke(
39
+ {"messages": [HumanMessage(content=question)]},
40
+ {"configurable": {"thread_id": "1"}, "recursion_limit": 50},
41
+ )
42
+ answer = response["messages"][-1].text()
43
+ print(f"Agent returning answer: {answer}")
44
+ return answer
 
 
 
 
requirements.txt CHANGED
@@ -17,3 +17,4 @@ langchain-google-genai
17
  duckduckgo-search
18
  langchain-community
19
  python-dotenv
 
 
17
  duckduckgo-search
18
  langchain-community
19
  python-dotenv
20
+ openinference-instrumentation-langchain