Skip to content

Instantly share code, notes, and snippets.

@unicolet
Created June 29, 2025 06:51
Show Gist options
  • Save unicolet/ca9e08675f38a70614df0ab50ff7ced9 to your computer and use it in GitHub Desktop.
Save unicolet/ca9e08675f38a70614df0ab50ff7ced9 to your computer and use it in GitHub Desktop.
from langchain_core.prompts import ChatPromptTemplate
from langchain_anthropic import ChatAnthropic # or langchain_openai.ChatOpenAI
from langchain_core.tools import tool
from langchain_core.pydantic_v1 import BaseModel
# Define a tool using the @tool decorator
@tool
def multiply(x: int, y: int) -> int:
"""Multiply two integers."""
return x * y
# Define output schema
class OutputSchema(BaseModel):
result: int
# Create prompt template
prompt = ChatPromptTemplate.from_messages([
("system", "You can use tools to help answer questions."),
("user", "{input}")
])
# Initialize LLM and bind tools
llm = ChatAnthropic(api_key="YOUR_KEY", model="claude-3-5-sonnet-20240620")
llm_with_tools = llm.bind_tools([multiply])
# Enable structured output
structured_llm = llm_with_tools.with_structured_output(OutputSchema, include_raw=True)
# Compose the chain
chain = prompt | structured_llm
# Run the chain
result = chain.invoke({"input": "What is 6 times 7?"})
print(result["parsed"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment