kamorou commited on
Commit
e2bb92a
·
verified ·
1 Parent(s): a6b7e42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -19
app.py CHANGED
@@ -259,8 +259,13 @@ from typing import List
259
  from langchain_core.messages import BaseMessage
260
  from langchain_core.tools import tool
261
  from langchain_cohere.chat_models import ChatCohere
262
- from langchain.agents import AgentExecutor, create_cohere_tools_agent
263
  from langchain_core.prompts import ChatPromptTemplate
 
 
 
 
 
264
  from tavily import TavilyClient
265
  import pypdf
266
 
@@ -334,27 +339,39 @@ def python_interpreter(code: str) -> str:
334
 
335
  #
336
  # ================================================================================================
337
- # ✅ 2. CONFIGURE AND BUILD THE AGENT (Standard, Robust Method)
338
  # ================================================================================================
339
  #
340
  def build_agent_graph():
341
- """Builds the agent using the standard create_cohere_tools_agent function."""
342
  tools = [tavily_search, read_file, python_interpreter]
343
 
344
- # Instantiate the ChatCohere model
345
  llm = ChatCohere(model="command-r-plus", temperature=0, cohere_api_key=os.getenv("COHERE_API_KEY"))
346
 
347
- # Create the prompt template. The 'agent_scratchpad' is crucial.
 
 
 
348
  prompt = ChatPromptTemplate.from_messages([
349
  ("system", AGENT_SYSTEM_PROMPT),
350
- ("human", "{input}"),
351
- ("placeholder", "{agent_scratchpad}"),
352
  ])
353
 
354
- # Use the standard agent creation function
355
- agent = create_cohere_tools_agent(llm, tools, prompt)
356
-
357
- # Create the executor to run the agent loop
 
 
 
 
 
 
 
 
 
358
  agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
359
 
360
  return agent_executor
@@ -366,17 +383,14 @@ def build_agent_graph():
366
  #
367
  class GaiaAgent:
368
  def __init__(self):
369
- print("GaiaAgent initialized. Building agent with create_cohere_tools_agent...")
370
  self.agent_app = build_agent_graph()
371
 
372
  def __call__(self, question: str) -> str:
373
  print(f"\n{'='*60}\nAgent received question: {question[:100]}...\n{'='*60}")
374
  try:
375
- # The standard agent executor expects 'input' and 'chat_history'.
376
- response = self.agent_app.invoke({
377
- "input": question,
378
- "chat_history": [] # Each question is independent, so history is empty.
379
- })
380
  final_answer = str(response.get("output", "")).strip()
381
  print(f"\n--- Agent finished. Final Answer: {final_answer} ---\n")
382
  return final_answer
@@ -430,13 +444,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
430
  f"Message: {result_data.get('message', 'No message received.')}"
431
  )
432
  return final_status, pd.DataFrame(results_log)
433
- except Exception as e: return f"An unexpected error occurred during submission: {e}", pd.DataFrame(results_log)
434
 
435
  with gr.Blocks() as demo:
436
  gr.Markdown("# GAIA Agent Final Assessment (Direct Cohere Integration)")
437
  gr.Markdown(
438
  """
439
- **Instructor's Note:** This version uses the standard `create_cohere_tools_agent` function, which is the most robust way to create a tool-calling agent with Cohere.
440
  1. Ensure you have a **`COHERE_API_KEY`** and a **`TAVILY_API_KEY`** set in your Space secrets.
441
  2. Ensure your `requirements.txt` includes `langchain-cohere` and `langchain`.
442
  """
 
259
  from langchain_core.messages import BaseMessage
260
  from langchain_core.tools import tool
261
  from langchain_cohere.chat_models import ChatCohere
262
+ from langchain.agents import AgentExecutor
263
  from langchain_core.prompts import ChatPromptTemplate
264
+ # These are the fundamental components we need for a Cohere Tools agent
265
+ from langchain.agents.format_scratchpad.cohere import format_cohere_tools
266
+ from langchain.agents.output_parsers.cohere import CohereToolsAgentOutputParser
267
+
268
+
269
  from tavily import TavilyClient
270
  import pypdf
271
 
 
339
 
340
  #
341
  # ================================================================================================
342
+ # ✅ 2. CONFIGURE AND BUILD THE AGENT (Manual, Stable Method)
343
  # ================================================================================================
344
  #
345
  def build_agent_graph():
346
+ """Builds the agent using the most fundamental LangChain components."""
347
  tools = [tavily_search, read_file, python_interpreter]
348
 
349
+ # 1. Create the ChatCohere model instance
350
  llm = ChatCohere(model="command-r-plus", temperature=0, cohere_api_key=os.getenv("COHERE_API_KEY"))
351
 
352
+ # 2. Bind the tools to the LLM. This lets the LLM know about the tools.
353
+ llm_with_tools = llm.bind_tools(tools)
354
+
355
+ # 3. Create the prompt template. This is the core instruction for the agent.
356
  prompt = ChatPromptTemplate.from_messages([
357
  ("system", AGENT_SYSTEM_PROMPT),
358
+ ("user", "{input}"),
359
+ ("placeholder", "{agent_scratchpad}"), # This is where tool results will be injected.
360
  ])
361
 
362
+ # 4. Define the agent runnable. This is a chain that pipes components together.
363
+ # It formats the input, sends it to the LLM, and parses the output.
364
+ agent = (
365
+ {
366
+ "input": lambda x: x["input"],
367
+ "agent_scratchpad": lambda x: format_cohere_tools(x["intermediate_steps"]),
368
+ }
369
+ | prompt
370
+ | llm_with_tools
371
+ | CohereToolsAgentOutputParser()
372
+ )
373
+
374
+ # 5. Create the AgentExecutor to run the agent-tool loop.
375
  agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
376
 
377
  return agent_executor
 
383
  #
384
  class GaiaAgent:
385
  def __init__(self):
386
+ print("GaiaAgent initialized. Building agent with fundamental LangChain components...")
387
  self.agent_app = build_agent_graph()
388
 
389
  def __call__(self, question: str) -> str:
390
  print(f"\n{'='*60}\nAgent received question: {question[:100]}...\n{'='*60}")
391
  try:
392
+ # The standard agent executor expects 'input'.
393
+ response = self.agent_app.invoke({"input": question})
 
 
 
394
  final_answer = str(response.get("output", "")).strip()
395
  print(f"\n--- Agent finished. Final Answer: {final_answer} ---\n")
396
  return final_answer
 
444
  f"Message: {result_data.get('message', 'No message received.')}"
445
  )
446
  return final_status, pd.DataFrame(results_log)
447
+ except Exception as e: return f"An unexpected error in submission: {e}", pd.DataFrame(results_log)
448
 
449
  with gr.Blocks() as demo:
450
  gr.Markdown("# GAIA Agent Final Assessment (Direct Cohere Integration)")
451
  gr.Markdown(
452
  """
453
+ **Instructor's Note:** This version uses a fundamental, manual agent construction. It is the most stable and recommended approach, avoiding any version-specific helper functions.
454
  1. Ensure you have a **`COHERE_API_KEY`** and a **`TAVILY_API_KEY`** set in your Space secrets.
455
  2. Ensure your `requirements.txt` includes `langchain-cohere` and `langchain`.
456
  """