Skip to content

copilot_client

GitHub Copilot SDK client wrapper for feature engineering.

Provides a simplified interface to the Copilot SDK specifically designed for feature engineering tasks.

CopilotConfig

Bases: BaseModel

Configuration for Copilot client.

Source code in featcopilot/llm/copilot_client.py
class CopilotConfig(BaseModel):
    """Configuration for Copilot client."""

    model: str = Field(default=DEFAULT_MODEL, description="Model to use")
    temperature: float = Field(default=0.3, ge=0, le=1, description="Temperature for generation")
    max_tokens: int = Field(default=4096, gt=0, description="Legacy setting; not supported by the SDK session API")
    timeout: float = Field(default=60.0, gt=0, strict=True, allow_inf_nan=False, description="Timeout in seconds")
    streaming: bool = Field(default=False, description="Enable streaming responses")
    isolated_plan: bool = Field(default=False, description="Use fresh tool-disabled sessions for typed plans only")

CopilotFeatureClient

GitHub Copilot SDK client wrapper for feature engineering.

Provides high-level methods for: - Generating feature suggestions - Explaining features - Generating feature code - Validating features

Parameters:

Name Type Description Default
config CopilotConfig

Configuration for the client

None
model str

Model to use for generation. Defaults to :data:featcopilot.utils.models.DEFAULT_MODEL.

DEFAULT_MODEL
isolated_plan bool

Opt into fresh, tool-disabled, permission-rejecting typed-plan sessions. start checks SDK support locally; each send owns its entire SDK lifecycle. timeout covers startup through send, with separate bounded cooperative shutdown grace. Blocking or cancellation-resistant SDK code cannot be forcibly terminated, and may outlive the synchronous watchdog. Legacy code-generation sessions retain their existing permission policy.

False

Examples:

>>> client = CopilotFeatureClient()  # uses DEFAULT_MODEL
>>> await client.start()
>>> suggestions = await client.suggest_features(
...     column_info={'age': 'int', 'income': 'float'},
...     task='predict churn'
... )
>>> await client.stop()
Source code in featcopilot/llm/copilot_client.py
 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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
class CopilotFeatureClient:
    """
    GitHub Copilot SDK client wrapper for feature engineering.

    Provides high-level methods for:
    - Generating feature suggestions
    - Explaining features
    - Generating feature code
    - Validating features

    Parameters
    ----------
    config : CopilotConfig, optional
        Configuration for the client
    model : str, optional
        Model to use for generation. Defaults to
        :data:`featcopilot.utils.models.DEFAULT_MODEL`.
    isolated_plan : bool, default=False
        Opt into fresh, tool-disabled, permission-rejecting typed-plan sessions.
        start checks SDK support locally; each send owns its entire SDK lifecycle.
        timeout covers startup through send, with separate bounded cooperative
        shutdown grace. Blocking or cancellation-resistant SDK code cannot be
        forcibly terminated, and may outlive the synchronous watchdog.
        Legacy code-generation sessions retain their existing permission policy.

    Examples
    --------
    >>> client = CopilotFeatureClient()  # uses DEFAULT_MODEL
    >>> await client.start()
    >>> suggestions = await client.suggest_features(
    ...     column_info={'age': 'int', 'income': 'float'},
    ...     task='predict churn'
    ... )
    >>> await client.stop()
    """

    def __init__(self, config: CopilotConfig | None = None, model: str = DEFAULT_MODEL, **kwargs):
        self.config = config or CopilotConfig(model=model, **kwargs)
        self._client: CopilotClient | None = None
        self._session: CopilotSession | None = None
        self._is_started = False
        self._copilot_available = False
        self._plan_transport: IsolatedCopilotTransport | None = None

    async def start(self) -> CopilotFeatureClient:
        """
        Start the Copilot client.

        Returns
        -------
        self : CopilotFeatureClient
        """
        if self._is_started:
            return self
        if self.config.temperature != 0.3 or self.config.max_tokens != 4096:
            logger.warning("Copilot SDK sessions do not support temperature or max_tokens; these settings are ignored")
        if self.config.isolated_plan:
            try:
                self._plan_transport = IsolatedCopilotTransport()
            except ImportError:
                logger.error("Copilot SDK is unavailable. Install featcopilot[llm].")
                raise
            self._is_started = True
            self._copilot_available = True
            return self
        try:
            from copilot import CopilotClient
            from copilot.session import PermissionHandler

            self._client = CopilotClient()
            await self._client.start()
            # ``on_permission_request`` is required by the Copilot SDK
            # (since v0.1.32+; mandatory in v0.3.0); pass ``approve_all``
            # so the SDK doesn't block on interactive permission prompts
            # (the benchmarks / feature-engineering workflow has no
            # human-in-the-loop). We pass everything as keyword args
            # because v0.3.0 made ``create_session`` keyword-only.
            self._session = await self._client.create_session(
                on_permission_request=PermissionHandler.approve_all,
                model=self.config.model,
                streaming=self.config.streaming,
            )
            self._is_started = True
            self._copilot_available = True

        except ImportError:
            self._copilot_available = False
            self._is_started = False
            logger.error("Copilot SDK is unavailable. Install featcopilot[llm].")
            raise

        except Exception as e:
            self._copilot_available = False
            self._is_started = False
            logger.error(f"Could not connect to Copilot: {e}")
            if self._client is not None:
                await self._client.stop()
                self._client = None
            raise

        return self

    async def stop(self) -> None:
        """Stop the Copilot client."""
        if self._session:
            # ``destroy()`` was renamed to ``disconnect()`` in the
            # Copilot SDK 0.3.x; ``destroy()`` still works but emits a
            # ``DeprecationWarning`` before being removed. Prefer the new
            # name and look up the legacy method only for older SDKs.
            disconnect = getattr(self._session, "disconnect", None)
            if disconnect is not None:
                await disconnect()
            else:
                destroy = getattr(self._session, "destroy", None)
                if destroy is None:
                    raise RuntimeError("Copilot session has no supported cleanup method")
                await destroy()
        if self._client:
            await self._client.stop()
        self._is_started = False
        self._copilot_available = False
        self._session = None
        self._client = None
        self._plan_transport = None

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

        Parameters
        ----------
        prompt : str
            The prompt to send

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

        if self.config.isolated_plan:
            if self._plan_transport is None:
                raise RuntimeError("Copilot plan transport is not initialized")

            async def send(session: CopilotSession) -> str:
                event = await session.send_and_wait(prompt, timeout=self.config.timeout)
                content: str = plan_message(event).content
                return content

            return await self._plan_transport.request(self.config.model, self.config.timeout, send)

        if not self._copilot_available or self._session is None:
            raise RuntimeError("Copilot client has no active session")

        # Use the SDK's ``send_and_wait`` helper which handles the
        # send-prompt → wait-for-session.idle → return-assistant-message
        # pattern internally. Returns ``SessionEvent | None`` whose
        # ``data.content`` carries the assistant's text. Older SDKs
        # (<0.1.32) accepted a dict; the new SDK takes a positional
        # string and exposes a typed return type.
        # Catch the union of timeout exception classes so timeout handling
        # is reliable across Python versions and SDK implementations:
        # - Built-in ``TimeoutError`` is what the github-copilot-sdk
        #   currently raises (``raise TimeoutError(...)`` in
        #   ``copilot/session.py``).
        # - ``asyncio.TimeoutError`` was a separate class on Python 3.10
        #   (only became an alias for ``TimeoutError`` in 3.11+); we
        #   support 3.10 per ``pyproject.toml``.
        # - ``concurrent.futures.TimeoutError`` is what some thread/process
        #   bridges surface; cheap to include.
        try:
            event = await self._session.send_and_wait(prompt, timeout=self.config.timeout)
        except (TimeoutError, asyncio.TimeoutError, concurrent.futures.TimeoutError) as error:
            raise TimeoutError(f"Copilot request timed out after {self.config.timeout} seconds") from error

        if event is None:
            raise ValueError("Copilot returned an empty response")
        # ``event.data`` is an ``AssistantMessageData`` with a text ``content`` attribute.
        data = getattr(event, "data", None)
        content = getattr(data, "content", None)
        if not isinstance(content, str) or not content.strip():
            raise ValueError("Copilot returned an empty or non-text response")
        return content

    def _mock_response(self, prompt: str) -> str:
        """Generate synthetic responses for explicit test doubles only."""
        # Extract column names from prompt if available
        import re

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

        if ("suggest" in prompt.lower() or "feature" in prompt.lower()) and columns:
            # Generate context-aware mock features based on actual 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"{col1}_normalized_by_{col3}",
                        "code": f"result = (df['{col1}'] - df['{col1}'].mean()) / (df['{col3}'] + 1e-8)",
                        "explanation": f"Normalized {col1} adjusted by {col3}",
                        "source_columns": [col1, 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
        )

        response = await self.send_prompt(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"""You are an expert data scientist specializing in feature engineering.

TASK: 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:
            # Try to extract JSON from response
            response = response.strip()
            if response.startswith("```"):
                # Remove markdown code blocks
                lines = response.split("\n")
                response = "\n".join(lines[1:-1])

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

        except json.JSONDecodeError:
            # Try to extract JSON substring
            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("Copilot 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)

        # Extract code from response
        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("Copilot 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/copilot_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/copilot_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)

        # Extract code from response
        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("Copilot returned an empty code response")
        return code

send_prompt(prompt) async

Send a prompt and get a response.

Parameters:

Name Type Description Default
prompt str

The prompt to send

required

Returns:

Name Type Description
response str

The model's response

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

    Parameters
    ----------
    prompt : str
        The prompt to send

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

    if self.config.isolated_plan:
        if self._plan_transport is None:
            raise RuntimeError("Copilot plan transport is not initialized")

        async def send(session: CopilotSession) -> str:
            event = await session.send_and_wait(prompt, timeout=self.config.timeout)
            content: str = plan_message(event).content
            return content

        return await self._plan_transport.request(self.config.model, self.config.timeout, send)

    if not self._copilot_available or self._session is None:
        raise RuntimeError("Copilot client has no active session")

    # Use the SDK's ``send_and_wait`` helper which handles the
    # send-prompt → wait-for-session.idle → return-assistant-message
    # pattern internally. Returns ``SessionEvent | None`` whose
    # ``data.content`` carries the assistant's text. Older SDKs
    # (<0.1.32) accepted a dict; the new SDK takes a positional
    # string and exposes a typed return type.
    # Catch the union of timeout exception classes so timeout handling
    # is reliable across Python versions and SDK implementations:
    # - Built-in ``TimeoutError`` is what the github-copilot-sdk
    #   currently raises (``raise TimeoutError(...)`` in
    #   ``copilot/session.py``).
    # - ``asyncio.TimeoutError`` was a separate class on Python 3.10
    #   (only became an alias for ``TimeoutError`` in 3.11+); we
    #   support 3.10 per ``pyproject.toml``.
    # - ``concurrent.futures.TimeoutError`` is what some thread/process
    #   bridges surface; cheap to include.
    try:
        event = await self._session.send_and_wait(prompt, timeout=self.config.timeout)
    except (TimeoutError, asyncio.TimeoutError, concurrent.futures.TimeoutError) as error:
        raise TimeoutError(f"Copilot request timed out after {self.config.timeout} seconds") from error

    if event is None:
        raise ValueError("Copilot returned an empty response")
    # ``event.data`` is an ``AssistantMessageData`` with a text ``content`` attribute.
    data = getattr(event, "data", None)
    content = getattr(data, "content", None)
    if not isinstance(content, str) or not content.strip():
        raise ValueError("Copilot returned an empty or non-text response")
    return content

start() async

Start the Copilot client.

Returns:

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

    Returns
    -------
    self : CopilotFeatureClient
    """
    if self._is_started:
        return self
    if self.config.temperature != 0.3 or self.config.max_tokens != 4096:
        logger.warning("Copilot SDK sessions do not support temperature or max_tokens; these settings are ignored")
    if self.config.isolated_plan:
        try:
            self._plan_transport = IsolatedCopilotTransport()
        except ImportError:
            logger.error("Copilot SDK is unavailable. Install featcopilot[llm].")
            raise
        self._is_started = True
        self._copilot_available = True
        return self
    try:
        from copilot import CopilotClient
        from copilot.session import PermissionHandler

        self._client = CopilotClient()
        await self._client.start()
        # ``on_permission_request`` is required by the Copilot SDK
        # (since v0.1.32+; mandatory in v0.3.0); pass ``approve_all``
        # so the SDK doesn't block on interactive permission prompts
        # (the benchmarks / feature-engineering workflow has no
        # human-in-the-loop). We pass everything as keyword args
        # because v0.3.0 made ``create_session`` keyword-only.
        self._session = await self._client.create_session(
            on_permission_request=PermissionHandler.approve_all,
            model=self.config.model,
            streaming=self.config.streaming,
        )
        self._is_started = True
        self._copilot_available = True

    except ImportError:
        self._copilot_available = False
        self._is_started = False
        logger.error("Copilot SDK is unavailable. Install featcopilot[llm].")
        raise

    except Exception as e:
        self._copilot_available = False
        self._is_started = False
        logger.error(f"Could not connect to Copilot: {e}")
        if self._client is not None:
            await self._client.stop()
            self._client = None
        raise

    return self

stop() async

Stop the Copilot client.

Source code in featcopilot/llm/copilot_client.py
async def stop(self) -> None:
    """Stop the Copilot client."""
    if self._session:
        # ``destroy()`` was renamed to ``disconnect()`` in the
        # Copilot SDK 0.3.x; ``destroy()`` still works but emits a
        # ``DeprecationWarning`` before being removed. Prefer the new
        # name and look up the legacy method only for older SDKs.
        disconnect = getattr(self._session, "disconnect", None)
        if disconnect is not None:
            await disconnect()
        else:
            destroy = getattr(self._session, "destroy", None)
            if destroy is None:
                raise RuntimeError("Copilot session has no supported cleanup method")
            await destroy()
    if self._client:
        await self._client.stop()
    self._is_started = False
    self._copilot_available = False
    self._session = None
    self._client = None
    self._plan_transport = 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/copilot_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
    )

    response = await self.send_prompt(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/copilot_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)

SyncCopilotFeatureClient

Synchronous wrapper for CopilotFeatureClient.

Source code in featcopilot/llm/copilot_client.py
class SyncCopilotFeatureClient:
    """Synchronous wrapper for CopilotFeatureClient."""

    def __init__(self, **kwargs) -> None:
        self._async_client = CopilotFeatureClient(**kwargs)
        self._loop: asyncio.AbstractEventLoop | None = None

    def _get_or_create_loop(self) -> asyncio.AbstractEventLoop:
        """Get or create a persistent event loop for this client."""
        if self._loop is None or self._loop.is_closed():
            self._loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self._loop)
        return self._loop

    def _run_async(self, coro: Coroutine[Any, Any, _T]) -> _T:
        """Run an async coroutine, handling various event loop scenarios."""
        if self._async_client.config.isolated_plan:
            # Each plan send owns startup through shutdown in one loop. Do not
            # patch the caller's active loop or retain a loop between attempts.
            timeout = self._async_client.config.timeout
            total_timeout = timeout + 2 * min(timeout, PLAN_CLEANUP_TIMEOUT) + 0.1
            running: concurrent.futures.Future[tuple[asyncio.AbstractEventLoop, asyncio.Task[Any]]] = (
                concurrent.futures.Future()
            )

            async def bounded() -> _T:
                task = asyncio.current_task()
                if task is not None:
                    running.set_result((asyncio.get_running_loop(), task))
                # The transport owns the request deadline. This outer guard
                # also bounds bridge-only work and allows its two cleanup steps.
                try:
                    return await asyncio.wait_for(coro, timeout=total_timeout)
                except (TimeoutError, asyncio.TimeoutError, concurrent.futures.TimeoutError) as exc:
                    contextual = plan_timeout_error(
                        exc, total_timeout, f"synchronous bridge (request timeout {timeout:g} seconds)"
                    )
                    if contextual is exc:
                        raise
                    raise contextual from exc

            try:
                asyncio.get_running_loop()
            except RuntimeError:
                return asyncio.run(bounded())
            executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
            future = executor.submit(asyncio.run, bounded())
            try:
                return future.result(timeout=total_timeout + 0.1)
            except BaseException as exc:
                if not future.done():
                    if running.done():
                        loop, task = running.result()
                        try:
                            loop.call_soon_threadsafe(task.cancel)
                        except RuntimeError:
                            logger.debug("Copilot plan worker loop closed before cancellation")
                    future.cancel()
                    if isinstance(exc, concurrent.futures.TimeoutError):
                        logger.warning("Copilot plan exceeded shutdown grace; SDK cancellation is cooperative")
                contextual = plan_timeout_error(
                    exc, total_timeout + 0.1, f"shutdown watchdog (request timeout {timeout:g} seconds)"
                )
                if contextual is not exc:
                    raise contextual from exc
                raise
            finally:
                # Do not turn the watchdog into an unbounded executor join.
                # A cancellation-resistant SDK may still outlive this call.
                executor.shutdown(wait=future.done(), cancel_futures=True)
        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:
            return self._get_or_create_loop().run_until_complete(coro)

        try:
            import nest_asyncio
        except ImportError:
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(self._run_in_new_loop, coro)
                return future.result(timeout=120)

        nest_asyncio.apply()
        return loop.run_until_complete(coro)

    def _run_in_new_loop(self, coro: Coroutine[Any, Any, _T]) -> _T:
        """Run coroutine in a fresh event loop."""
        loop = asyncio.new_event_loop()
        try:
            asyncio.set_event_loop(loop)
            return loop.run_until_complete(coro)
        finally:
            loop.close()

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

    def stop(self) -> None:
        """Stop the client and close its event loop."""
        self._run_async(self._async_client.stop())
        # Close our loop if it exists
        if self._loop is not None and not self._loop.is_closed():
            self._loop.close()
            self._loop = None

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

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

    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/copilot_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/copilot_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)

Send a prompt and get a response.

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

start()

Start the client.

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

stop()

Stop the client and close its event loop.

Source code in featcopilot/llm/copilot_client.py
def stop(self) -> None:
    """Stop the client and close its event loop."""
    self._run_async(self._async_client.stop())
    # Close our loop if it exists
    if self._loop is not None and not self._loop.is_closed():
        self._loop.close()
        self._loop = None

suggest_features(**kwargs)

Get feature suggestions.

Source code in featcopilot/llm/copilot_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/copilot_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))