llm-math tool problem #26623
Replies: 1 comment 8 replies
-
The error you're encountering when invoking Correct Way to Configure Tools in LangChain v0.2
Example CodeHere is an example of how to configure and use the import asyncio
import json
import os
from typing import List
from azure.functions import HttpResponse
import logging
import httpx
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from datetime import datetime, timedelta
import calendar
from helpers.factor_planta_random_generator_helper import factor_planta_random_generator
from models.factor_planta_request import FactorPlantaRequest
from models.factor_planta_response import FactorPlanta, FactorPlantaResponse
from langchain_community.tools.llm_math import LLMMathChain
from langchain_core.agents import create_tool_calling_agent
async def func_asistente_comercializadora(req: FactorPlantaRequest, llm: BaseChatModel) -> HttpResponse:
# Initialize the LLM Math Chain
llm_math = LLMMathChain.from_llm(llm)
factores_planta = generate_random_factors(req.organization_id)
# Cadena de procesamiento con LangChain
chain_stadistics = (
RunnablePassthrough.assign(historical_data=(lambda x: set_factor_to_agent(factores_planta)))
| set_agent_prompt()
| llm_math
)
response = chain_stadistics.invoke({"input": "Analiza los factores de planta"})
chain = (
RunnablePassthrough.assign(language=(lambda x: str(req.language)))
.assign(historical_data=(lambda x: set_factor_planta_format(factores_planta)))
| set_system_prompt()
| llm_math
)
try:
# Ejecuta la cadena y captura el resultado
response = chain.invoke({"input": "Analiza los factores de planta"})
return HttpResponse(json.dumps({"content": response["answer"]}), status_code=200, mimetype="application/json")
except Exception as e:
logging.error(f"Error during LLM invocation: {e}")
return HttpResponse("Error processing plant factors", status_code=500)
# Other functions remain unchanged Explanation
This should resolve the error and configure the tools correctly in LangChain v0.2. If you encounter any further issues, please provide additional details for further assistance. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
i have the next code
`import asyncio
import json
import os
from typing import List
from azure.functions import HttpResponse
import logging
import httpx
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from datetime import datetime, timedelta
import calendar
from helpers.factor_planta_random_generator_helper import factor_planta_random_generator
from models.factor_planta_request import FactorPlantaRequest
from models.factor_planta_response import FactorPlanta, FactorPlantaResponse
from langchain.agents import load_tools, initialize_agent, AgentType, AgentExecutor, create_tool_calling_agent
async def func_asistente_comercializadora(req: FactorPlantaRequest, llm: BaseChatModel) -> HttpResponse:
tools = load_tools(["llm-math"], llm=llm)
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors=True)
async def fetch_plant_factors(client: httpx.AsyncClient, week_url: str, historical_url: str):
"""
Función para realizar las solicitudes asíncronas de factores planta semanales e históricos.
"""
tasks = [client.get(url=week_url), client.get(url=historical_url)]
def set_system_prompt():
"""
Función para establecer la plantilla de prompt del sistema.
"""
template = (
"""You are an assistant in charge of analyzing the plant factors of the week and historical plant factors\n
Please note the following information:
- The plant factor is the relationship between the energy consumed and the maximum energy installed and indicates the level of use of the company's network.
- The closer the value of the plant factor is to 1, the more the network is being fully used.\n
- When the plant factor values decrease, it may be due to factors such as equipment running periodically or being shut down.\n
- If the plant factor values are below 70%, it indicates a loss of utility and an overdesigned system.\n
- If the plant factor is greater than 1, more energy than designed is being used.\n
- Get the most relevant statistical data from the data provided\n
Once the analysis is complete, present the results in a clear and easy-to-understand format.
If there are any specific ideas or factors that you think I should consider based on this analysis, please highlight those as well. Thank you.\n
If the language is 0 you must respond in Spanish, otherwise respond in English.\n
The following is the data to be analyzed:\n\n
Language: {language}
HistoricalData: {historical_data}\n\n
The data are lists which have the following structure:\n
'year': 'int',\n
'mes': 'int',\n
'semana': 'int',\n
'nombreMes': 'string',\n
'factorPlanta': 'float',\n
'organization': 'string'\n\n
Where:
- 'year': represents the year of the data.\n
- 'mes': represents the numerical month of the data.\n
- 'semana': represents the week of the data.\n
- 'nombreMes': represents the name of the month.\n
- 'factorPlanta': represents the value of the plant factor.\n
- 'organization': represents the counter of the organization being analyzed.
"""
)
return ChatPromptTemplate.from_template(template)
def set_factor_planta_format(factores_planta: List[FactorPlanta]):
"""
Formatea los factores de planta como una lista de cadenas JSON.
"""
return "\n".join(factor.model_dump_json() for factor in factores_planta)
def set_factor_to_agent(factores_planta: List[FactorPlanta]):
"""
Formatea los factores de planta como una lista de numeros.
"""
return "\n".join(str(factor.factorPlanta) for factor in factores_planta)
def set_agent_prompt():
template = """You are the agent specialized in descriptive statistics, from the following data: \n
Data: {historical_data}\n\n
-calculate the mean, median and mode.
-range, variance and standard deviation of the data ."""
return ChatPromptTemplate.from_template(template)
def generate_random_factors(org_id: str):
current_date = datetime.now()
start_of_year = datetime(current_date.year, 1, 1)
days_passed = (current_date - start_of_year).days
weeks_passed = days_passed // 7
`
when i execute
response = chain_stadistics.invoke( {"input": "Analiza los factores de planta"})
i have the next error
[2024-09-18T15:44:39.037Z] Stack: File "/usr/lib/azure-functions-core-tools/workers/python/3.11/LINUX/X64/azure_functions_worker/dispatcher.py", line 602, in _handle__invocation_request [2024-09-18T15:44:39.037Z] await self._run_async_func(fi_context, fi.func, args) [2024-09-18T15:44:39.037Z] File "/usr/lib/azure-functions-core-tools/workers/python/3.11/LINUX/X64/azure_functions_worker/dispatcher.py", line 939, in _run_async_func [2024-09-18T15:44:39.037Z] return await ExtensionManager.get_async_invocation_wrapper( [2024-09-18T15:44:39.037Z] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.037Z] File "/usr/lib/azure-functions-core-tools/workers/python/3.11/LINUX/X64/azure_functions_worker/extension.py", line 147, in get_async_invocation_wrapper [2024-09-18T15:44:39.037Z] result = await function(**args) [2024-09-18T15:44:39.038Z] ^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.038Z] File "/workspaces/Az-Function-Asistente-Comercializadora/function_app.py", line 19, in asistente_comercializadora [2024-09-18T15:44:39.038Z] return await func_asistente_comercializadora(request,llm) [2024-09-18T15:44:39.038Z] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.038Z] File "/workspaces/Az-Function-Asistente-Comercializadora/functions/func_asistente_comercializadora.py", line 49, in func_asistente_comercializadora [2024-09-18T15:44:39.039Z] response = chain_stadistics.invoke( [2024-09-18T15:44:39.039Z] ^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.039Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 2878, in invoke [2024-09-18T15:44:39.039Z] input = context.run(step.invoke, input, config) [2024-09-18T15:44:39.039Z] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.039Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/chains/base.py", line 164, in invoke [2024-09-18T15:44:39.039Z] raise e [2024-09-18T15:44:39.039Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/chains/base.py", line 154, in invoke [2024-09-18T15:44:39.039Z] self._call(inputs, run_manager=run_manager) [2024-09-18T15:44:39.039Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/agents/agent.py", line 1608, in _call [2024-09-18T15:44:39.039Z] next_step_output = self._take_next_step( [2024-09-18T15:44:39.039Z] ^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.039Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/agents/agent.py", line 1314, in _take_next_step [2024-09-18T15:44:39.040Z] [ [2024-09-18T15:44:39.040Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/agents/agent.py", line 1314, in <listcomp> [2024-09-18T15:44:39.040Z] [ [2024-09-18T15:44:39.040Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/agents/agent.py", line 1399, in _iter_next_step [2024-09-18T15:44:39.040Z] yield self._perform_agent_action( [2024-09-18T15:44:39.040Z] ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.040Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/agents/agent.py", line 1421, in _perform_agent_action [2024-09-18T15:44:39.040Z] observation = tool.run( [2024-09-18T15:44:39.040Z] ^^^^^^^^^ [2024-09-18T15:44:39.040Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain_core/tools/base.py", line 585, in run [2024-09-18T15:44:39.040Z] raise error_to_raise [2024-09-18T15:44:39.040Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain_core/tools/base.py", line 554, in run [2024-09-18T15:44:39.040Z] response = context.run(self._run, *tool_args, **tool_kwargs) [2024-09-18T15:44:39.041Z] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.041Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain_core/tools/simple.py", line 84, in _run [2024-09-18T15:44:39.041Z] return self.func(*args, **kwargs) [2024-09-18T15:44:39.041Z] ^^^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.041Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain_core/_api/deprecation.py", line 180, in warning_emitting_wrapper [2024-09-18T15:44:39.041Z] return wrapped(*args, **kwargs) [2024-09-18T15:44:39.041Z] ^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.041Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/chains/base.py", line 598, in run [2024-09-18T15:44:39.041Z] return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[ [2024-09-18T15:44:39.041Z] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.041Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain_core/_api/deprecation.py", line 180, in warning_emitting_wrapper [2024-09-18T15:44:39.041Z] return wrapped(*args, **kwargs) [2024-09-18T15:44:39.041Z] ^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.041Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/chains/base.py", line 381, in __call__ [2024-09-18T15:44:39.041Z] return self.invoke( [2024-09-18T15:44:39.042Z] ^^^^^^^^^^^^ [2024-09-18T15:44:39.042Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/chains/base.py", line 164, in invoke [2024-09-18T15:44:39.042Z] raise e [2024-09-18T15:44:39.042Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/chains/base.py", line 154, in invoke [2024-09-18T15:44:39.042Z] self._call(inputs, run_manager=run_manager) [2024-09-18T15:44:39.042Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/chains/llm_math/base.py", line 157, in _call [2024-09-18T15:44:39.042Z] return self._process_llm_result(llm_output, _run_manager) [2024-09-18T15:44:39.042Z] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [2024-09-18T15:44:39.042Z] File "/workspaces/Az-Function-Asistente-Comercializadora/.venv/lib/python3.11/site-packages/langchain/chains/llm_math/base.py", line 120, in _process_llm_result [2024-09-18T15:44:39.042Z] raise ValueError(f"unknown format from LLM: {llm_output}") [2024-09-18T15:44:39.042Z] .
what could be happening?
what is the correct way to configure the tools in langchain v 0.2
Beta Was this translation helpful? Give feedback.
All reactions