Final_Assignment_Template / basic_agent.py
juancitro's picture
Second commit, grant certificate, and various tests
81769c3
Raw History Blame Contribute Delete
4.43 kB
from langgraph.graph import Graph, add_messages
from langchain.prompts import PromptTemplate
from langchain_ollama.chat_models import ChatOllama
from langchain_ollama.llms import OllamaLLM
from langchain.agents import AgentExecutor, create_react_agent, Tool
from langchain_ollama import OllamaEmbeddings
from langchain_community.tools import DuckDuckGoSearchRun
EMBEDDINGS_MODEL = "bge-m3"
# ollama pull nomic-embed-text
# mxbai-embed-large
embeddings = OllamaEmbeddings(model=EMBEDDINGS_MODEL)
CHAT_MODEL = "gemma3:4b"
llm = ChatOllama(
model=CHAT_MODEL,
temperature=0.0,
#max_tokens=512,
#streaming=True,
verbose=True,
)
SYSTEM_PROMPT = """
You are a general AI assistant. I will ask you a question.
Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
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.
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.
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.
"""
REACT_PROMPT = """
Answer the following questions as best you can. You have access to the following tools:
{tools}
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
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.
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.
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.
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Question: {input}
Thought:{agent_scratchpad}
"""
AGENT_PROMPT = PromptTemplate.from_template(REACT_PROMPT)
# USER_PROMPT_TEMPLATE = """
# Answer the following question as best you can.
# Do not use a tool if not required.
# Question: {question}
# """
# user_prompt_template = PromptTemplate.from_template(USER_PROMPT_TEMPLATE)
class BasicAgent():
def __init__(self, prompt=AGENT_PROMPT, tools=[], llm=llm, embeddings=embeddings):
print("Agent initialized.")
self.llm = llm
self.embeddings = embeddings
self.tools = tools + self.setup_base_tools()
self.prompt = prompt
self.graph = self.__initialize_graph()
def __initialize_graph(self):
agent = create_react_agent(llm, self.tools, self.prompt)
agent_executor = AgentExecutor(agent=agent, tools=self.tools, verbose=True)
return agent_executor
def setup_base_tools(self):
search = DuckDuckGoSearchRun()
duckduckgo_tool = Tool(
name = 'DuckDuckGo Search',
func = search.run,
description = '''
A wrapper around DuckDuckGo Search.
Useful for when you need to answer questions about current events, and search some information in the web.
Input should be a search query.
'''
)
tools = [duckduckgo_tool]
return tools
def __call__(self, question: str) -> str:
print(f"Agent received question (first 50 chars): {question[:50]}...")
fixed_answer = self.graph.invoke({"input": question})
print(f"Agent returning fixed answer: {fixed_answer['output']}")
return fixed_answer["output"]
# basic_agent = BasicAgent(tools=[DuckDuckGoSearchRun()])
basic_agent = BasicAgent()
if __name__ == "__main__":
# answer = basic_agent("What is the capital of France?")
# print(type(answer))
# print(answer)
pass