Skip to content

litellm_client

LiteLLM client wrapper for feature engineering.

Provides a unified interface to 100+ LLM providers through LiteLLM, enabling flexible model selection without vendor lock-in.

LiteLLMConfig

Bases: BaseModel

Configuration for LiteLLM client.

Source code in featcopilot/llm/litellm_client.py
class LiteLLMConfig(BaseModel):
    """Configuration for LiteLLM client."""

    model: str = Field(default=DEFAULT_MODEL, description="Model identifier")
    temperature: float = Field(default=0.3, ge=0, le=2, description="Temperature for generation")
    max_tokens: int = Field(default=4096, gt=0, description="Maximum tokens in response")
    timeout: float = Field(default=60.0, gt=0, description="Timeout in seconds")
    api_key: str | None = Field(default=None, description="API key (uses env var if not provided)")
    api_base: str | None = Field(default=None, description="Custom API base URL")

LiteLLMFeatureClient

LiteLLM client wrapper for feature engineering.

Provides a unified interface to 100+ LLM providers through LiteLLM, supporting OpenAI, Anthropic, Azure, Google, Cohere, and many more.

Parameters:

Name Type Description Default
config LiteLLMConfig

Configuration for the client

None
model str

Model to use for generation. Defaults to the shared DEFAULT_MODEL; specify a provider-supported identifier when using another backend.

DEFAULT_MODEL
api_key str

API key for the provider (uses environment variable if not provided)

None
api_base str

Custom API base URL for self-hosted models

None

Examples:

>>> client = LiteLLMFeatureClient(model='gpt-4o')
>>> await client.start()
>>> suggestions = await client.suggest_features(
...     column_info={'age': 'int', 'income': 'float'},
...     task='predict churn'
... )
>>> await client.stop()
Notes

Supported model prefixes: - OpenAI: gpt-4, gpt-4o, gpt-3.5-turbo - Anthropic: claude-3-opus, claude-3-sonnet, claude-3-haiku - Azure: azure/deployment-name - Google: gemini-pro, gemini-ultra - AWS Bedrock: bedrock/model-id - Ollama: ollama/llama2, ollama/mistral - And many more...

Source code in featcopilot/llm/litellm_client.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
class LiteLLMFeatureClient:
    """
    LiteLLM client wrapper for feature engineering.

    Provides a unified interface to 100+ LLM providers through LiteLLM,
    supporting OpenAI, Anthropic, Azure, Google, Cohere, and many more.

    Parameters
    ----------
    config : LiteLLMConfig, optional
        Configuration for the client
    model : str, optional
        Model to use for generation. Defaults to the shared DEFAULT_MODEL;
        specify a provider-supported identifier when using another backend.
    api_key : str, optional
        API key for the provider (uses environment variable if not provided)
    api_base : str, optional
        Custom API base URL for self-hosted models

    Examples
    --------
    >>> client = LiteLLMFeatureClient(model='gpt-4o')
    >>> await client.start()
    >>> suggestions = await client.suggest_features(
    ...     column_info={'age': 'int', 'income': 'float'},
    ...     task='predict churn'
    ... )
    >>> await client.stop()

    Notes
    -----
    Supported model prefixes:
    - OpenAI: gpt-4, gpt-4o, gpt-3.5-turbo
    - Anthropic: claude-3-opus, claude-3-sonnet, claude-3-haiku
    - Azure: azure/deployment-name
    - Google: gemini-pro, gemini-ultra
    - AWS Bedrock: bedrock/model-id
    - Ollama: ollama/llama2, ollama/mistral
    - And many more...
    """

    def __init__(
        self,
        config: LiteLLMConfig | None = None,
        model: str = DEFAULT_MODEL,
        api_key: str | None = None,
        api_base: str | None = None,
        **kwargs,
    ):
        self.config = config or LiteLLMConfig(model=model, api_key=api_key, api_base=api_base, **kwargs)
        self._is_started = False
        self._litellm_available = False
        self._litellm: LiteLLMProvider | None = None

    async def start(self) -> "LiteLLMFeatureClient":
        """
        Start the LiteLLM client.

        Returns
        -------
        self : LiteLLMFeatureClient
        """
        try:
            import litellm

            self._litellm = litellm
            self._litellm_available = True
            self._is_started = True

            logger.info(f"LiteLLM client started with model: {self.config.model}")

        except ImportError:
            self._litellm_available = False
            self._is_started = False
            logger.error("LiteLLM is unavailable. Install featcopilot[litellm].")
            raise

        return self

    async def stop(self) -> None:
        """Stop the LiteLLM client."""
        self._is_started = False
        self._litellm_available = False
        self._litellm = None

    async def send_prompt(self, prompt: str, system_prompt: str | None = None) -> str:
        """
        Send a prompt and get a response.

        Parameters
        ----------
        prompt : str
            The prompt to send
        system_prompt : str, optional
            System prompt for the model

        Returns
        -------
        response : str
            The model's response
        """
        if not self._is_started:
            await self.start()

        if not self._litellm_available or self._litellm is None:
            raise RuntimeError("LiteLLM client is unavailable")

        try:
            messages = []
            if system_prompt:
                messages.append({"role": "system", "content": system_prompt})
            messages.append({"role": "user", "content": prompt})

            # Build kwargs for litellm
            kwargs: dict[str, Any] = {
                "model": self.config.model,
                "messages": messages,
                "temperature": self.config.temperature,
                "max_tokens": self.config.max_tokens,
                "timeout": self.config.timeout,
            }

            if self.config.api_base:
                kwargs["api_base"] = self.config.api_base
            if self.config.api_key:
                kwargs["api_key"] = self.config.api_key

            # Use async completion
            response = await self._litellm.acompletion(**kwargs)

            content = response.choices[0].message.content if response.choices else None
            if not isinstance(content, str) or not content.strip():
                raise ValueError("LiteLLM returned an empty or non-text response")
            return content

        except Exception as e:
            logger.error(f"LiteLLM request failed: {e}")
            raise

    def _mock_response(self, prompt: str) -> str:
        """Generate synthetic responses for explicit test doubles only."""
        import re

        columns = re.findall(r"- (\w+) \(", prompt)

        if ("suggest" in prompt.lower() or "feature" in prompt.lower()) and columns:
            features = []
            if len(columns) >= 2:
                col1, col2 = columns[0], columns[1]
                features.append(
                    {
                        "name": f"{col1}_{col2}_ratio",
                        "code": f"result = df['{col1}'] / (df['{col2}'] + 1e-8)",
                        "explanation": f"Ratio of {col1} to {col2}, captures relative relationship",
                        "source_columns": [col1, col2],
                    }
                )
                features.append(
                    {
                        "name": f"{col1}_{col2}_product",
                        "code": f"result = df['{col1}'] * df['{col2}']",
                        "explanation": f"Interaction between {col1} and {col2}",
                        "source_columns": [col1, col2],
                    }
                )
            if len(columns) >= 3:
                col3 = columns[2]
                features.append(
                    {
                        "name": f"{columns[0]}_normalized_by_{col3}",
                        "code": f"result = (df['{columns[0]}'] - df['{columns[0]}'].mean()) / (df['{col3}'] + 1e-8)",
                        "explanation": f"Normalized {columns[0]} adjusted by {col3}",
                        "source_columns": [columns[0], col3],
                    }
                )
            if len(columns) >= 1:
                features.append(
                    {
                        "name": f"{columns[0]}_zscore",
                        "code": f"result = (df['{columns[0]}'] - df['{columns[0]}'].mean()) / (df['{columns[0]}'].std() + 1e-8)",
                        "explanation": f"Z-score normalization of {columns[0]}",
                        "source_columns": [columns[0]],
                    }
                )
            return json.dumps({"features": features})
        elif "suggest" in prompt.lower() or "feature" in prompt.lower():
            return json.dumps(
                {
                    "features": [
                        {
                            "name": "feature_interaction",
                            "code": "result = df.iloc[:, 0] * df.iloc[:, 1]",
                            "explanation": "Interaction between first two features",
                        }
                    ]
                }
            )
        elif "explain" in prompt.lower():
            return "This feature captures the relationship between the input variables."
        elif "code" in prompt.lower():
            return "result = df.iloc[:, 0] * df.iloc[:, 1]"
        else:
            return "Mock response for: " + prompt[:100]

    async def suggest_features(
        self,
        column_info: dict[str, str],
        task_description: str,
        column_descriptions: dict[str, str] | None = None,
        domain: str | None = None,
        max_suggestions: int = 10,
    ) -> list[dict[str, Any]]:
        """
        Get LLM suggestions for new features.

        Parameters
        ----------
        column_info : dict
            Dictionary mapping column names to data types
        task_description : str
            Description of the ML task
        column_descriptions : dict, optional
            Human-readable descriptions of columns
        domain : str, optional
            Domain context (e.g., 'healthcare', 'finance')
        max_suggestions : int, default=10
            Maximum number of feature suggestions

        Returns
        -------
        suggestions : list
            List of feature suggestions with code and explanations
        """
        prompt = self._build_suggestion_prompt(
            column_info, task_description, column_descriptions, domain, max_suggestions
        )

        system_prompt = (
            "You are an expert data scientist specializing in feature engineering. "
            "Always respond with valid JSON only."
        )

        response = await self.send_prompt(prompt, system_prompt=system_prompt)
        return self._parse_suggestions(response)

    def _build_suggestion_prompt(
        self,
        column_info: dict[str, str],
        task_description: str,
        column_descriptions: dict[str, str] | None = None,
        domain: str | None = None,
        max_suggestions: int = 10,
    ) -> str:
        """Build the prompt for feature suggestions."""
        prompt = f"""Suggest {max_suggestions} new features for the following machine learning task.

## ML Task
{task_description}

## Available Columns
"""
        for col, dtype in column_info.items():
            desc = column_descriptions.get(col, "") if column_descriptions else ""
            prompt += f"- {col} ({dtype}): {desc}\n"

        if domain:
            prompt += f"\n## Domain Context\nThis is a {domain} problem.\n"

        prompt += """
## Requirements
1. Suggest features that would be predictive for this task
2. Provide Python code using pandas (assume df is the DataFrame)
3. Explain why each feature might be useful
4. Consider interactions, ratios, and domain-specific transformations
5. Assign a one-dimensional result to `result`, retaining the input row index
6. Use row-wise transformations only: do not recompute dataset/group statistics,
   quantile bins, ranks, or learned mappings from the inference batch
7. Do not mutate df; np and pd are available, without imports

## Output Format
Return a JSON object with a "features" array, each element having:
- "name": feature name (snake_case)
- "code": Python code to compute the feature (single line, result assigned to variable)
- "explanation": why this feature might be predictive
- "source_columns": list of column names used

Example:
{
  "features": [
    {
      "name": "age_income_ratio",
      "code": "result = df['age'] / (df['income'] + 1)",
      "explanation": "Ratio of age to income may indicate life stage and financial maturity",
      "source_columns": ["age", "income"]
    }
  ]
}

Return ONLY the JSON object, no other text.
"""
        return prompt

    def _parse_suggestions(self, response: str) -> list[dict[str, Any]]:
        """Parse feature suggestions from LLM response."""
        try:
            response = response.strip()
            if response.startswith("```"):
                lines = response.split("\n")
                response = "\n".join(lines[1:-1])

            data = json.loads(response)
            return feature_suggestions(data)

        except json.JSONDecodeError:
            import re

            json_match = re.search(r"\{.*\}", response, re.DOTALL)
            if json_match:
                try:
                    data = json.loads(json_match.group())
                    return feature_suggestions(data)
                except json.JSONDecodeError:
                    pass

            logger.warning("LiteLLM returned invalid feature suggestion JSON")
            return []

    async def explain_feature(
        self,
        feature_name: str,
        feature_code: str,
        column_descriptions: dict[str, str] | None = None,
        task_description: str | None = None,
    ) -> str:
        """
        Get a human-readable explanation of a feature.

        Parameters
        ----------
        feature_name : str
            Name of the feature
        feature_code : str
            Code that generates the feature
        column_descriptions : dict, optional
            Descriptions of source columns
        task_description : str, optional
            Description of the ML task

        Returns
        -------
        explanation : str
            Human-readable explanation
        """
        prompt = f"""Explain this feature in simple terms for a business stakeholder:

Feature Name: {feature_name}
Code: {feature_code}
"""
        if column_descriptions:
            prompt += "\nColumn Descriptions:\n"
            for col, desc in column_descriptions.items():
                prompt += f"- {col}: {desc}\n"

        if task_description:
            prompt += f"\nML Task: {task_description}\n"

        prompt += """
Provide a 2-3 sentence explanation of:
1. What this feature represents
2. Why it might be predictive for the task
"""
        return await self.send_prompt(prompt)

    async def generate_feature_code(
        self, description: str, column_info: dict[str, str], constraints: list[str] | None = None
    ) -> str:
        """
        Generate Python code for a described feature.

        Parameters
        ----------
        description : str
            Natural language description of desired feature
        column_info : dict
            Available columns and their types
        constraints : list, optional
            Constraints on the generated code

        Returns
        -------
        code : str
            Python code to generate the feature
        """
        prompt = f"""Generate Python code to create this feature:

Description: {description}

Available Columns:
"""
        for col, dtype in column_info.items():
            prompt += f"- {col} ({dtype})\n"

        if constraints:
            prompt += "\nConstraints:\n"
            for c in constraints:
                prompt += f"- {c}\n"

        prompt += """
Requirements:
1. Use pandas operations (assume df is the DataFrame)
2. Assign the result to a variable called 'result'
3. Handle edge cases (division by zero, missing values)
4. Return ONLY the code, no explanations

Example output:
result = df['col1'] / (df['col2'] + 1e-8)
"""
        response = await self.send_prompt(prompt)

        code = response.strip()
        if "```" in code:
            lines = code.split("\n")
            code_lines = []
            in_code_block = False
            for line in lines:
                if line.startswith("```"):
                    in_code_block = not in_code_block
                elif in_code_block:
                    code_lines.append(line)
            code = "\n".join(code_lines)

        if not code.strip():
            raise ValueError("LiteLLM returned an empty code response")
        return code

    async def validate_feature_code(self, code: str, sample_data: dict[str, list] | None = None) -> dict[str, Any]:
        """
        Validate generated feature code.

        Parameters
        ----------
        code : str
            Feature code to validate
        sample_data : dict, optional
            Sample data for testing

        Returns
        -------
        result : dict
            Validation result with 'valid', 'error', and 'warnings' keys
        """
        return validate_feature_code(code, sample_data)

explain_feature(feature_name, feature_code, column_descriptions=None, task_description=None) async

Get a human-readable explanation of a feature.

Parameters:

Name Type Description Default
feature_name str

Name of the feature

required
feature_code str

Code that generates the feature

required
column_descriptions dict

Descriptions of source columns

None
task_description str

Description of the ML task

None

Returns:

Name Type Description
explanation str

Human-readable explanation

Source code in featcopilot/llm/litellm_client.py
    async def explain_feature(
        self,
        feature_name: str,
        feature_code: str,
        column_descriptions: dict[str, str] | None = None,
        task_description: str | None = None,
    ) -> str:
        """
        Get a human-readable explanation of a feature.

        Parameters
        ----------
        feature_name : str
            Name of the feature
        feature_code : str
            Code that generates the feature
        column_descriptions : dict, optional
            Descriptions of source columns
        task_description : str, optional
            Description of the ML task

        Returns
        -------
        explanation : str
            Human-readable explanation
        """
        prompt = f"""Explain this feature in simple terms for a business stakeholder:

Feature Name: {feature_name}
Code: {feature_code}
"""
        if column_descriptions:
            prompt += "\nColumn Descriptions:\n"
            for col, desc in column_descriptions.items():
                prompt += f"- {col}: {desc}\n"

        if task_description:
            prompt += f"\nML Task: {task_description}\n"

        prompt += """
Provide a 2-3 sentence explanation of:
1. What this feature represents
2. Why it might be predictive for the task
"""
        return await self.send_prompt(prompt)

generate_feature_code(description, column_info, constraints=None) async

Generate Python code for a described feature.

Parameters:

Name Type Description Default
description str

Natural language description of desired feature

required
column_info dict

Available columns and their types

required
constraints list

Constraints on the generated code

None

Returns:

Name Type Description
code str

Python code to generate the feature

Source code in featcopilot/llm/litellm_client.py
    async def generate_feature_code(
        self, description: str, column_info: dict[str, str], constraints: list[str] | None = None
    ) -> str:
        """
        Generate Python code for a described feature.

        Parameters
        ----------
        description : str
            Natural language description of desired feature
        column_info : dict
            Available columns and their types
        constraints : list, optional
            Constraints on the generated code

        Returns
        -------
        code : str
            Python code to generate the feature
        """
        prompt = f"""Generate Python code to create this feature:

Description: {description}

Available Columns:
"""
        for col, dtype in column_info.items():
            prompt += f"- {col} ({dtype})\n"

        if constraints:
            prompt += "\nConstraints:\n"
            for c in constraints:
                prompt += f"- {c}\n"

        prompt += """
Requirements:
1. Use pandas operations (assume df is the DataFrame)
2. Assign the result to a variable called 'result'
3. Handle edge cases (division by zero, missing values)
4. Return ONLY the code, no explanations

Example output:
result = df['col1'] / (df['col2'] + 1e-8)
"""
        response = await self.send_prompt(prompt)

        code = response.strip()
        if "```" in code:
            lines = code.split("\n")
            code_lines = []
            in_code_block = False
            for line in lines:
                if line.startswith("```"):
                    in_code_block = not in_code_block
                elif in_code_block:
                    code_lines.append(line)
            code = "\n".join(code_lines)

        if not code.strip():
            raise ValueError("LiteLLM returned an empty code response")
        return code

send_prompt(prompt, system_prompt=None) async

Send a prompt and get a response.

Parameters:

Name Type Description Default
prompt str

The prompt to send

required
system_prompt str

System prompt for the model

None

Returns:

Name Type Description
response str

The model's response

Source code in featcopilot/llm/litellm_client.py
async def send_prompt(self, prompt: str, system_prompt: str | None = None) -> str:
    """
    Send a prompt and get a response.

    Parameters
    ----------
    prompt : str
        The prompt to send
    system_prompt : str, optional
        System prompt for the model

    Returns
    -------
    response : str
        The model's response
    """
    if not self._is_started:
        await self.start()

    if not self._litellm_available or self._litellm is None:
        raise RuntimeError("LiteLLM client is unavailable")

    try:
        messages = []
        if system_prompt:
            messages.append({"role": "system", "content": system_prompt})
        messages.append({"role": "user", "content": prompt})

        # Build kwargs for litellm
        kwargs: dict[str, Any] = {
            "model": self.config.model,
            "messages": messages,
            "temperature": self.config.temperature,
            "max_tokens": self.config.max_tokens,
            "timeout": self.config.timeout,
        }

        if self.config.api_base:
            kwargs["api_base"] = self.config.api_base
        if self.config.api_key:
            kwargs["api_key"] = self.config.api_key

        # Use async completion
        response = await self._litellm.acompletion(**kwargs)

        content = response.choices[0].message.content if response.choices else None
        if not isinstance(content, str) or not content.strip():
            raise ValueError("LiteLLM returned an empty or non-text response")
        return content

    except Exception as e:
        logger.error(f"LiteLLM request failed: {e}")
        raise

start() async

Start the LiteLLM client.

Returns:

Name Type Description
self LiteLLMFeatureClient
Source code in featcopilot/llm/litellm_client.py
async def start(self) -> "LiteLLMFeatureClient":
    """
    Start the LiteLLM client.

    Returns
    -------
    self : LiteLLMFeatureClient
    """
    try:
        import litellm

        self._litellm = litellm
        self._litellm_available = True
        self._is_started = True

        logger.info(f"LiteLLM client started with model: {self.config.model}")

    except ImportError:
        self._litellm_available = False
        self._is_started = False
        logger.error("LiteLLM is unavailable. Install featcopilot[litellm].")
        raise

    return self

stop() async

Stop the LiteLLM client.

Source code in featcopilot/llm/litellm_client.py
async def stop(self) -> None:
    """Stop the LiteLLM client."""
    self._is_started = False
    self._litellm_available = False
    self._litellm = None

suggest_features(column_info, task_description, column_descriptions=None, domain=None, max_suggestions=10) async

Get LLM suggestions for new features.

Parameters:

Name Type Description Default
column_info dict

Dictionary mapping column names to data types

required
task_description str

Description of the ML task

required
column_descriptions dict

Human-readable descriptions of columns

None
domain str

Domain context (e.g., 'healthcare', 'finance')

None
max_suggestions int

Maximum number of feature suggestions

10

Returns:

Name Type Description
suggestions list

List of feature suggestions with code and explanations

Source code in featcopilot/llm/litellm_client.py
async def suggest_features(
    self,
    column_info: dict[str, str],
    task_description: str,
    column_descriptions: dict[str, str] | None = None,
    domain: str | None = None,
    max_suggestions: int = 10,
) -> list[dict[str, Any]]:
    """
    Get LLM suggestions for new features.

    Parameters
    ----------
    column_info : dict
        Dictionary mapping column names to data types
    task_description : str
        Description of the ML task
    column_descriptions : dict, optional
        Human-readable descriptions of columns
    domain : str, optional
        Domain context (e.g., 'healthcare', 'finance')
    max_suggestions : int, default=10
        Maximum number of feature suggestions

    Returns
    -------
    suggestions : list
        List of feature suggestions with code and explanations
    """
    prompt = self._build_suggestion_prompt(
        column_info, task_description, column_descriptions, domain, max_suggestions
    )

    system_prompt = (
        "You are an expert data scientist specializing in feature engineering. "
        "Always respond with valid JSON only."
    )

    response = await self.send_prompt(prompt, system_prompt=system_prompt)
    return self._parse_suggestions(response)

validate_feature_code(code, sample_data=None) async

Validate generated feature code.

Parameters:

Name Type Description Default
code str

Feature code to validate

required
sample_data dict

Sample data for testing

None

Returns:

Name Type Description
result dict

Validation result with 'valid', 'error', and 'warnings' keys

Source code in featcopilot/llm/litellm_client.py
async def validate_feature_code(self, code: str, sample_data: dict[str, list] | None = None) -> dict[str, Any]:
    """
    Validate generated feature code.

    Parameters
    ----------
    code : str
        Feature code to validate
    sample_data : dict, optional
        Sample data for testing

    Returns
    -------
    result : dict
        Validation result with 'valid', 'error', and 'warnings' keys
    """
    return validate_feature_code(code, sample_data)

SyncLiteLLMFeatureClient

Own one loop/worker for nested and concurrent calls; stop must not overlap calls.

Source code in featcopilot/llm/litellm_client.py
class SyncLiteLLMFeatureClient:
    """Own one loop/worker for nested and concurrent calls; stop must not overlap calls."""

    def __init__(self, **kwargs) -> None:
        self._async_client = LiteLLMFeatureClient(**kwargs)
        self._loop: asyncio.AbstractEventLoop | None = None
        self._executor: ThreadPoolExecutor | None = None
        self._executor_lock = Lock()

    def _get_or_create_loop(self) -> asyncio.AbstractEventLoop:
        """Keep pooled provider connections on one event loop."""
        if self._loop is None or self._loop.is_closed():
            self._loop = asyncio.new_event_loop()
        return self._loop

    def _run_async(self, coro: Coroutine[Any, Any, _T]) -> _T:
        """Keep construction, requests and closing on the provider's owned loop."""
        with self._executor_lock:
            if self._executor is None:
                self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="featcopilot-litellm")
            future = self._executor.submit(self._run_on_owned_loop, coro)
        return future.result()

    def _run_on_owned_loop(self, coro: Coroutine[Any, Any, _T]) -> _T:
        return self._get_or_create_loop().run_until_complete(coro)

    def _close_loop(self) -> None:
        if self._loop is not None:
            self._loop.close()
            self._loop = None

    def start(self) -> "LiteLLMFeatureClient":
        """Start the client."""
        return self._run_async(self._async_client.start())

    def stop(self) -> None:
        """Stop the client."""
        try:
            self._run_async(self._async_client.stop())
        finally:
            if self._executor is not None:
                try:
                    self._executor.submit(self._close_loop).result()
                finally:
                    self._executor.shutdown(wait=True)
                    self._executor = None

    def send_prompt(self, prompt: str, system_prompt: str | None = None) -> str:
        """Send a prompt and get a response."""
        return self._run_async(self._async_client.send_prompt(prompt, system_prompt=system_prompt))

    def suggest_features(self, **kwargs) -> list[dict[str, Any]]:
        """Get feature suggestions."""
        return self._run_async(self._async_client.suggest_features(**kwargs))

    def explain_feature(self, **kwargs) -> str:
        """Explain a feature."""
        return self._run_async(self._async_client.explain_feature(**kwargs))

    def generate_feature_code(self, **kwargs) -> str:
        """Generate feature code."""
        return self._run_async(self._async_client.generate_feature_code(**kwargs))

    def validate_feature_code(self, code: str, sample_data: dict[str, list] | None = None) -> dict[str, Any]:
        """Validate feature code."""
        return self._run_async(self._async_client.validate_feature_code(code=code, sample_data=sample_data))

explain_feature(**kwargs)

Explain a feature.

Source code in featcopilot/llm/litellm_client.py
def explain_feature(self, **kwargs) -> str:
    """Explain a feature."""
    return self._run_async(self._async_client.explain_feature(**kwargs))

generate_feature_code(**kwargs)

Generate feature code.

Source code in featcopilot/llm/litellm_client.py
def generate_feature_code(self, **kwargs) -> str:
    """Generate feature code."""
    return self._run_async(self._async_client.generate_feature_code(**kwargs))

send_prompt(prompt, system_prompt=None)

Send a prompt and get a response.

Source code in featcopilot/llm/litellm_client.py
def send_prompt(self, prompt: str, system_prompt: str | None = None) -> str:
    """Send a prompt and get a response."""
    return self._run_async(self._async_client.send_prompt(prompt, system_prompt=system_prompt))

start()

Start the client.

Source code in featcopilot/llm/litellm_client.py
def start(self) -> "LiteLLMFeatureClient":
    """Start the client."""
    return self._run_async(self._async_client.start())

stop()

Stop the client.

Source code in featcopilot/llm/litellm_client.py
def stop(self) -> None:
    """Stop the client."""
    try:
        self._run_async(self._async_client.stop())
    finally:
        if self._executor is not None:
            try:
                self._executor.submit(self._close_loop).result()
            finally:
                self._executor.shutdown(wait=True)
                self._executor = None

suggest_features(**kwargs)

Get feature suggestions.

Source code in featcopilot/llm/litellm_client.py
def suggest_features(self, **kwargs) -> list[dict[str, Any]]:
    """Get feature suggestions."""
    return self._run_async(self._async_client.suggest_features(**kwargs))

validate_feature_code(code, sample_data=None)

Validate feature code.

Source code in featcopilot/llm/litellm_client.py
def validate_feature_code(self, code: str, sample_data: dict[str, list] | None = None) -> dict[str, Any]:
    """Validate feature code."""
    return self._run_async(self._async_client.validate_feature_code(code=code, sample_data=sample_data))