> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lithoblocks.com/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain

> Use LithoBlocks templates from LangChain agents and chains.

Use LithoBlocks with [LangChain](https://python.langchain.com/) so your agent can send Slack messages via templates. The agent chooses a template and payload; a tool calls the LithoBlocks API. You get deterministic messages and far fewer tokens because the LLM does not generate Block Kit JSON. The resulting LLM savings help offset LithoBlocks cost, with net cost reduction at higher volumes.

## Prerequisites

* LithoBlocks API key and at least one template
* [Connecting Slack](/connecting-slack) for your LithoBlocks workspace
* LangChain installed (`pip install langchain langchain-openai` or equivalent)

## Why use LithoBlocks with LangChain

* **Deterministic messages** — The agent picks a template and data; the tool sends it. No Block Kit in the prompt.
* **Lower LLM cost** — The agent outputs only `template_id` and a small payload; the tool does the HTTP call. LLM savings help offset LithoBlocks cost; at higher volumes, net cost reduction.
* **Consistency** — Same layout every time; fewer malformed blocks.

## Implementing the tool

Define a LangChain tool that accepts `template_id` and `payload` (mapped to API field `data`), then POSTs to the LithoBlocks API.

```python theme={null}
import os
from typing import Optional

import requests
from langchain_core.tools import tool

LITHOBLOCKS_API_KEY = os.environ.get("LITHOBLOCKS_API_KEY")
BASE_URL = "https://api.lithoblocks.com"

@tool
def send_slack_message(template_id: str, payload: dict, channel_id: Optional[str] = None) -> str:
    """Send a Slack message using a LithoBlocks template. Use when the user wants to notify someone in Slack.
    template_id: The LithoBlocks template ID (e.g. from your dashboard).
    payload: JSON object matching the template's placeholders (e.g. {"user": {"name": "Alice"}, "message": "Hello"}).
    channel_id: Optional Slack channel ID for send (see API reference for other destinations).
    """
    url = f"{BASE_URL}/v1/templates/send"
    headers = {
        "Authorization": f"Bearer {LITHOBLOCKS_API_KEY}",
        "Content-Type": "application/json",
    }
    body = {"template_id": template_id, "data": payload}
    if channel_id:
        body["channel_id"] = channel_id
    response = requests.post(url, json=body, headers=headers)
    if response.ok:
        return f"Message sent successfully: {response.json().get('message_ts', 'ok')}"
    return f"Failed to send message: {response.status_code} {response.text}"
```

For **compile** (get blocks without sending), POST to `https://api.lithoblocks.com/v1/templates/compile` (or your configured base URL plus `/v1/templates/compile`) with JSON `{"template_id": "...", "data": {...}}` and return the response to the agent or post blocks yourself. See the [API reference](/api-reference/introduction) for request/response shapes.

## Using the tool in an agent

Add the tool to your agent's tools list. The agent can then "send a Slack message" by invoking the tool with `template_id` and `payload`.

```python theme={null}
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [send_slack_message]
prompt = ChatPromptTemplate.from_messages([
    ("system", "You can send Slack messages using the send_slack_message tool when the user asks to notify someone."),
    MessagesPlaceholder(variable_name="chat_history", optional=True),
    ("human", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "Send a Slack message to #general saying the report is ready."})
```

The agent will call `send_slack_message` with the appropriate `template_id` and `payload` for your template.

## Next steps

<CardGroup cols={2}>
  <Card title="AI agents overview" icon="robot" href="/guides/ai-agents-overview">
    Why templates and agents fit together.
  </Card>

  <Card title="API reference" icon="code" href="/api-reference/introduction">
    Endpoints, auth, and parameters.
  </Card>

  <Card title="Placeholders" icon="code" href="/guides/templates-placeholders">
    Template data shape and syntax.
  </Card>
</CardGroup>
