Intégration CI LangChain

VérifiéSûr

Configurez l'intégration CI/CD pour LangChain avec GitHub Actions et les tests. Utilisez pour mettre en place des pipelines automatisés.

Spar Skills Guide Bot
DevOpsIntermédiaire
25/07/2026
Claude Code
#langchain#github-actions#ci-cd#pytest#automation

Recommandé pour

Synthèse automatique

Configure une intégration CI/CD GitHub Actions pour les applications LangChain, avec linting, vérification de types, tests unitaires et tests d'intégration.

Points forts

  • Fournit un workflow GitHub Actions complet prêt à l'emploi avec jobs lint, tests unitaires et tests d'intégration
  • Sépare clairement les tests unitaires (sans appels API) des tests d'intégration nécessitant des clés, limités à la branche main
  • Inclut des fixtures de mock pour LLM et chaînes LangChain, ainsi qu'une configuration des markers pytest
  • Ajoute des hooks pre-commit Ruff et mypy pour la qualité de code en local

Limites

  • Le workflow est spécifique à GitHub Actions et à Python, sans variante pour GitLab CI ou d'autres langages
  • Les fixtures de mock restent minimales et ne couvrent pas les cas avancés comme les tools, retrievers ou streaming
  • Suppose une structure de projet particulière (tests/unit, tests/integration, src/) non adaptée automatiquement
Quand l'utiliser

Utilisez ce skill lorsque vous devez mettre en place ou automatiser un pipeline CI pour une application LangChain basée sur Python hébergée sur GitHub.

Quand l'éviter

Évitez ce skill si votre projet n'utilise pas GitHub Actions, n'est pas écrit en Python, ou si vous cherchez uniquement des stratégies de test sans configuration d'intégration continue.

Analyse de sécurité

Sûr
Score qualité85/100

The skill only produces standard GitHub Actions workflow YAML, pytest configuration, mock fixtures, and pre-commit hooks. Secrets are referenced correctly via GitHub Secrets (secrets.OPENAI_API_KEY) and the integration example uses a placeholder key. There is no curl|sh, no destructive commands, no obfuscated payloads, and no exfiltration of tokens. The Bash(gh:*) permission and Write/Edit access are used for legitimate CI configuration tasks, so overall execution risk is low.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Add CI pipeline
Set up a GitHub Actions CI pipeline for my LangChain app with lint, unit tests and integration tests.
LangChain test markers
Configure pytest markers and mock LLM fixtures so my LangChain tests run without hitting the API.
Pre-commit hooks
Add pre-commit hooks with Ruff and mypy to my LangChain repository.

name: langchain-ci-integration description: | Configure LangChain CI/CD integration with GitHub Actions and testing. Use when setting up automated testing, configuring CI pipelines, or integrating LangChain tests into your build process. Trigger with phrases like "langchain CI", "langchain GitHub Actions", "langchain automated tests", "CI langchain", "langchain pipeline". allowed-tools: Read, Write, Edit, Bash(gh:*) version: 1.0.0 license: MIT author: Jeremy Longshore jeremy@intentsolutions.io

LangChain CI Integration

Overview

Configure comprehensive CI/CD pipelines for LangChain applications with testing, linting, and deployment automation.

Prerequisites

  • GitHub repository with Actions enabled
  • LangChain application with test suite
  • API keys for testing (stored as GitHub Secrets)

Instructions

Step 1: Create GitHub Actions Workflow

# .github/workflows/langchain-ci.yml
name: LangChain CI

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

env:
  PYTHON_VERSION: "3.11"

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: ${{ env.PYTHON_VERSION }}

      - name: Install dependencies
        run: |
          pip install ruff mypy

      - name: Lint with Ruff
        run: ruff check .

      - name: Type check with mypy
        run: mypy src/

  test-unit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: ${{ env.PYTHON_VERSION }}

      - name: Install dependencies
        run: |
          pip install -e ".[dev]"

      - name: Run unit tests
        run: |
          pytest tests/unit -v --cov=src --cov-report=xml

      - name: Upload coverage
        uses: codecov/codecov-action@v4
        with:
          files: coverage.xml

  test-integration:
    runs-on: ubuntu-latest
    needs: [lint, test-unit]
    # Only run on main branch or manual trigger
    if: github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch'
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: ${{ env.PYTHON_VERSION }}

      - name: Install dependencies
        run: |
          pip install -e ".[dev]"

      - name: Run integration tests
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          pytest tests/integration -v -m integration

Step 2: Configure Test Markers

# pyproject.toml
[tool.pytest.ini_options]
markers = [
    "unit: Unit tests (no external API calls)",
    "integration: Integration tests (requires API keys)",
    "slow: Slow tests (skip in fast mode)",
]
asyncio_mode = "auto"
testpaths = ["tests"]

Step 3: Create Mock Fixtures

# tests/conftest.py
import pytest
from unittest.mock import MagicMock, AsyncMock
from langchain_core.messages import AIMessage

@pytest.fixture
def mock_llm():
    """Mock LLM for unit tests."""
    mock = MagicMock()
    mock.invoke.return_value = AIMessage(content="Mock response")
    mock.ainvoke = AsyncMock(return_value=AIMessage(content="Mock response"))
    return mock

@pytest.fixture
def mock_chain(mock_llm):
    """Mock chain for testing."""
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.output_parsers import StrOutputParser

    prompt = ChatPromptTemplate.from_template("{input}")
    return prompt | mock_llm | StrOutputParser()

Step 4: Add Pre-commit Hooks

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.6
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.7.1
    hooks:
      - id: mypy
        additional_dependencies:
          - langchain-core
          - pydantic

Step 5: Add Deployment Stage

# Add to .github/workflows/langchain-ci.yml
  deploy:
    runs-on: ubuntu-latest
    needs: [test-integration]
    if: github.ref == 'refs/heads/main'
    environment: production
    steps:
      - uses: actions/checkout@v4

      - name: Deploy to Cloud Run
        uses: google-github-actions/deploy-cloudrun@v2
        with:
          service: langchain-api
          source: .
          env_vars: |
            LANGCHAIN_PROJECT=production

Output

  • GitHub Actions workflow with lint, test, deploy stages
  • pytest configuration with markers
  • Mock fixtures for unit testing
  • Pre-commit hooks for code quality

Examples

Running Tests Locally

# Run unit tests only (fast)
pytest tests/unit -v

# Run with coverage
pytest tests/unit --cov=src --cov-report=html

# Run integration tests (requires API key)
OPENAI_API_KEY=sk-... pytest tests/integration -v -m integration

# Skip slow tests
pytest tests/ -v -m "not slow"

Integration Test Example

# tests/integration/test_chain.py
import pytest
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate

@pytest.mark.integration
def test_real_chain_invocation():
    """Test with real LLM (requires API key)."""
    llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
    prompt = ChatPromptTemplate.from_template("Say exactly: {word}")
    chain = prompt | llm

    result = chain.invoke({"word": "hello"})
    assert "hello" in result.content.lower()

Error Handling

| Error | Cause | Solution | |-------|-------|----------| | Secret Not Found | Missing GitHub secret | Add OPENAI_API_KEY to repository secrets | | Rate Limit in CI | Too many API calls | Use mocks for unit tests, limit integration tests | | Timeout | Slow tests | Add timeout markers, parallelize tests | | Import Error | Missing dev dependencies | Ensure .[dev] extras installed |

Resources

Next Steps

Proceed to langchain-deploy-integration for deployment configuration.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/langchain-ci-integration-mrzxur1b/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/langchain-ci-integration-mrzxur1b' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/langchain-ci-integration-mrzxur1b/download' --output '.skill-downloads/langchain-ci-integration-mrzxur1b/SKILL.md.part' && mv '.skill-downloads/langchain-ci-integration-mrzxur1b/SKILL.md.part' '.skill-downloads/langchain-ci-integration-mrzxur1b/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Write, Edit, Bash(gh:*)

Extrait original : Prerequisites
  • GitHub repository with Actions enabled
  • LangChain application with test suite
  • API keys for testing (stored as GitHub Secrets)

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/langchain-ci-integration-mrzxur1b/SKILL.md' && test -s '.skill-downloads/langchain-ci-integration-mrzxur1b/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/langchain-ci-integration' && cp -R '.skill-downloads/langchain-ci-integration-mrzxur1b' '.claude/skills/langchain-ci-integration'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/langchain-ci-integration-mrzxur1b'

openskills read 'langchain-ci-integration-mrzxur1b'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/langchain-ci-integration-mrzxur1b/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires