A LangChain tool implementing sequential thinking logic based on MCP.
Project description
LangChain Sequential Thinking Tool
This package provides a LangChain BaseTool implementation based on the sequential thinking pattern, inspired by the Model Context Protocol (MCP) server implementation. It allows language models to structure their problem-solving process into explicit, potentially revisable thought steps.
Features
- Structured Thinking: Guides LLMs to break down problems into numbered thoughts.
- State Management: Tracks thought history and allows for branching/revisions (managed within the tool instance).
- Rich Output: Displays thoughts and recommendations in the console using
richfor better visibility during agent execution. - LangChain Integration: Designed to be used seamlessly within LangChain agents.
- Pydantic Validation: Uses Pydantic for robust input validation.
Installation
pip install langchain-sequential-thinking-tool
Usage
Instantiate the tool and include it in your agent's tool list. The agent's LLM should be prompted to use this tool for complex reasoning tasks, providing the required fields (thought, thought_number, total_thoughts, next_thought_needed) and optional fields (is_revision, current_step, etc.) as needed.
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain_core.prompts import PromptTemplate
from sequential_thinking_tool import SequentialThinkingTool # Assuming package is installed
# 1. Initialize LLM and Tool
llm = ChatOpenAI(model="gpt-4o", temperature=0)
thinking_tool = SequentialThinkingTool()
tools = [thinking_tool]
# 2. Define Agent Prompt (example)
# Ensure your prompt instructs the LLM on HOW and WHEN to use the sequential_thinking_tool
prompt_template = """
Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do. For complex problems, use the sequential_thinking_tool to break down your reasoning step-by-step. Structure your thoughts clearly.
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action, as a dictionary. For sequential_thinking_tool, provide 'thought', 'thought_number', 'total_thoughts', 'next_thought_needed', and optional fields like 'current_step'.
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer.
Final Answer: the final answer to the original input question
Begin!
Question: {input}
{agent_scratchpad}
"""
prompt = PromptTemplate.from_template(prompt_template)
# 3. Create Agent
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# 4. Run the Agent
try:
# Example task requiring sequential thought
task = "Plan the steps to build a simple web server using Python Flask, including setting up the environment, writing basic code, and running it."
result = agent_executor.invoke({"input": task})
print("\nFinal Result:")
print(result.get("output"))
# You can inspect the tool's history after execution
# print("\nTool History:")
# print(json.dumps(thinking_tool.get_history(), indent=2))
except Exception as e:
print(f"An error occurred: {e}")
How it Works
The tool receives a dictionary matching the ThoughtDataInput schema. It validates the input, updates its internal history (stored in the thought_history list within the tool instance), formats the thought using rich, prints it to stderr, and returns a summary dictionary to the agent.
Note: Unlike the original MCP server, this tool does not automatically analyze other available tools. Any tool recommendations within the current_step field must be generated by the LLM itself based on its knowledge or the context provided in the prompt/history.
Development
- Clone the repository.
- Create a virtual environment:
python -m venv .venv - Activate:
source .venv/bin/activate(or.\.venv\Scripts\activateon Windows) - Install dependencies:
pip install -e ".[dev]"(Assuming a[project.optional-dependencies]section for dev tools likepytest,build,twineis added topyproject.toml) - Run tests:
pytest
Publishing to PyPI
This project uses GitHub Actions with OIDC for trusted publishing to the Python Package Index (PyPI).
The publishing process is defined in the .github/workflows/publish-to-pypi.yml workflow file. Creating a new GitHub release will automatically trigger this workflow, building the package and uploading it to PyPI.
For more details on how trusted publishing works, refer to the PyPI documentation on trusted publishers.
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file langchain_sequential_thinking_tool-0.1.0.tar.gz.
File metadata
- Download URL: langchain_sequential_thinking_tool-0.1.0.tar.gz
- Upload date:
- Size: 10.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
89d25cb058c87a4c6c326c800e34019b7ee4852f44f088efa2a29b750e7f9452
|
|
| MD5 |
e0fe95c9204922e872e2142aab357a9e
|
|
| BLAKE2b-256 |
ee54de6ad8fba31e5777c37245c843bf86ada62f6047d74b1d3f749231796738
|
Provenance
The following attestation bundles were made for langchain_sequential_thinking_tool-0.1.0.tar.gz:
Publisher:
publish-to-pypi.yml on cognitive-glitch/langchain-sequential-thinking-tool
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
langchain_sequential_thinking_tool-0.1.0.tar.gz -
Subject digest:
89d25cb058c87a4c6c326c800e34019b7ee4852f44f088efa2a29b750e7f9452 - Sigstore transparency entry: 206543476
- Sigstore integration time:
-
Permalink:
cognitive-glitch/langchain-sequential-thinking-tool@244a070cd65bfacc9a10f5664a57f166699091f6 -
Branch / Tag:
refs/tags/release - Owner: https://github.com/cognitive-glitch
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-to-pypi.yml@244a070cd65bfacc9a10f5664a57f166699091f6 -
Trigger Event:
release
-
Statement type:
File details
Details for the file langchain_sequential_thinking_tool-0.1.0-py3-none-any.whl.
File metadata
- Download URL: langchain_sequential_thinking_tool-0.1.0-py3-none-any.whl
- Upload date:
- Size: 11.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
459e9875596aa4d4e9d49658a80816109546bfd1b06de1b5b3e290181cd869d8
|
|
| MD5 |
3e6eb569537fc404e03846dce12b7c16
|
|
| BLAKE2b-256 |
d4f4ccdd10314679b7e6a4046aaf02cfe4e0831e1fe61532e5db0d2250bc3cc0
|
Provenance
The following attestation bundles were made for langchain_sequential_thinking_tool-0.1.0-py3-none-any.whl:
Publisher:
publish-to-pypi.yml on cognitive-glitch/langchain-sequential-thinking-tool
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
langchain_sequential_thinking_tool-0.1.0-py3-none-any.whl -
Subject digest:
459e9875596aa4d4e9d49658a80816109546bfd1b06de1b5b3e290181cd869d8 - Sigstore transparency entry: 206543477
- Sigstore integration time:
-
Permalink:
cognitive-glitch/langchain-sequential-thinking-tool@244a070cd65bfacc9a10f5664a57f166699091f6 -
Branch / Tag:
refs/tags/release - Owner: https://github.com/cognitive-glitch
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-to-pypi.yml@244a070cd65bfacc9a10f5664a57f166699091f6 -
Trigger Event:
release
-
Statement type: