drf-to-mkdoc 0.2.0__py3-none-any.whl → 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of drf-to-mkdoc might be problematic. Click here for more details.

Files changed (33) hide show
  1. drf_to_mkdoc/conf/defaults.py +5 -0
  2. drf_to_mkdoc/conf/settings.py +123 -9
  3. drf_to_mkdoc/management/commands/build_docs.py +8 -7
  4. drf_to_mkdoc/management/commands/build_endpoint_docs.py +69 -0
  5. drf_to_mkdoc/management/commands/build_model_docs.py +50 -0
  6. drf_to_mkdoc/management/commands/{generate_model_docs.py → extract_model_data.py} +14 -19
  7. drf_to_mkdoc/utils/ai_tools/__init__.py +0 -0
  8. drf_to_mkdoc/utils/ai_tools/enums.py +13 -0
  9. drf_to_mkdoc/utils/ai_tools/exceptions.py +19 -0
  10. drf_to_mkdoc/utils/ai_tools/providers/__init__.py +0 -0
  11. drf_to_mkdoc/utils/ai_tools/providers/base_provider.py +123 -0
  12. drf_to_mkdoc/utils/ai_tools/providers/gemini_provider.py +80 -0
  13. drf_to_mkdoc/utils/ai_tools/types.py +81 -0
  14. drf_to_mkdoc/utils/commons/__init__.py +0 -0
  15. drf_to_mkdoc/utils/commons/code_extractor.py +22 -0
  16. drf_to_mkdoc/utils/commons/file_utils.py +35 -0
  17. drf_to_mkdoc/utils/commons/model_utils.py +83 -0
  18. drf_to_mkdoc/utils/commons/operation_utils.py +83 -0
  19. drf_to_mkdoc/utils/commons/path_utils.py +78 -0
  20. drf_to_mkdoc/utils/commons/schema_utils.py +230 -0
  21. drf_to_mkdoc/utils/endpoint_detail_generator.py +7 -34
  22. drf_to_mkdoc/utils/endpoint_list_generator.py +1 -1
  23. drf_to_mkdoc/utils/extractors/query_parameter_extractors.py +33 -30
  24. drf_to_mkdoc/utils/model_detail_generator.py +21 -15
  25. drf_to_mkdoc/utils/model_list_generator.py +25 -15
  26. drf_to_mkdoc/utils/schema.py +259 -0
  27. {drf_to_mkdoc-0.2.0.dist-info → drf_to_mkdoc-0.2.1.dist-info}/METADATA +16 -5
  28. {drf_to_mkdoc-0.2.0.dist-info → drf_to_mkdoc-0.2.1.dist-info}/RECORD +31 -16
  29. drf_to_mkdoc/management/commands/generate_docs.py +0 -113
  30. drf_to_mkdoc/utils/common.py +0 -353
  31. {drf_to_mkdoc-0.2.0.dist-info → drf_to_mkdoc-0.2.1.dist-info}/WHEEL +0 -0
  32. {drf_to_mkdoc-0.2.0.dist-info → drf_to_mkdoc-0.2.1.dist-info}/licenses/LICENSE +0 -0
  33. {drf_to_mkdoc-0.2.0.dist-info → drf_to_mkdoc-0.2.1.dist-info}/top_level.txt +0 -0
@@ -7,6 +7,11 @@ DEFAULTS = {
7
7
  "CUSTOM_SCHEMA_FILE": "docs/configs/custom_schema.json", # Path to custom schema file
8
8
  "PATH_PARAM_SUBSTITUTE_FUNCTION": None,
9
9
  "PATH_PARAM_SUBSTITUTE_MAPPING": {},
10
+ # AI documentation settings
11
+ "ENABLE_AI_DOCS": False,
12
+ "AI_CONFIG_DIR_NAME": "ai_code", # Directory name for AI-generated code files
13
+ "AI_OPERATION_MAP_FILE": "docs/configs/operation_map.json", # Path to operation map file
14
+ "SERIALIZERS_INHERITANCE_DEPTH": 1, # Maximum depth for class inheritance analysis
10
15
  # Django apps - required, no default
11
16
  "DJANGO_APPS": None, # List of Django app names to process
12
17
  }
@@ -1,31 +1,145 @@
1
+ from pathlib import Path
2
+ from typing import Any, ClassVar
3
+
1
4
  from django.conf import settings
2
5
 
3
6
  from drf_to_mkdoc.conf.defaults import DEFAULTS
4
7
 
5
8
 
6
9
  class DRFToMkDocSettings:
7
- required_settings = ["DJANGO_APPS"]
8
- project_settings = {"PROJECT_NAME": "drf-to-mkdoc"}
10
+ required_settings: ClassVar[list[str]] = ["DJANGO_APPS"]
11
+ project_settings: ClassVar[dict[str, Any]] = {"PROJECT_NAME": "drf-to-mkdoc"}
12
+
13
+ settings_types: ClassVar[dict[str, type]] = {
14
+ "ENABLE_AI_DOCS": bool,
15
+ "AI_CONFIG_DIR_NAME": str,
16
+ "SERIALIZERS_INHERITANCE_DEPTH": int,
17
+ }
18
+
19
+ settings_ranges: ClassVar[dict[str, tuple[int, int]]] = {
20
+ "SERIALIZERS_INHERITANCE_DEPTH": (1, 3),
21
+ }
22
+
23
+ path_settings = {
24
+ "CONFIG_DIR",
25
+ "MODEL_DOCS_FILE",
26
+ "DOC_CONFIG_FILE",
27
+ "CUSTOM_SCHEMA_FILE",
28
+ "AI_OPERATION_MAP_FILE",
29
+ }
9
30
 
10
31
  def __init__(self, user_settings_key="DRF_TO_MKDOC", defaults=None):
11
32
  self.user_settings_key = user_settings_key
12
33
  self._user_settings = getattr(settings, user_settings_key, {})
13
34
  self.defaults = defaults or {}
14
35
 
15
- def get(self, key):
16
- if key not in self.defaults:
17
- if key in self.project_settings:
18
- return self.project_settings[key]
19
- raise AttributeError(f"Invalid DRF_TO_MKDOC setting: '{key}'")
36
+ def _validate_type(self, key: str, value: Any) -> None:
37
+ """Validate the type of setting value."""
38
+ if key in self.settings_types:
39
+ expected_type = self.settings_types[key]
40
+ if not isinstance(value, expected_type):
41
+ raise TypeError(
42
+ f"DRF_TO_MKDOC setting '{key}' must be of type {expected_type.__name__}, "
43
+ f"got {type(value).__name__} instead."
44
+ )
20
45
 
21
- value = self._user_settings.get(key, self.defaults[key])
46
+ def _validate_range(self, key: str, value: Any) -> None:
47
+ """Validate the range of a setting value."""
48
+ if key in self.settings_ranges:
49
+ min_val, max_val = self.settings_ranges[key]
50
+ if not min_val <= value <= max_val:
51
+ raise ValueError(
52
+ f"DRF_TO_MKDOC setting '{key}' must be between {min_val} and {max_val}, "
53
+ f"got {value} instead."
54
+ )
22
55
 
56
+ def _validate_required(self, key: str, value: Any) -> None:
57
+ """Validate if a required setting is configured."""
23
58
  if value is None and key in self.required_settings:
24
59
  raise ValueError(
25
60
  f"DRF_TO_MKDOC setting '{key}' is required but not configured. "
26
61
  f"Please add it to your Django settings under {self.user_settings_key}."
27
62
  )
28
63
 
64
+ def _validate_dir(self, key: str, value: str) -> None:
65
+ if key not in self.path_settings or not isinstance(value, str):
66
+ return
67
+
68
+ if not value.strip():
69
+ raise ValueError(
70
+ f"DRF_TO_MKDOC path setting '{key}' cannot be empty or contain only whitespace."
71
+ )
72
+
73
+ dangerous_components = {"..", "~", "/", "\\"}
74
+ path_parts = Path(value).parts
75
+ for part in path_parts:
76
+ if part in dangerous_components or part.startswith("."):
77
+ raise ValueError(
78
+ f"DRF_TO_MKDOC path setting '{key}' contains unsafe path component '{part}'. "
79
+ f"Directory names should be simple names without separators or relative path components."
80
+ )
81
+
82
+ if Path(value).is_absolute():
83
+ raise ValueError(
84
+ f"DRF_TO_MKDOC path setting '{key}' cannot be an absolute path. "
85
+ f"Use relative directory names only."
86
+ )
87
+
88
+ reserved_names = {
89
+ "CON",
90
+ "PRN",
91
+ "AUX",
92
+ "NUL",
93
+ "COM1",
94
+ "COM2",
95
+ "COM3",
96
+ "COM4",
97
+ "COM5",
98
+ "COM6",
99
+ "COM7",
100
+ "COM8",
101
+ "COM9",
102
+ "LPT1",
103
+ "LPT2",
104
+ "LPT3",
105
+ "LPT4",
106
+ "LPT5",
107
+ "LPT6",
108
+ "LPT7",
109
+ "LPT8",
110
+ "LPT9",
111
+ }
112
+ if value.upper() in reserved_names:
113
+ raise ValueError(
114
+ f"DRF_TO_MKDOC path setting '{key}' uses a reserved system name '{value}'. "
115
+ f"Please choose a different name."
116
+ )
117
+
118
+ invalid_chars = '<>:"|?*'
119
+ if any(char in value for char in invalid_chars):
120
+ raise ValueError(
121
+ f"DRF_TO_MKDOC path setting '{key}' contains invalid characters. "
122
+ f"Avoid using: {invalid_chars}"
123
+ )
124
+
125
+ def get(self, key):
126
+ if key in self.project_settings:
127
+ return self.project_settings[key]
128
+
129
+ # User-provided settings take precedence
130
+ if key in self._user_settings:
131
+ value = self._user_settings[key]
132
+ else:
133
+ value = self.defaults.get(key, None)
134
+
135
+ # Run all validations
136
+ self._validate_required(key, value)
137
+ self._validate_type(key, value)
138
+ self._validate_range(key, value)
139
+ self._validate_dir(key, value)
140
+
141
+ if value is None:
142
+ raise AttributeError(f"Invalid DRF_TO_MKDOC setting: '{key}'")
29
143
  return value
30
144
 
31
145
  def __getattr__(self, key):
@@ -37,7 +151,7 @@ class DRFToMkDocSettings:
37
151
  for setting in self.required_settings:
38
152
  try:
39
153
  self.get(setting)
40
- except ValueError:
154
+ except (ValueError, AttributeError):
41
155
  missing_settings.append(setting)
42
156
 
43
157
  if missing_settings:
@@ -34,15 +34,16 @@ class Command(BaseCommand):
34
34
  )
35
35
 
36
36
  try:
37
- # Generate the model documentation JSON first
38
- self.stdout.write("Generating model documentation...")
39
- call_command("generate_model_docs", "--pretty")
40
- self.stdout.write(self.style.SUCCESS("Model documentation generated."))
37
+ # Extract model data from Django models
38
+ self.stdout.write("Extracting model data...")
39
+ call_command("extract_model_data", "--pretty")
40
+ self.stdout.write(self.style.SUCCESS("Model data extracted."))
41
41
 
42
42
  # Generate the documentation content
43
- self.stdout.write("Generating documentation content...")
44
- call_command("generate_docs")
45
- self.stdout.write(self.style.SUCCESS("Documentation content generated."))
43
+ self.stdout.write("Building documentation content...")
44
+ call_command("build_model_docs")
45
+ call_command("build_endpoint_docs")
46
+ self.stdout.write(self.style.SUCCESS("Documentation content built."))
46
47
 
47
48
  # Build the MkDocs site
48
49
  self.stdout.write("Building MkDocs site...")
@@ -0,0 +1,69 @@
1
+ from pathlib import Path
2
+
3
+ from django.core.management.base import BaseCommand
4
+
5
+ from drf_to_mkdoc.conf.settings import drf_to_mkdoc_settings
6
+ from drf_to_mkdoc.utils.commons.schema_utils import get_schema
7
+ from drf_to_mkdoc.utils.endpoint_detail_generator import (
8
+ generate_endpoint_files,
9
+ parse_endpoints_from_schema,
10
+ )
11
+ from drf_to_mkdoc.utils.endpoint_list_generator import create_endpoints_index
12
+
13
+
14
+ class Command(BaseCommand):
15
+ help = "Build endpoint documentation from OpenAPI schema"
16
+
17
+ def handle(self, *args, **options):
18
+ self.stdout.write(
19
+ self.style.SUCCESS("🚀 Starting endpoint documentation generation...")
20
+ )
21
+
22
+ docs_dir = self._setup_docs_directory()
23
+ schema_data = self._load_schema_data()
24
+
25
+ if schema_data:
26
+ self._generate_endpoints_documentation(schema_data, docs_dir)
27
+ self.stdout.write(
28
+ self.style.SUCCESS("✅ Endpoint documentation generation complete!")
29
+ )
30
+ else:
31
+ self.stdout.write(self.style.ERROR("❌ Failed to generate endpoint documentation."))
32
+
33
+ def _setup_docs_directory(self):
34
+ docs_dir = Path(drf_to_mkdoc_settings.DOCS_DIR)
35
+ docs_dir.mkdir(parents=True, exist_ok=True)
36
+ return docs_dir
37
+
38
+ def _load_schema_data(self):
39
+ try:
40
+ schema = get_schema()
41
+ except Exception as e:
42
+ self.stdout.write(self.style.ERROR(f"❌ Failed to load OpenAPI schema: {e}"))
43
+ return {}
44
+ if not schema:
45
+ self.stdout.write(self.style.ERROR("❌ Failed to load OpenAPI schema"))
46
+ return {}
47
+
48
+ paths = schema.get("paths", {})
49
+ components = schema.get("components", {})
50
+
51
+ self.stdout.write(f"📊 Loaded {len(paths)} API paths")
52
+
53
+ return {"paths": paths, "components": components}
54
+
55
+ def _generate_endpoints_documentation(self, schema_data, docs_dir):
56
+ self.stdout.write("🔗 Generating endpoint documentation...")
57
+
58
+ paths = schema_data["paths"]
59
+ components = schema_data["components"]
60
+
61
+ endpoints_by_app = parse_endpoints_from_schema(paths)
62
+ total_endpoints = generate_endpoint_files(endpoints_by_app, components)
63
+ create_endpoints_index(endpoints_by_app, docs_dir)
64
+
65
+ self.stdout.write(
66
+ self.style.SUCCESS(
67
+ f"✅ Generated {total_endpoints} endpoint files with Django view introspection"
68
+ )
69
+ )
@@ -0,0 +1,50 @@
1
+ from pathlib import Path
2
+
3
+ from django.core.management.base import BaseCommand
4
+
5
+ from drf_to_mkdoc.conf.settings import drf_to_mkdoc_settings
6
+ from drf_to_mkdoc.utils.commons.file_utils import load_json_data
7
+ from drf_to_mkdoc.utils.model_detail_generator import generate_model_docs
8
+ from drf_to_mkdoc.utils.model_list_generator import create_models_index
9
+
10
+
11
+ class Command(BaseCommand):
12
+ help = "Build model documentation from model JSON data"
13
+
14
+ def handle(self, *args, **options):
15
+ self.stdout.write(self.style.SUCCESS("🚀 Starting model documentation generation..."))
16
+
17
+ docs_dir = self._setup_docs_directory()
18
+ models_data = self._load_models_data()
19
+
20
+ if models_data:
21
+ self._generate_models_documentation(models_data, docs_dir)
22
+ self.stdout.write(self.style.SUCCESS("✅ Model documentation generation complete!"))
23
+ else:
24
+ self.stdout.write(self.style.ERROR("❌ Failed to generate model documentation."))
25
+
26
+ def _setup_docs_directory(self):
27
+ docs_dir = Path(drf_to_mkdoc_settings.DOCS_DIR)
28
+ docs_dir.mkdir(parents=True, exist_ok=True)
29
+ return docs_dir
30
+
31
+ def _load_models_data(self):
32
+ models_data = load_json_data(
33
+ drf_to_mkdoc_settings.MODEL_DOCS_FILE, raise_not_found=False
34
+ )
35
+
36
+ if not models_data:
37
+ self.stdout.write(self.style.WARNING("⚠️ No model data found"))
38
+
39
+ return models_data
40
+
41
+ def _generate_models_documentation(self, models_data, docs_dir):
42
+ self.stdout.write("📋 Generating model documentation...")
43
+
44
+ try:
45
+ generate_model_docs(models_data)
46
+ create_models_index(models_data, docs_dir)
47
+ self.stdout.write(self.style.SUCCESS("✅ Model documentation generated"))
48
+ except Exception as e:
49
+ self.stdout.write(self.style.WARNING(f"⚠️ Failed to generate model docs: {e}"))
50
+ raise
@@ -1,6 +1,7 @@
1
1
  import inspect
2
2
  import json
3
3
  import re
4
+ from collections import defaultdict
4
5
  from pathlib import Path
5
6
 
6
7
  from django.apps import apps
@@ -11,7 +12,7 @@ from drf_to_mkdoc.conf.settings import drf_to_mkdoc_settings
11
12
 
12
13
 
13
14
  class Command(BaseCommand):
14
- help = "Generate model documentation JSON from Django model introspection"
15
+ help = "Extract model data from Django model introspection and save as JSON"
15
16
 
16
17
  def add_arguments(self, parser):
17
18
  parser.add_argument(
@@ -38,33 +39,26 @@ class Command(BaseCommand):
38
39
 
39
40
  model_docs = self.generate_model_documentation(exclude_apps)
40
41
 
41
- json_data = {
42
- "models": model_docs,
43
- "stats": {
44
- "total_models": len(model_docs),
45
- "total_apps": len({model["app_label"] for model in model_docs.values()}),
46
- },
47
- }
48
-
49
42
  output_path = Path(output_file)
50
43
  output_path.parent.mkdir(parents=True, exist_ok=True)
51
44
  with output_path.open("w", encoding="utf-8") as f:
45
+ payload = dict(model_docs)
52
46
  if pretty:
53
- json.dump(json_data, f, indent=2, ensure_ascii=False, default=str)
47
+ json.dump(payload, f, ensure_ascii=False, sort_keys=True, default=str, indent=2)
54
48
  else:
55
- json.dump(json_data, f, ensure_ascii=False, default=str)
49
+ json.dump(payload, f, ensure_ascii=False, sort_keys=True, default=str)
56
50
 
57
51
  self.stdout.write(
58
52
  self.style.SUCCESS(f"✅ Generated model documentation: {output_path.absolute()}")
59
53
  )
60
- self.stdout.write(f"📊 Total models: {len(model_docs)}")
61
54
  self.stdout.write(
62
- f"📦 Total apps: {len({model['app_label'] for model in model_docs.values()})}"
55
+ f"📊 Total models: {sum([len(model_docs[app_label]) for app_label in model_docs])}"
63
56
  )
57
+ self.stdout.write(f"📦 Total apps: {len(model_docs)}")
64
58
 
65
59
  def generate_model_documentation(self, exclude_apps):
66
60
  """Generate documentation for all Django models"""
67
- model_docs = {}
61
+ model_docs = defaultdict(dict)
68
62
 
69
63
  for app_config in apps.get_app_configs():
70
64
  app_label = app_config.label
@@ -78,13 +72,11 @@ class Command(BaseCommand):
78
72
 
79
73
  for model in app_config.get_models():
80
74
  model_name = model.__name__
81
- model_key = f"{app_label}.{model_name}"
82
-
83
75
  self.stdout.write(f" 📋 Processing model: {model_name}")
84
76
 
85
- model_docs[model_key] = self.introspect_model(model, app_label)
77
+ model_docs[app_label][model_name] = self.introspect_model(model, app_label)
86
78
 
87
- return model_docs
79
+ return {app_label: dict(models) for app_label, models in model_docs.items()}
88
80
 
89
81
  def introspect_model(self, model, app_label):
90
82
  """Introspect a single Django model"""
@@ -154,6 +146,9 @@ class Command(BaseCommand):
154
146
  "type": field.__class__.__name__,
155
147
  "related_model": related_model_label,
156
148
  "related_name": getattr(field, "related_name", None),
149
+ "app_label": field.related_model._meta.app_label,
150
+ "table_name": field.related_model._meta.db_table,
151
+ "verbose_name": field.related_model._meta.verbose_name,
157
152
  "on_delete": self.get_on_delete_name(field),
158
153
  "null": getattr(field, "null", False),
159
154
  "blank": getattr(field, "blank", False),
@@ -286,7 +281,7 @@ class Command(BaseCommand):
286
281
  if display_method_match:
287
282
  field_name = display_method_match.group(1)
288
283
  if field_name in model_field_names:
289
- # Exclude if the field doesn't exist in the model
284
+ # Exclude built-in get_<field>_display for fields present on the model
290
285
  continue
291
286
 
292
287
  method = getattr(model, attr_name)
File without changes
@@ -0,0 +1,13 @@
1
+ from enum import Enum
2
+
3
+
4
+ class MessageRole(Enum):
5
+ SYSTEM = "system"
6
+ USER = "user"
7
+ ASSISTANT = "assistant"
8
+ FUNCTION = "function"
9
+ TOOL = "tool"
10
+ MODEL = "model"
11
+
12
+ def __str__(self) -> str:
13
+ return self.value
@@ -0,0 +1,19 @@
1
+ class AIProviderError(Exception):
2
+ """Base exception for AI provider errors"""
3
+
4
+ def __init__(self, message: str, provider: str | None = None, model: str | None = None):
5
+ self.provider = provider
6
+ self.model = model
7
+ super().__init__(message)
8
+
9
+ def __str__(self) -> str:
10
+ base = super().__str__()
11
+ meta = ", ".join(
12
+ part
13
+ for part in (
14
+ f"provider={self.provider}" if self.provider else None,
15
+ f"model={self.model}" if self.model else None,
16
+ )
17
+ if part
18
+ )
19
+ return f"{base} ({meta})" if meta else base
File without changes
@@ -0,0 +1,123 @@
1
+ import json
2
+ from abc import ABC, abstractmethod
3
+ from pathlib import Path
4
+ from threading import Lock
5
+ from typing import Any
6
+
7
+ from django.template import RequestContext
8
+
9
+ from drf_to_mkdoc.conf.settings import drf_to_mkdoc_settings
10
+ from drf_to_mkdoc.utils.ai_tools.exceptions import AIProviderError
11
+ from drf_to_mkdoc.utils.ai_tools.types import (
12
+ ChatResponse,
13
+ Message,
14
+ ProviderConfig,
15
+ TokenUsage,
16
+ )
17
+ from drf_to_mkdoc.utils.commons.schema_utils import OperationExtractor
18
+
19
+
20
+ class BaseProvider(ABC):
21
+ """Abstract base class for AI providers"""
22
+
23
+ def __init__(self, config: ProviderConfig):
24
+ self.config = config
25
+ self._client = None
26
+
27
+ @property
28
+ def client(self):
29
+ """Lazy load client"""
30
+ if self._client is None:
31
+ if not hasattr(self, "_client_lock"):
32
+ # If providers are shared across threads, guard initialization.
33
+ self._client_lock = Lock()
34
+ with self._client_lock:
35
+ if self._client is None:
36
+ self._client = self._initialize_client()
37
+ return self._client
38
+
39
+ @abstractmethod
40
+ def _initialize_client(self) -> Any:
41
+ """Initialize provider-specific client"""
42
+ pass
43
+
44
+ @abstractmethod
45
+ def _send_chat_request(self, formatted_messages: Any, **kwargs) -> Any:
46
+ """Send request to provider's API"""
47
+ pass
48
+
49
+ @abstractmethod
50
+ def _parse_provider_response(self, response: Any) -> ChatResponse:
51
+ """Parse provider response to standard ChatResponse"""
52
+ pass
53
+
54
+ @abstractmethod
55
+ def _extract_token_usage(self, response: Any) -> TokenUsage:
56
+ """Extract token usage from provider response"""
57
+ pass
58
+
59
+ def format_messages_for_provider(self, messages: list[Message]) -> Any:
60
+ """
61
+ Convert your Message objects into a single string for chat.send_message().
62
+ This is a default behavior. You can override it your self as you want.
63
+ """
64
+ lines = []
65
+ for message in messages:
66
+ lines.append(f"{message.role.value}: {message.content}")
67
+
68
+ return "\n".join(lines)
69
+
70
+ def chat_completion(self, messages: list[Message], **kwargs) -> ChatResponse:
71
+ """
72
+ Send chat completion request without functions
73
+
74
+ Args:
75
+ messages: List of chat messages
76
+ **kwargs: Additional provider-specific parameters
77
+
78
+ Returns:
79
+ ChatResponse with AI's response
80
+ """
81
+ try:
82
+ formatted_messages = self.format_messages_for_provider(messages)
83
+
84
+ raw_response = self._send_chat_request(formatted_messages, **kwargs)
85
+
86
+ response = self._parse_provider_response(raw_response)
87
+
88
+ response.usage = self._extract_token_usage(raw_response)
89
+ response.model = self.config.model_name
90
+
91
+ except Exception as e:
92
+ raise AIProviderError(
93
+ f"Chat completion failed: {e!s}",
94
+ provider=self.__class__.__name__,
95
+ model=self.config.model_name,
96
+ ) from e
97
+ else:
98
+ return response
99
+
100
+ def _get_operation_info(
101
+ self, operation_id: str, context: RequestContext | None = None
102
+ ) -> dict[str, Any]:
103
+ return OperationExtractor().operation_map.get(operation_id)
104
+
105
+ def _get_model_info(self, app_label: str, model_name: str) -> dict[str, Any]:
106
+ docs_file = Path(drf_to_mkdoc_settings.MODEL_DOCS_FILE)
107
+
108
+ if not docs_file.exists():
109
+ raise FileNotFoundError(f"Model documentation file not found: {docs_file}")
110
+
111
+ with docs_file.open("r", encoding="utf-8") as f:
112
+ model_docs = json.load(f)
113
+
114
+ if app_label not in model_docs:
115
+ raise LookupError(f"App '{app_label}' not found in model documentation.")
116
+
117
+ if model_name not in model_docs[app_label]:
118
+ raise LookupError(f"Model '{model_name}' not found in model documentation.")
119
+
120
+ return model_docs[app_label][model_name]
121
+
122
+ def __repr__(self) -> str:
123
+ return f"{self.__class__.__name__}(provider={self.__class__.__name__}, model={self.config.model_name})"
@@ -0,0 +1,80 @@
1
+ from google import genai
2
+ from google.genai.types import GenerateContentConfig, GenerateContentResponse
3
+
4
+ from drf_to_mkdoc.utils.ai_tools.exceptions import AIProviderError
5
+ from drf_to_mkdoc.utils.ai_tools.providers.base_provider import BaseProvider
6
+ from drf_to_mkdoc.utils.ai_tools.types import (
7
+ ChatResponse,
8
+ TokenUsage,
9
+ )
10
+
11
+
12
+ class GeminiProvider(BaseProvider):
13
+ def _initialize_client(self) -> genai.Client:
14
+ try:
15
+ client = genai.Client(api_key=self.config.api_key)
16
+
17
+ except Exception as e:
18
+ raise AIProviderError(
19
+ f"Failed to initialize Gemini client: {e!s}",
20
+ provider="GeminiProvider",
21
+ model=self.config.model_name,
22
+ ) from e
23
+ else:
24
+ return client
25
+
26
+ def _send_chat_request(
27
+ self, formatted_messages, *args, **kwargs
28
+ ) -> GenerateContentResponse:
29
+ client: genai.Client = self.client
30
+ try:
31
+ return client.models.generate_content(
32
+ model=self.config.model_name,
33
+ contents=formatted_messages,
34
+ config=GenerateContentConfig(
35
+ temperature=self.config.temperature,
36
+ max_output_tokens=self.config.max_tokens,
37
+ **(self.config.extra_params or {}).get("generate_content_config", {}),
38
+ ),
39
+ )
40
+
41
+ except Exception as e:
42
+ raise AIProviderError(
43
+ f"Chat completion failed: Gemini API request failed: {e!s}",
44
+ provider="GeminiProvider",
45
+ model=self.config.model_name,
46
+ ) from e
47
+
48
+ def _parse_provider_response(self, response: GenerateContentResponse) -> ChatResponse:
49
+ try:
50
+ return ChatResponse(
51
+ content=(getattr(response, "text", "") or "").strip(),
52
+ model=self.config.model_name,
53
+ )
54
+
55
+ except Exception as e:
56
+ raise AIProviderError(
57
+ f"Failed to parse Gemini response: {e!s}",
58
+ provider="GeminiProvider",
59
+ model=self.config.model_name,
60
+ ) from e
61
+
62
+ def _extract_token_usage(self, response: GenerateContentResponse) -> TokenUsage:
63
+ usage = getattr(response, "usage_metadata", None)
64
+ if not usage:
65
+ return TokenUsage(
66
+ request_tokens=0,
67
+ response_tokens=0,
68
+ total_tokens=0,
69
+ provider=self.__class__.__name__,
70
+ model=self.config.model_name,
71
+ )
72
+ request_tokens = int(getattr(usage, "prompt_token_count", 0) or 0)
73
+ response_tokens = int(getattr(usage, "candidates_token_count", 0) or 0)
74
+ return TokenUsage(
75
+ request_tokens=request_tokens,
76
+ response_tokens=response_tokens,
77
+ total_tokens=request_tokens + response_tokens,
78
+ provider=self.__class__.__name__,
79
+ model=self.config.model_name,
80
+ )