Views
No views yet
1# Agente de Chamada de Função com LangChain e Prompt Personalizado
2
3Este projeto implementa um agente baseado em LangChain com um prompt personalizado para realizar chamadas de função, utilizando o modelo `GEMMA-2-2B-it-GGUF-function_calling` hospedado no Hugging Face.
4
5## Descrição
6
7O código cria um agente que utiliza ferramentas personalizadas e um modelo de linguagem para responder perguntas com base em um fluxo estruturado de pensamento e ação. Ele inclui uma ferramenta personalizada (`get_word_length`) que calcula o comprimento de uma palavra e um prompt ReAct modificado para guiar o raciocínio do agente.
8
9## Pré-requisitos
10
11- Python 3.8+
12- Bibliotecas necessárias:
13 ```bash
14 pip install langchain langchain-ollama1from langchain.agents import AgentExecutor
2from langchain.agents import tool, create_react_agent
3from langchain import hub
4from langchain_ollama.llms import OllamaLLM
5from langchain.prompts import PromptTemplate
6
7# Definir o modelo
8MODEL = "hf.co/vinimuchulski/GEMMA-2-2B-it-GGUF-function_calling:latest"
9llm = OllamaLLM(model=MODEL)
10
11# Criar ferramenta personalizada
12@tool
13def get_word_length(word: str) -> int:
14 """Retorna o comprimento de uma palavra."""
15 return len(word)
16
17# Definir prompt personalizado
18custom_react_prompt = PromptTemplate(
19 input_variables=["input", "agent_scratchpad", "tools", "tool_names"],
20 template="""Answer the following questions as best you can. You have access to the following tools:
21
22{tools}
23
24Use the following format:
25
26Question: the input question you must answer
27Thought: you should always think about what to do
28Action: the action to take, should be one of [{tool_names}]
29Action Input: the input to the action, formatted as a string
30Observation: the result of the action
31Thought: I now know the final answer
32Final Answer: the final answer to the original input question
33
34Example:
35Question: What is the length of the word "hello"?
36Thought: I need to use the get_word_length tool to calculate the length of the word "hello".
37Action: get_word_length
38Action Input: "hello"
39Observation: 5
40Thought: I now know the length of the word "hello" is 5.
41Final Answer: 5
42
43Begin!
44
45Question: {input}
46Thought: {agent_scratchpad}"""
47)
48
49# Configurar ferramentas
50tools = [get_word_length]
51tools_str = "\n".join([f"{tool.name}: {tool.description}" for tool in tools])
52tool_names = ", ".join([tool.name for tool in tools])
53
54# Criar o agente
55agent = create_react_agent(
56 tools=tools,
57 llm=llm,
58 prompt=custom_react_prompt.partial(tools=tools_str, tool_names=tool_names),
59)
60
61# Criar o executor
62agent_executor = AgentExecutor(
63 agent=agent,
64 tools=tools,
65 verbose=True,
66 handle_parsing_errors=True
67)
68
69# Testar o agente
70question = "What is the length of the word PythonDanelonAugustoTrajanoRomanovCzarVespasianoDiocleciano?"
71response = agent_executor.invoke({"input": question})
72print(response)