Skip to Content
GuidesAI Integration

AI Integration Guide

Give a Django CFG project LLM access: keys live in DjangoConfig.api_keys, and model calls go through the django_llm module. This is independent of documentation assistance and the Django Admin Overview. For authenticated project tools, see AI and MCP Integration.

Configuration Setup

1. API keys

DjangoConfig.api_keys is an ApiKeys model with two slots, openai and openrouter. The module reads environment variables first (DJANGO_LLM_KEYS__OPENAI, DJANGO_LLM_KEYS__OPENROUTER), then this config, so a deployment can redirect a provider without a release.

# config.py import os from django_cfg import DjangoConfig, ApiKeys class MyProjectConfig(DjangoConfig): api_keys: ApiKeys | None = ApiKeys( openai=os.environ.get("OPENAI_API_KEY"), openrouter=os.environ.get("OPENROUTER_API_KEY"), ) config = MyProjectConfig()

2. Environment

# .env.production OPENAI_API_KEY=sk-... OPENROUTER_API_KEY=sk-or-v1-...

Never commit these. See Environment Configuration.

Using the Client

LLMClient() finds its keys through the module’s single reader, so you pass none in application code.

from django_cfg.modules.django_llm import LLMClient class CustomerSupportAgent: def __init__(self): self.llm = LLMClient() def answer_question(self, question: str, context: dict) -> str: response = self.llm.chat_completion( messages=[ {"role": "system", "content": "You are a helpful support agent."}, {"role": "user", "content": f"Question: {question}\nContext: {context}"}, ], model="openai/gpt-4o-mini", ) return response.content

chat_completion returns a ChatCompletionResponse with content, tokens_used and cost_usd.

Structured output

Pass a Pydantic model as response_format and the module requests strict JSON schema output, then parses and repairs the reply.

from pydantic import BaseModel class Ticket(BaseModel): category: str urgent: bool response = LLMClient().chat_completion( messages=[{"role": "user", "content": "Server is down for all users!"}], model="openai/gpt-4o-mini", response_format=Ticket, )

Production Best Practices

Fail fast on missing keys

import os from django_cfg import DjangoConfig, ApiKeys class ProductionConfig(DjangoConfig): api_keys: ApiKeys | None = ApiKeys( openai=os.environ["OPENAI_API_KEY"], # raises at startup if missing )

Watch spend

Every response carries cost_usd; do not recompute it downstream. The module also has a balance monitor and the check_llm_balance management command; see Cost Tracking and Balance Monitoring.

Testing

Patch the client method so tests never call a provider:

# tests/test_ai_integration.py from unittest.mock import MagicMock, patch from django.test import TestCase class AIIntegrationTest(TestCase): @patch("django_cfg.modules.django_llm.LLMClient.chat_completion") def test_customer_support_agent(self, mock_chat): mock_chat.return_value = MagicMock(content="Test response") agent = CustomerSupportAgent() response = agent.answer_question("How do I reset my password?", context={"user_id": 123}) assert response == "Test response" mock_chat.assert_called_once()

See Also

AI Features & Integration

Configuration & Setup

Background Processing

Production & Deployment

Last updated on