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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -32
app.py CHANGED
@@ -247,26 +247,20 @@
247
  # =================================================================================================
248
 
249
  #
250
-
251
  import os
252
  import io
253
- import json
254
  import requests
255
  import pandas as pd
256
  import gradio as gr
257
  from contextlib import redirect_stdout
258
- from typing import TypedDict, Annotated, List
259
- import operator
260
 
261
  # --- LangChain & LangGraph Imports ---
262
- from langchain_core.messages import BaseMessage, HumanMessage, ToolMessage
263
  from langchain_core.tools import tool
264
- # <<<--- CHANGE: Import ChatCohere and Cohere's Tool annd ToolCall classes--->>>
265
- from langchain_cohere import ChatCohere
266
- from langchain_cohere.cohere_agent import CohereAgent
267
- from langchain.agents import AgentExecutor
268
- from langgraph.graph import StateGraph, END
269
- from langgraph.prebuilt import ToolNode
270
  from tavily import TavilyClient
271
  import pypdf
272
 
@@ -276,7 +270,6 @@ FILES_DIR = "./files"
276
  os.makedirs(FILES_DIR, exist_ok=True)
277
 
278
  # --- System Prompt (Unchanged) ---
279
- # This prompt is excellent and requires no changes.
280
  AGENT_SYSTEM_PROMPT = """You are a world-class AI agent, specialized in solving complex problems from the GAIA benchmark.
281
  Your task is to analyze the user's question, think step-by-step, and use the provided tools to find the correct answer.
282
  CRITICAL INSTRUCTIONS:
@@ -341,25 +334,27 @@ def python_interpreter(code: str) -> str:
341
 
342
  #
343
  # ================================================================================================
344
- # ✅ 2. CONFIGURE AND BUILD THE AGENT (Using ChatCohere)
345
  # ================================================================================================
346
  #
347
- class AgentState(TypedDict):
348
- input: str
349
- chat_history: List[BaseMessage]
350
- agent_outcome: dict | None
351
-
352
  def build_agent_graph():
353
- """Builds the agent using the direct ChatCohere integration."""
354
  tools = [tavily_search, read_file, python_interpreter]
355
 
356
- # <<<--- CHANGE: Instantiate ChatCohere directly --->>>
357
- # It will use the COHERE_API_KEY from your secrets.
358
- # We use command-r-plus, Cohere's most powerful model.
359
- llm = ChatCohere(model="command-r-plus", temperature=0)
 
 
 
 
 
360
 
361
- # <<<--- This is much simpler now, as ChatCohere has built-in agent capabilities --->>>
362
- agent = CohereAgent(llm=llm, tools=tools)
 
 
363
  agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
364
 
365
  return agent_executor
@@ -371,16 +366,16 @@ def build_agent_graph():
371
  #
372
  class GaiaAgent:
373
  def __init__(self):
374
- print("GaiaAgent initialized. Building agent with direct ChatCohere integration...")
375
  self.agent_app = build_agent_graph()
376
 
377
  def __call__(self, question: str) -> str:
378
  print(f"\n{'='*60}\nAgent received question: {question[:100]}...\n{'='*60}")
379
  try:
380
- # The Cohere agent executor expects 'input' and a 'preamble' for the system message.
381
  response = self.agent_app.invoke({
382
  "input": question,
383
- "preamble": AGENT_SYSTEM_PROMPT
384
  })
385
  final_answer = str(response.get("output", "")).strip()
386
  print(f"\n--- Agent finished. Final Answer: {final_answer} ---\n")
@@ -389,7 +384,7 @@ class GaiaAgent:
389
  print(f"An error occurred during agent execution: {e}")
390
  return f"AGENT_EXECUTION_ERROR: {e}"
391
 
392
- # --- The rest of the file is mostly the same ---
393
  def run_and_submit_all( profile: gr.OAuthProfile | None):
394
  space_id = os.getenv("SPACE_ID")
395
  if not profile: return "Please Login to Hugging Face with the button.", None
@@ -441,9 +436,9 @@ with gr.Blocks() as demo:
441
  gr.Markdown("# GAIA Agent Final Assessment (Direct Cohere Integration)")
442
  gr.Markdown(
443
  """
444
- **Instructor's Note:** We are now using the direct `langchain-cohere` integration. This is the most reliable way to use the Command R+ model.
445
  1. Ensure you have a **`COHERE_API_KEY`** and a **`TAVILY_API_KEY`** set in your Space secrets.
446
- 2. Ensure your `requirements.txt` includes `langchain-cohere`.
447
  """
448
  )
449
  gr.LoginButton()
@@ -454,5 +449,4 @@ with gr.Blocks() as demo:
454
 
455
  if __name__ == "__main__":
456
  print("\n" + "-"*30 + " App Starting " + "-"*30)
457
- # Disable experimental SSR to prevent startup crashes
458
  demo.launch(debug=True, share=False, ssr_mode=False)
 
247
  # =================================================================================================
248
 
249
  #
 
250
  import os
251
  import io
 
252
  import requests
253
  import pandas as pd
254
  import gradio as gr
255
  from contextlib import redirect_stdout
256
+ from typing import List
 
257
 
258
  # --- LangChain & LangGraph Imports ---
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
 
 
270
  os.makedirs(FILES_DIR, exist_ok=True)
271
 
272
  # --- System Prompt (Unchanged) ---
 
273
  AGENT_SYSTEM_PROMPT = """You are a world-class AI agent, specialized in solving complex problems from the GAIA benchmark.
274
  Your task is to analyze the user's question, think step-by-step, and use the provided tools to find the correct answer.
275
  CRITICAL INSTRUCTIONS:
 
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
  #
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")
 
384
  print(f"An error occurred during agent execution: {e}")
385
  return f"AGENT_EXECUTION_ERROR: {e}"
386
 
387
+ # --- The rest of the file is unchanged ---
388
  def run_and_submit_all( profile: gr.OAuthProfile | None):
389
  space_id = os.getenv("SPACE_ID")
390
  if not profile: return "Please Login to Hugging Face with the button.", None
 
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
  """
443
  )
444
  gr.LoginButton()
 
449
 
450
  if __name__ == "__main__":
451
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
452
  demo.launch(debug=True, share=False, ssr_mode=False)