Skip to content

Django Chain Utilities

django_chain.utils

Utility functions and helpers for django-chain.

This package contains utility modules for LLM client instantiation, serialization, and workflow execution.

django_chain.utils.llm_client

LLM client utilities for django-chain.

This module provides functions to instantiate chat and embedding models, serialize LangChain objects, and build workflow chains for LLM-powered Django applications.

Typical usage example

chat_model = create_llm_chat_client("openai", ...) embedding_model = create_llm_embedding_client("openai", ...) chain = create_langchain_workflow_chain([...], {...})

LoggingHandler

Bases: BaseCallbackHandler

Enhanced callback handler for comprehensive LLM interaction logging.

Captures detailed metadata including model information, token usage, performance metrics, and error details.

on_llm_start(serialized, prompts, **kwargs)

Run when LLM starts running.

on_llm_end(response, **kwargs)

Run when LLM ends running.

on_llm_error(error, **kwargs)

Run when LLM errors.

on_chat_model_start(serialized, messages, **kwargs)

Run when a chat model starts running.

create_llm_chat_client(provider, **kwargs)

Get a chat model instance for the specified provider.

Parameters:

  • provider (str) –

    The LLM provider name (e.g., 'openai', 'google')

  • **kwargs

    Additional arguments for the chat model

Returns:

  • BaseChatModel | None

    A configured chat model instance

Raises:

  • ImportError

    If the required provider package is not installed

  • ValueError

    If the provider is not supported

create_llm_embedding_client(provider, **kwargs)

Get an embedding model instance for the specified provider.

Parameters:

  • provider (str) –

    The LLM provider name (e.g., 'openai', 'google')

  • **kwargs

    Additional arguments for the embedding model

Returns:

  • Embeddings | None

    A configured embedding model instance

Raises:

  • ImportError

    If the required provider package is not installed

  • ValueError

    If the provider is not supported

add_wrapper_function(chain, function_name='runnable_with_message_history', **kwargs)

Add a wrapper function to a chain for message history support.

Parameters:

  • chain

    The LangChain chain to wrap

  • function_name

    Name of the wrapper function

  • **kwargs

    Additional arguments for the wrapper

Returns:

  • The wrapped chain