Add bind tools to custom BaseChatModel #26146
Replies: 2 comments 7 replies
-
To bind tools to your custom
Here's how you can implement it: from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.utils.function_calling import convert_to_openai_tool
# Define your tools
class GetWeather(BaseModel):
'''Get the current weather in a given location'''
location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
class GetPopulation(BaseModel):
'''Get the current population in a given location'''
location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
# Your custom chat model
class GPT4oCustomChatModel(BaseChatModel):
# ... (your existing implementation)
def bind_tools(self, tools):
formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
return super().bind_tools(formatted_tools)
# Initialize your custom chat model
llm = GPT4oCustomChatModel(
client_id="your_client_id",
client_secret="your_client_secret",
apim_Subscription_Key="your_subscription_key",
api_url="https://api.yourservice.com/v1",
model_name="gpt-4o",
token_manager=TokenManager(),
temperature=0.7,
top_p=0.95,
max_tokens=8000,
)
# Bind the tools to the chat model
tools = [GetWeather, GetPopulation]
llm_with_tools = llm.bind_tools(tools)
# Example usage
ai_msg = llm_with_tools.invoke("Which city is hotter today and which is bigger: LA or NY?")
print(ai_msg.tool_calls) This code defines two tools, For more advanced use cases, such as creating agents that can interact with multiple tools and handle more complex workflows, you might want to explore the |
Beta Was this translation helpful? Give feedback.
-
Hi @santiagovasquez1 , Facing same issue, can you please let me know how you solved this problem. but my customchatmodel class is not able to recognize presence of any tool. Any thoughts please ? |
Beta Was this translation helpful? Give feedback.
-
Checked other resources
Commit to Help
Example Code
Description
I have a custom BaseChatModel that call a gpt 4.o mini via a rest api via url I need bind tools to it, how can I do that?
System Info
langchain==0.2.14
langchain-cli==0.0.30
langchain-community==0.2.12
langchain-core==0.2.35
langchain-experimental==0.0.64
langchain-openai==0.1.22
langchain-text-splitters==0.2.2
Beta Was this translation helpful? Give feedback.
All reactions