55
66try :
77 from langchain .chat_models .base import BaseChatModel
8+ from langchain_core .messages import AIMessage
89except ImportError :
910 raise ImportError ("langchain is not installed. Please install it using `pip install langchain`" )
1011
@@ -21,6 +22,35 @@ def __init__(self, config: Optional[BaseLlmConfig] = None):
2122
2223 self .langchain_model = self .config .model
2324
25+ def _parse_response (self , response : AIMessage , tools : Optional [List [Dict ]]):
26+ """
27+ Process the response based on whether tools are used or not.
28+
29+ Args:
30+ response: AI Message.
31+ tools: The list of tools provided in the request.
32+
33+ Returns:
34+ str or dict: The processed response.
35+ """
36+ if not tools :
37+ return response .content
38+
39+ processed_response = {
40+ "content" : response .content ,
41+ "tool_calls" : [],
42+ }
43+
44+ for tool_call in response .tool_calls :
45+ processed_response ["tool_calls" ].append (
46+ {
47+ "name" : tool_call ["name" ],
48+ "arguments" : tool_call ["args" ],
49+ }
50+ )
51+
52+ return processed_response
53+
2454 def generate_response (
2555 self ,
2656 messages : List [Dict [str , str ]],
@@ -34,32 +64,31 @@ def generate_response(
3464 Args:
3565 messages (list): List of message dicts containing 'role' and 'content'.
3666 response_format (str or object, optional): Format of the response. Not used in Langchain.
37- tools (list, optional): List of tools that the model can call. Not used in Langchain.
38- tool_choice (str, optional): Tool choice method. Not used in Langchain.
67+ tools (list, optional): List of tools that the model can call.
68+ tool_choice (str, optional): Tool choice method.
3969
4070 Returns:
4171 str: The generated response.
4272 """
43- try :
44- # Convert the messages to LangChain's tuple format
45- langchain_messages = []
46- for message in messages :
47- role = message ["role" ]
48- content = message ["content" ]
49-
50- if role == "system" :
51- langchain_messages .append (("system" , content ))
52- elif role == "user" :
53- langchain_messages .append (("human" , content ))
54- elif role == "assistant" :
55- langchain_messages .append (("ai" , content ))
73+ # Convert the messages to LangChain's tuple format
74+ langchain_messages = []
75+ for message in messages :
76+ role = message ["role" ]
77+ content = message ["content" ]
5678
57- if not langchain_messages :
58- raise ValueError ("No valid messages found in the messages list" )
79+ if role == "system" :
80+ langchain_messages .append (("system" , content ))
81+ elif role == "user" :
82+ langchain_messages .append (("human" , content ))
83+ elif role == "assistant" :
84+ langchain_messages .append (("ai" , content ))
5985
60- ai_message = self .langchain_model .invoke (langchain_messages )
86+ if not langchain_messages :
87+ raise ValueError ("No valid messages found in the messages list" )
6188
62- return ai_message .content
89+ langchain_model = self .langchain_model
90+ if tools :
91+ langchain_model = langchain_model .bind_tools (tools = tools , tool_choice = tool_choice )
6392
64- except Exception as e :
65- raise Exception ( f"Error generating response using langchain model: { str ( e ) } " )
93+ response : AIMessage = langchain_model . invoke ( langchain_messages )
94+ return self . _parse_response ( response , tools )
0 commit comments