Feat: New prompt
This commit is contained in:
@@ -7,6 +7,8 @@ from langchain_core.tools import render_text_description
|
||||
from langchain.chains import create_history_aware_retriever
|
||||
from langchain.chains.combine_documents import create_stuff_documents_chain
|
||||
import langchain.chains
|
||||
from langchain.chains import create_history_aware_retriever
|
||||
from langchain.chains.combine_documents import create_stuff_documents_chain
|
||||
from langchain.agents.format_scratchpad import format_log_to_str
|
||||
from langchain.chains import create_retrieval_chain
|
||||
from langchain_aws import ChatBedrock
|
||||
@@ -17,6 +19,7 @@ from langchain_core.agents import AgentAction, AgentFinish
|
||||
from langchain.agents.output_parsers import ReActSingleInputOutputParser
|
||||
from langchain.tools import Tool
|
||||
import os
|
||||
|
||||
def find_tool_by_name(tools: list[Tool],tool_name:str):
|
||||
for tool in tools:
|
||||
if tool.name==tool_name:
|
||||
@@ -25,30 +28,36 @@ def find_tool_by_name(tools: list[Tool],tool_name:str):
|
||||
return tool
|
||||
raise ValueError(f"Tool with name {tool_name} not found")
|
||||
def agent_call(event,context):
|
||||
|
||||
llm = ChatBedrock(
|
||||
model_id="arn:aws:bedrock:us-east-1:654654422992:application-inference-profile/d9blf0g3fzqz",
|
||||
region_name="us-east-1",
|
||||
aws_access_key_id=os.environ["AWS_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"],
|
||||
aws_session_token=os.environ["AWS_SESSION_TOKEN"],
|
||||
model_kwargs={"temperature": 0.2, 'max_tokens': 1000,},
|
||||
model_kwargs={"temperature": 0, 'max_tokens': 1000,},
|
||||
provider='anthropic'
|
||||
)
|
||||
retriever = AmazonKnowledgeBasesRetriever(
|
||||
knowledge_base_id="RBD9TI5HYU",
|
||||
region_name="us-east-1",
|
||||
retrieval_config={"vectorSearchConfiguration": {"numberOfResults": 4}},
|
||||
|
||||
|
||||
)
|
||||
print("Hello React Langhain")
|
||||
tools=[retriever.as_tool()]
|
||||
|
||||
# Cria o retrieval chain
|
||||
retrievertool=retriever.as_tool()
|
||||
retrievertool.description="Baseando se numa query retorna trechos de editais de campus diferentes do instituto são paulo"
|
||||
tools=[retrievertool]
|
||||
template="""Você é um assistente para alunos de diversos campus diferentes do instituto federal de são paulo, sua função é responder perguntas
|
||||
de forma mais eficiente possivel sobre editais, que pode ser acessados pela tool fornecida:
|
||||
|
||||
{tools}
|
||||
|
||||
Note que dependendo do Campus os editais são diferentes, então é mandatório saber o campus do aluno antes de devolver alguma informação.
|
||||
Além disso leve em consideração o chat history fornecido.
|
||||
Além disso existem editais válidos apenas para alunos do ensino médio, apaenas para ensino superior e para ambos.
|
||||
O edital difere também se o aluno já recebe algum auxílio ou é o primeiro. Obtenha a informação do edital mais recente que cumpra as condições.
|
||||
Além disso leve em consideração o chat history fornecido. Responda baseando-se exclusivamente nos documentos retornados pela tool amazonknowledgebase retriever. Não crie informações de editais.
|
||||
Use the following format:
|
||||
|
||||
Question: the input question you must answer
|
||||
@@ -69,8 +78,8 @@ Thought: {agent_scratchpad}
|
||||
#llm=ChatOpenAI(model="gpt-4o-mini",temperature=0,stop_sequences=["\nObservation:"])
|
||||
intermediate_steps=[]
|
||||
|
||||
agent= {"input": lambda x:x["input"],"agent_scratchpad": lambda x:format_log_to_str(x["agent_scratchpad"]),"chat_history":lambda x:x["chat_history"]}|prompt | llm|ReActJsonSingleInputOutputParser()
|
||||
agent_step: Union[AgentAction,AgentFinish]=agent.invoke({"input": "Que dia é hoje?","agent_scratchpad":intermediate_steps,"chat_history":{"role":"user","content":"sou do campus sao paulo"}})
|
||||
agent= {"input": lambda x:x["input"],"agent_scratchpad": lambda x:format_log_to_str(x["agent_scratchpad"]),"chat_history":lambda x:x["chat_history"]}|prompt | llm
|
||||
agent_step: Union[AgentAction,AgentFinish]=agent.invoke({"input": "Quanto é o valor do auxilio moradia?","agent_scratchpad":intermediate_steps,"chat_history":{"role":"user","content":"sou do campus sao paulo, ensino superior e não recebo auxílio ainda, estamos no primeiro semestre de 2025"}})
|
||||
#print(agent_step)
|
||||
if isinstance(agent_step,AgentAction):
|
||||
tool_name=agent_step.tool
|
||||
@@ -79,10 +88,11 @@ Thought: {agent_scratchpad}
|
||||
observation=tool_to_use.func(str(tool_input))
|
||||
print(f"{observation=}")
|
||||
intermediate_steps.append((agent_step,str(observation)))
|
||||
agent_step: Union[AgentAction,AgentFinish]=agent.invoke({"input": "Quanto é o valor do auxilio moradia?","agent_scratchpad":intermediate_steps,"chat_history":{"role":"user","content":"sou do campus sao paulo"}})
|
||||
agent_step: Union[AgentAction,AgentFinish]=agent.invoke({"input": "Quanto é o valor do auxilio moradia?","agent_scratchpad":intermediate_steps,"chat_history":{"role":"user","content":"sou do campus sao paulo, ensino superior e não recebo auxílio ainda, estamos no primeiro semestre de 2025"}})
|
||||
return agent_step
|
||||
def hello(event,context):
|
||||
return{
|
||||
"statusCode":200,
|
||||
"body":json.dumps("hello_world")
|
||||
}
|
||||
print(agent_call("",""))
|
||||
Reference in New Issue
Block a user