Skip to main content

LangChain integration for APE (AI Programmatic Execution)

Project description

ape-langchain

LangChain integration for APE (AI Programmatic Execution).

What is ape-langchain?

ape-langchain provides seamless integration between APE's deterministic functions and LangChain's agent framework. Convert APE tasks into LangChain tools with automatic validation and type safety.

Why ape-langchain?

LangChain agents are powerful but need reliable tools:

  • Tool parameters must be validated
  • Type safety prevents runtime errors
  • Deterministic execution ensures consistency
  • Clear contracts between agent and tools

ape-langchain solves this by wrapping APE functions as LangChain tools:

LangChain Agent → APE Tool → Validation → Deterministic execution ✓

Installation

# Core package
pip install ape-langchain

# With LangChain
pip install ape-langchain[langchain]

# Development dependencies
pip install ape-langchain[dev]

Prerequisites:

  • Python >= 3.11
  • ape-lang >= 0.2.0

Test Coverage

Tests: 17 passing, 3 skipped

  • Total tests: 20 (17 passing + 3 documented skips)
  • Last verified via pytest discovery

See ../ape/docs/APE_TESTING_GUARANTEES.md for details on what these tests guarantee.

The test suite covers:

  • Schema conversion (APE → LangChain)
  • Utils (result formatting, input validation)

Skipped tests (documented with reasons):

  • End-to-end integration (API difference: file-based vs task-based)
  • Executor (API difference documented)
  • Generator (needs implementation verification)

To verify test counts:

pytest packages/ape-langchain/tests --collect-only -q

Quick Start

from langchain.llms import OpenAI
from ape_langchain import create_langchain_tool

# 1. Create Ape task file
# calculator.ape:
# task add:
#     inputs: a: Integer, b: Integer
#     outputs: sum: Integer
#     constraints: deterministic
#     steps: sum = a + b

# 2. Create LangChain tool
tool = create_langchain_tool("calculator.ape", "add")

# 3. Use with LangChain
from langchain.agents import initialize_agent, AgentType

llm = OpenAI(temperature=0)
agent = initialize_agent(
    tools=[tool],
    llm=llm,
    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

# 4. Run agent
result = agent.run("Add 5 and 3")
print(result)  # "The sum of 5 and 3 is 8"

API Reference

Schema Conversion

ape_task_to_langchain_schema(task: ApeTask) -> dict

Converts APE task to LangChain tool schema.

from ape_langchain import ape_task_to_langchain_schema, ApeTask

task = ApeTask(
    name="calculate_tax",
    inputs={"amount": "float", "rate": "float"},
    output="float",
    description="Calculate tax amount"
)

schema = ape_task_to_langchain_schema(task)

Tool Creation

create_langchain_tool(ape_file, function_name) -> StructuredTool

Create a LangChain StructuredTool from an Ape file.

from ape_langchain import create_langchain_tool

tool = create_langchain_tool("math_ops.ape", "multiply")

# Use in agent
result = tool.run({"a": 4, "b": 7})

Tool Wrapper

ApeLangChainTool

Low-level wrapper for more control.

from ape_langchain import ApeLangChainTool

ape_tool = ApeLangChainTool.from_ape_file("calc.ape", "divide")
langchain_tool = ape_tool.as_structured_tool()

# Execute directly
result = ape_tool.execute(a=10, b=2)

Chain Creation

create_ape_chain(ape_file, llm) -> AgentExecutor

Create a complete LangChain agent with all functions from an Ape file.

from ape_langchain import create_ape_chain
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)
chain = create_ape_chain("calculator.ape", llm=llm)

result = chain.run("Calculate 15 * 8 and then add 42")

Features

  • StructuredTool integration: Full LangChain tool support
  • Automatic validation: Type and constraint checking
  • Pydantic schemas: Generated from APE types
  • Multi-tool agents: Load entire APE modules as tools
  • Error handling: Clear error propagation
  • Type mapping: APE types → Python types → Pydantic

Type Mapping

Ape Type Python Type LangChain Schema
String str string
Integer int integer
Float float number
Boolean bool boolean
List list array
Dict dict object

Advanced Usage

Multiple Tools

from ape_langchain import ApeLangChainTool
from langchain.agents import initialize_agent, AgentType
from langchain.llms import OpenAI

# Load multiple functions
add_tool = create_langchain_tool("calc.ape", "add")
multiply_tool = create_langchain_tool("calc.ape", "multiply")
divide_tool = create_langchain_tool("calc.ape", "divide")

# Create agent
llm = OpenAI(temperature=0)
agent = initialize_agent(
    tools=[add_tool, multiply_tool, divide_tool],
    llm=llm,
    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION
)

result = agent.run("Calculate (5 + 3) * 2 / 4")

Custom Descriptions

tool = create_langchain_tool(
    "calc.ape",
    "add",
    description="Adds two numbers together with validation"
)

With Memory

from langchain.memory import ConversationBufferMemory
from langchain.agents import initialize_agent

memory = ConversationBufferMemory(memory_key="chat_history")
agent = initialize_agent(
    tools=[tool],
    llm=llm,
    agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
    memory=memory
)

Examples

Basic Calculator Agent

# calculator.ape
task add:
    inputs:
        a: Integer
        b: Integer
    outputs:
        result: Integer
    constraints:
        - deterministic
    steps:
        - result = a + b

task multiply:
    inputs:
        a: Integer
        b: Integer
    outputs:
        result: Integer
    constraints:
        - deterministic
    steps:
        - result = a * b
# agent.py
from ape_langchain import create_ape_chain
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)
agent = create_ape_chain("calculator.ape", llm=llm)

agent.run("What is 7 times 8, then add 15?")
# Agent uses multiply(7, 8) → 56, then add(56, 15) → 71

Development

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black .

# Type checking
mypy src/

License

MIT License - see LICENSE file for details.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ape_langchain-1.0.6.tar.gz (12.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ape_langchain-1.0.6-py3-none-any.whl (9.6 kB view details)

Uploaded Python 3

File details

Details for the file ape_langchain-1.0.6.tar.gz.

File metadata

  • Download URL: ape_langchain-1.0.6.tar.gz
  • Upload date:
  • Size: 12.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for ape_langchain-1.0.6.tar.gz
Algorithm Hash digest
SHA256 be9cb98c1d1ae94abc4bbcc445ec9930bf79c2c70a5cd36bedfe9e788a4669fb
MD5 51262c9598899f1961128f8ca1e41d8f
BLAKE2b-256 a388833c37ff668d95ed94e5f8a363c2f388917bca3f50c165ff835dc0951db5

See more details on using hashes here.

File details

Details for the file ape_langchain-1.0.6-py3-none-any.whl.

File metadata

  • Download URL: ape_langchain-1.0.6-py3-none-any.whl
  • Upload date:
  • Size: 9.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for ape_langchain-1.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 dc6b625074511d6b1893884400ae0df72cd64e0ca2b7725ad3f571800a7d9ea7
MD5 081c2d42e97e5e8b025fe96fbc34bfc7
BLAKE2b-256 fe0d801d3b9d4e7bf655de8462d5175a4c8d8f9a03bcbf9651ed8a52ce2c61dc

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page