Spaces:
Running
Running
Update graph.py
Browse files
graph.py
CHANGED
@@ -1,81 +1,81 @@
|
|
1 |
-
from utils import MainState, generate_uuid, llm
|
2 |
-
from langchain_core.messages import AIMessage, ToolMessage, HumanMessage
|
3 |
-
from langchain_core.prompts import ChatPromptTemplate
|
4 |
-
from langgraph.graph import StateGraph, START, END
|
5 |
-
import re
|
6 |
-
|
7 |
-
def get_graph(retriever):
|
8 |
-
def retriever_node(state: MainState):
|
9 |
-
return {
|
10 |
-
'question': state['question'],
|
11 |
-
'scratchpad': state['scratchpad'] + [ToolMessage(content=retriever.invoke(state['question'].content),
|
12 |
-
tool_call_id=state['scratchpad'][-1].tool_call_id)],
|
13 |
-
'answer': state['answer'],
|
14 |
-
'next_node': 'model_node',
|
15 |
-
'history': state['history']
|
16 |
-
}
|
17 |
-
|
18 |
-
import re
|
19 |
-
|
20 |
-
def model_node(state: MainState):
|
21 |
-
prompt = ChatPromptTemplate.from_template(
|
22 |
-
"""
|
23 |
-
Você é um assistente de IA. Responda à pergunta abaixo da forma mais precisa possível.
|
24 |
-
|
25 |
-
Caso não tenha informações para responder à pergunte **retorne apenas** uma resposta no seguinte formato:
|
26 |
-
<tool>retriever</tool>,
|
27 |
-
ao fazer isso a task será repassada para um agente que irá complementar as informações.
|
28 |
-
Se a pergunta puder ser respondida sem acessar documentos enviados, forneça uma resposta **concisa e objetiva**, com no máximo três sentenças.
|
29 |
-
|
30 |
-
### Contexto:
|
31 |
-
- Bloco de Notas: {scratchpad}
|
32 |
-
- Histórico de Conversas: {chat_history}
|
33 |
-
|
34 |
-
**Pergunta:** {question}
|
35 |
-
"""
|
36 |
-
)
|
37 |
-
|
38 |
-
if isinstance(state['question'], str):
|
39 |
-
state['question'] = HumanMessage(content=state['question'])
|
40 |
-
|
41 |
-
qa_chain = prompt | llm
|
42 |
-
|
43 |
-
response = qa_chain.invoke({'question': state['question'].content,
|
44 |
-
'scratchpad': state['scratchpad'],
|
45 |
-
'chat_history': [
|
46 |
-
f'AI: {msg.content}' if isinstance(msg, AIMessage) else f'Human: {msg.content}'
|
47 |
-
for msg in state['history']],
|
48 |
-
})
|
49 |
-
|
50 |
-
if '<tool>' in response.content:
|
51 |
-
return {
|
52 |
-
'question': state['question'],
|
53 |
-
'scratchpad': state['scratchpad'] + [AIMessage(content='', tool_call_id=generate_uuid())] if state[
|
54 |
-
'scratchpad'] else [AIMessage(content='', tool_call_id=generate_uuid())],
|
55 |
-
'answer': state['answer'],
|
56 |
-
'next_node': 'retriever',
|
57 |
-
'history': state['history']
|
58 |
-
}
|
59 |
-
|
60 |
-
# print(state['scratchpad'])
|
61 |
-
return {
|
62 |
-
'question': state['question'],
|
63 |
-
'scratchpad': state['scratchpad'],
|
64 |
-
'answer': response,
|
65 |
-
'next_node': END,
|
66 |
-
'history': state['history'] + [HumanMessage(content=state['question'].content), response]
|
67 |
-
}
|
68 |
-
|
69 |
-
def next_node(state: MainState):
|
70 |
-
return state['next_node']
|
71 |
-
|
72 |
-
graph = StateGraph(MainState)
|
73 |
-
graph.add_node('model', model_node)
|
74 |
-
graph.add_node('retriever', retriever_node)
|
75 |
-
graph.add_edge(START, 'model')
|
76 |
-
graph.add_edge('retriever', 'model')
|
77 |
-
graph.add_conditional_edges('model', next_node)
|
78 |
-
|
79 |
-
chain = graph.compile()
|
80 |
-
|
81 |
return chain
|
|
|
1 |
+
from utils import MainState, generate_uuid, llm
|
2 |
+
from langchain_core.messages import AIMessage, ToolMessage, HumanMessage
|
3 |
+
from langchain_core.prompts import ChatPromptTemplate
|
4 |
+
from langgraph.graph import StateGraph, START, END
|
5 |
+
import re
|
6 |
+
|
7 |
+
def get_graph(retriever):
|
8 |
+
def retriever_node(state: MainState):
|
9 |
+
return {
|
10 |
+
'question': state['question'],
|
11 |
+
'scratchpad': state['scratchpad'] + [ToolMessage(content=retriever.invoke(state['question'].content),
|
12 |
+
tool_call_id=state['scratchpad'][-1].tool_call_id)],
|
13 |
+
'answer': state['answer'],
|
14 |
+
'next_node': 'model_node',
|
15 |
+
'history': state['history']
|
16 |
+
}
|
17 |
+
|
18 |
+
import re
|
19 |
+
|
20 |
+
def model_node(state: MainState):
|
21 |
+
prompt = ChatPromptTemplate.from_template(
|
22 |
+
"""
|
23 |
+
Você é um assistente de IA chamado DocAI. Responda à pergunta abaixo da forma mais precisa possível.
|
24 |
+
|
25 |
+
Caso não tenha informações para responder à pergunte **retorne apenas** uma resposta no seguinte formato:
|
26 |
+
<tool>retriever</tool>,
|
27 |
+
ao fazer isso a task será repassada para um agente que irá complementar as informações.
|
28 |
+
Se a pergunta puder ser respondida sem acessar documentos enviados, forneça uma resposta **concisa e objetiva**, com no máximo três sentenças.
|
29 |
+
|
30 |
+
### Contexto:
|
31 |
+
- Bloco de Notas: {scratchpad}
|
32 |
+
- Histórico de Conversas: {chat_history}
|
33 |
+
|
34 |
+
**Pergunta:** {question}
|
35 |
+
"""
|
36 |
+
)
|
37 |
+
|
38 |
+
if isinstance(state['question'], str):
|
39 |
+
state['question'] = HumanMessage(content=state['question'])
|
40 |
+
|
41 |
+
qa_chain = prompt | llm
|
42 |
+
|
43 |
+
response = qa_chain.invoke({'question': state['question'].content,
|
44 |
+
'scratchpad': state['scratchpad'],
|
45 |
+
'chat_history': [
|
46 |
+
f'AI: {msg.content}' if isinstance(msg, AIMessage) else f'Human: {msg.content}'
|
47 |
+
for msg in state['history']],
|
48 |
+
})
|
49 |
+
|
50 |
+
if '<tool>' in response.content:
|
51 |
+
return {
|
52 |
+
'question': state['question'],
|
53 |
+
'scratchpad': state['scratchpad'] + [AIMessage(content='', tool_call_id=generate_uuid())] if state[
|
54 |
+
'scratchpad'] else [AIMessage(content='', tool_call_id=generate_uuid())],
|
55 |
+
'answer': state['answer'],
|
56 |
+
'next_node': 'retriever',
|
57 |
+
'history': state['history']
|
58 |
+
}
|
59 |
+
|
60 |
+
# print(state['scratchpad'])
|
61 |
+
return {
|
62 |
+
'question': state['question'],
|
63 |
+
'scratchpad': state['scratchpad'],
|
64 |
+
'answer': response,
|
65 |
+
'next_node': END,
|
66 |
+
'history': state['history'] + [HumanMessage(content=state['question'].content), response]
|
67 |
+
}
|
68 |
+
|
69 |
+
def next_node(state: MainState):
|
70 |
+
return state['next_node']
|
71 |
+
|
72 |
+
graph = StateGraph(MainState)
|
73 |
+
graph.add_node('model', model_node)
|
74 |
+
graph.add_node('retriever', retriever_node)
|
75 |
+
graph.add_edge(START, 'model')
|
76 |
+
graph.add_edge('retriever', 'model')
|
77 |
+
graph.add_conditional_edges('model', next_node)
|
78 |
+
|
79 |
+
chain = graph.compile()
|
80 |
+
|
81 |
return chain
|