airia 0.1.12__py3-none-any.whl → 0.1.14__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.
Files changed (58) hide show
  1. airia/client/_request_handler/__init__.py +4 -0
  2. airia/client/_request_handler/async_request_handler.py +272 -0
  3. airia/client/_request_handler/base_request_handler.py +108 -0
  4. airia/client/_request_handler/sync_request_handler.py +255 -0
  5. airia/client/async_client.py +25 -584
  6. airia/client/base_client.py +2 -209
  7. airia/client/conversations/__init__.py +4 -0
  8. airia/client/conversations/async_conversations.py +187 -0
  9. airia/client/conversations/base_conversations.py +135 -0
  10. airia/client/conversations/sync_conversations.py +182 -0
  11. airia/client/pipeline_execution/__init__.py +4 -0
  12. airia/client/pipeline_execution/async_pipeline_execution.py +178 -0
  13. airia/client/pipeline_execution/base_pipeline_execution.py +96 -0
  14. airia/client/pipeline_execution/sync_pipeline_execution.py +178 -0
  15. airia/client/pipelines_config/__init__.py +4 -0
  16. airia/client/pipelines_config/async_pipelines_config.py +127 -0
  17. airia/client/pipelines_config/base_pipelines_config.py +76 -0
  18. airia/client/pipelines_config/sync_pipelines_config.py +127 -0
  19. airia/client/project/__init__.py +4 -0
  20. airia/client/project/async_project.py +122 -0
  21. airia/client/project/base_project.py +74 -0
  22. airia/client/project/sync_project.py +120 -0
  23. airia/client/store/__init__.py +4 -0
  24. airia/client/store/async_store.py +377 -0
  25. airia/client/store/base_store.py +243 -0
  26. airia/client/store/sync_store.py +352 -0
  27. airia/client/sync_client.py +25 -563
  28. airia/constants.py +13 -2
  29. airia/exceptions.py +8 -8
  30. airia/logs.py +10 -32
  31. airia/types/__init__.py +0 -0
  32. airia/types/_request_data.py +29 -2
  33. airia/types/api/__init__.py +0 -19
  34. airia/types/api/conversations/__init__.py +3 -0
  35. airia/types/api/conversations/_conversations.py +115 -0
  36. airia/types/api/pipeline_execution/__init__.py +13 -0
  37. airia/types/api/pipeline_execution/_pipeline_execution.py +76 -0
  38. airia/types/api/pipelines_config/__init__.py +3 -0
  39. airia/types/api/pipelines_config/get_pipeline_config.py +401 -0
  40. airia/types/api/project/__init__.py +3 -0
  41. airia/types/api/project/get_projects.py +91 -0
  42. airia/types/api/store/__init__.py +4 -0
  43. airia/types/api/store/get_file.py +145 -0
  44. airia/types/api/store/get_files.py +21 -0
  45. airia/types/sse/__init__.py +8 -0
  46. airia/types/sse/sse_messages.py +209 -0
  47. airia/utils/sse_parser.py +40 -7
  48. airia-0.1.14.dist-info/METADATA +221 -0
  49. airia-0.1.14.dist-info/RECORD +55 -0
  50. airia/types/api/conversations.py +0 -14
  51. airia/types/api/get_pipeline_config.py +0 -183
  52. airia/types/api/get_projects.py +0 -35
  53. airia/types/api/pipeline_execution.py +0 -29
  54. airia-0.1.12.dist-info/METADATA +0 -705
  55. airia-0.1.12.dist-info/RECORD +0 -23
  56. {airia-0.1.12.dist-info → airia-0.1.14.dist-info}/WHEEL +0 -0
  57. {airia-0.1.12.dist-info → airia-0.1.14.dist-info}/licenses/LICENSE +0 -0
  58. {airia-0.1.12.dist-info → airia-0.1.14.dist-info}/top_level.txt +0 -0
@@ -1,8 +1,5 @@
1
- import asyncio
2
- import weakref
3
- from typing import Any, AsyncIterator, Dict, List, Literal, Optional, overload
1
+ from typing import Optional
4
2
 
5
- import aiohttp
6
3
  import loguru
7
4
 
8
5
  from ..constants import (
@@ -11,19 +8,13 @@ from ..constants import (
11
8
  DEFAULT_OPENAI_GATEWAY_URL,
12
9
  DEFAULT_TIMEOUT,
13
10
  )
14
- from ..exceptions import AiriaAPIError
15
- from ..types._api_version import ApiVersion
16
- from ..types._request_data import RequestData
17
- from ..types.api import (
18
- CreateConversationResponse,
19
- GetPipelineConfigResponse,
20
- PipelineExecutionAsyncStreamedResponse,
21
- PipelineExecutionDebugResponse,
22
- PipelineExecutionResponse,
23
- ProjectItem,
24
- )
25
- from ..utils.sse_parser import async_parse_sse_stream_chunked
11
+ from ._request_handler import AsyncRequestHandler
26
12
  from .base_client import AiriaBaseClient
13
+ from .conversations import AsyncConversations
14
+ from .pipeline_execution import AsyncPipelineExecution
15
+ from .pipelines_config import AsyncPipelinesConfig
16
+ from .project import AsyncProject
17
+ from .store import AsyncStore
27
18
 
28
19
 
29
20
  class AiriaAsyncClient(AiriaBaseClient):
@@ -58,32 +49,19 @@ class AiriaAsyncClient(AiriaBaseClient):
58
49
  custom_logger=custom_logger,
59
50
  )
60
51
 
61
- # Session will be initialized in __aenter__
62
- self.headers = {"Content-Type": "application/json"}
63
- self.session = aiohttp.ClientSession(headers=self.headers)
64
-
65
- # Register finalizer to clean up session when client is garbage collected
66
- self._finalizer = weakref.finalize(self, self._cleanup_session, self.session)
67
-
68
- @staticmethod
69
- def _cleanup_session(session: aiohttp.ClientSession):
70
- """Static method to clean up session - called by finalizer"""
71
- if session and not session.closed:
72
- # Create a new event loop if none exists
73
- try:
74
- loop = asyncio.get_event_loop()
75
- if loop.is_closed():
76
- raise RuntimeError("Event loop is closed")
77
- except RuntimeError:
78
- loop = asyncio.new_event_loop()
79
- asyncio.set_event_loop(loop)
80
-
81
- # Close the session
82
- if not loop.is_running():
83
- loop.run_until_complete(session.close())
84
- else:
85
- # If loop is running, schedule the close operation
86
- asyncio.create_task(session.close())
52
+ self._request_handler = AsyncRequestHandler(
53
+ logger=self.logger,
54
+ timeout=self.timeout,
55
+ base_url=self.base_url,
56
+ api_key=self.api_key,
57
+ bearer_token=self.bearer_token,
58
+ log_requests=self.log_requests,
59
+ )
60
+ self.pipeline_execution = AsyncPipelineExecution(self._request_handler)
61
+ self.pipelines_config = AsyncPipelinesConfig(self._request_handler)
62
+ self.project = AsyncProject(self._request_handler)
63
+ self.conversations = AsyncConversations(self._request_handler)
64
+ self.store = AsyncStore(self._request_handler)
87
65
 
88
66
  @classmethod
89
67
  def with_openai_gateway(
@@ -192,548 +170,11 @@ class AiriaAsyncClient(AiriaBaseClient):
192
170
  custom_logger=custom_logger,
193
171
  )
194
172
 
195
- def _handle_exception(
196
- self, e: aiohttp.ClientResponseError, url: str, correlation_id: str
197
- ):
198
- # Log the error response if enabled
199
- if self.log_requests:
200
- self.logger.error(
201
- f"API Error: {e.status} {e.message}\n"
202
- f"URL: {url}\n"
203
- f"Correlation ID: {correlation_id}"
204
- )
205
-
206
- # Extract error details from response
207
- error_message = e.message
208
-
209
- # Make sure sensitive auth information is not included in error messages
210
- sanitized_message = error_message
211
- if self.api_key and self.api_key in sanitized_message:
212
- sanitized_message = sanitized_message.replace(self.api_key, "[REDACTED]")
213
- if self.bearer_token and self.bearer_token in sanitized_message:
214
- sanitized_message = sanitized_message.replace(
215
- self.bearer_token, "[REDACTED]"
216
- )
217
-
218
- # Raise custom exception with status code and sanitized message
219
- raise AiriaAPIError(status_code=e.status, message=sanitized_message) from e
220
-
221
- async def _make_request(
222
- self, method: str, request_data: RequestData
223
- ) -> Dict[str, Any]:
224
- """
225
- Makes an asynchronous HTTP request to the Airia API.
226
-
227
- Args:
228
- method (str): The HTTP method (e.g., 'GET', 'POST')
229
- request_data: A dictionary containing the following request information:
230
- - url: The endpoint URL for the request
231
- - headers: HTTP headers to include in the request
232
- - payload: The JSON payload/body for the request
233
- - correlation_id: Unique identifier for request tracing
234
-
235
- Returns:
236
- resp ([Dict[str, Any]): The JSON response from the API as a dictionary.
237
-
238
- Raises:
239
- AiriaAPIError: If the API returns an error response, with details about the error
240
- aiohttp.ClientResponseError: For HTTP-related errors
241
-
242
- Note:
243
- This is an internal method used by other client methods to make API requests.
244
- It handles logging, error handling, and API key redaction in error messages.
245
- """
246
- try:
247
- # Make the request
248
- async with self.session.request(
249
- method=method,
250
- url=request_data.url,
251
- json=request_data.payload,
252
- params=request_data.params,
253
- headers=request_data.headers,
254
- timeout=self.timeout,
255
- ) as response:
256
- # Log the response if enabled
257
- if self.log_requests:
258
- self.logger.info(
259
- f"API Response: {response.status} {response.reason}\n"
260
- f"URL: {request_data.url}\n"
261
- f"Correlation ID: {request_data.correlation_id}"
262
- )
263
-
264
- # Check for HTTP errors
265
- response.raise_for_status()
266
-
267
- # Return the response as a dictionary
268
- return await response.json()
269
-
270
- except aiohttp.ClientResponseError as e:
271
- self._handle_exception(e, request_data.url, request_data.correlation_id)
272
-
273
- async def _make_request_stream(
274
- self, method: str, request_data: RequestData
275
- ) -> AsyncIterator[str]:
276
- """
277
- Makes an asynchronous HTTP request to the Airia API.
278
-
279
- Args:
280
- method (str): The HTTP method (e.g., 'GET', 'POST')
281
- request_data: A dictionary containing the following request information:
282
- - url: The endpoint URL for the request
283
- - headers: HTTP headers to include in the request
284
- - payload: The JSON payload/body for the request
285
- - correlation_id: Unique identifier for request tracing
286
-
287
- Yields:
288
- resp AsyncIterator[str]]: yields chunks of the response as they are received.
289
-
290
- Raises:
291
- AiriaAPIError: If the API returns an error response, with details about the error
292
- aiohttp.ClientResponseError: For HTTP-related errors
293
-
294
- Note:
295
- This is an internal method used by other client methods to make API requests.
296
- It handles logging, error handling, and API key redaction in error messages.
297
- """
298
- try:
299
- # Make the request
300
- async with self.session.request(
301
- method=method,
302
- url=request_data.url,
303
- json=request_data.payload,
304
- params=request_data.params,
305
- headers=request_data.headers,
306
- timeout=self.timeout,
307
- chunked=True,
308
- ) as response:
309
- # Log the response if enabled
310
- if self.log_requests:
311
- self.logger.info(
312
- f"API Response: {response.status} {response.reason}\n"
313
- f"URL: {request_data.url}\n"
314
- f"Correlation ID: {request_data.correlation_id}"
315
- )
316
-
317
- # Check for HTTP errors
318
- response.raise_for_status()
319
-
320
- # Yields the response content as a stream if streaming
321
- async for message in async_parse_sse_stream_chunked(
322
- response.content.iter_any()
323
- ):
324
- yield message
325
-
326
- except aiohttp.ClientResponseError as e:
327
- self._handle_exception(e, request_data.url, request_data.correlation_id)
328
-
329
- @overload
330
- async def execute_pipeline(
331
- self,
332
- pipeline_id: str,
333
- user_input: str,
334
- debug: Literal[False] = False,
335
- user_id: Optional[str] = None,
336
- conversation_id: Optional[str] = None,
337
- async_output: Literal[False] = False,
338
- include_tools_response: bool = False,
339
- images: Optional[List[str]] = None,
340
- files: Optional[List[str]] = None,
341
- data_source_folders: Optional[Dict[str, Any]] = None,
342
- data_source_files: Optional[Dict[str, Any]] = None,
343
- in_memory_messages: Optional[List[Dict[str, str]]] = None,
344
- current_date_time: Optional[str] = None,
345
- save_history: bool = True,
346
- additional_info: Optional[List[Any]] = None,
347
- prompt_variables: Optional[Dict[str, Any]] = None,
348
- correlation_id: Optional[str] = None,
349
- ) -> PipelineExecutionResponse: ...
350
-
351
- @overload
352
- async def execute_pipeline(
353
- self,
354
- pipeline_id: str,
355
- user_input: str,
356
- debug: Literal[True] = True,
357
- user_id: Optional[str] = None,
358
- conversation_id: Optional[str] = None,
359
- async_output: Literal[False] = False,
360
- include_tools_response: bool = False,
361
- images: Optional[List[str]] = None,
362
- files: Optional[List[str]] = None,
363
- data_source_folders: Optional[Dict[str, Any]] = None,
364
- data_source_files: Optional[Dict[str, Any]] = None,
365
- in_memory_messages: Optional[List[Dict[str, str]]] = None,
366
- current_date_time: Optional[str] = None,
367
- save_history: bool = True,
368
- additional_info: Optional[List[Any]] = None,
369
- prompt_variables: Optional[Dict[str, Any]] = None,
370
- correlation_id: Optional[str] = None,
371
- ) -> PipelineExecutionDebugResponse: ...
372
-
373
- @overload
374
- async def execute_pipeline(
375
- self,
376
- pipeline_id: str,
377
- user_input: str,
378
- debug: bool = False,
379
- user_id: Optional[str] = None,
380
- conversation_id: Optional[str] = None,
381
- async_output: Literal[True] = True,
382
- include_tools_response: bool = False,
383
- images: Optional[List[str]] = None,
384
- files: Optional[List[str]] = None,
385
- data_source_folders: Optional[Dict[str, Any]] = None,
386
- data_source_files: Optional[Dict[str, Any]] = None,
387
- in_memory_messages: Optional[List[Dict[str, str]]] = None,
388
- current_date_time: Optional[str] = None,
389
- save_history: bool = True,
390
- additional_info: Optional[List[Any]] = None,
391
- prompt_variables: Optional[Dict[str, Any]] = None,
392
- correlation_id: Optional[str] = None,
393
- ) -> PipelineExecutionAsyncStreamedResponse: ...
394
-
395
- async def execute_pipeline(
396
- self,
397
- pipeline_id: str,
398
- user_input: str,
399
- debug: bool = False,
400
- user_id: Optional[str] = None,
401
- conversation_id: Optional[str] = None,
402
- async_output: bool = False,
403
- include_tools_response: bool = False,
404
- images: Optional[List[str]] = None,
405
- files: Optional[List[str]] = None,
406
- data_source_folders: Optional[Dict[str, Any]] = None,
407
- data_source_files: Optional[Dict[str, Any]] = None,
408
- in_memory_messages: Optional[List[Dict[str, str]]] = None,
409
- current_date_time: Optional[str] = None,
410
- save_history: bool = True,
411
- additional_info: Optional[List[Any]] = None,
412
- prompt_variables: Optional[Dict[str, Any]] = None,
413
- correlation_id: Optional[str] = None,
414
- ) -> Dict[str, Any]:
415
- """
416
- Execute a pipeline with the provided input asynchronously.
417
-
418
- Args:
419
- pipeline_id: The ID of the pipeline to execute.
420
- user_input: input text to process.
421
- debug: Whether debug mode execution is enabled. Default is False.
422
- user_id: Optional ID of the user making the request (guid).
423
- conversation_id: Optional conversation ID (guid).
424
- async_output: Whether to stream the response. Default is False.
425
- include_tools_response: Whether to return the initial LLM tool result. Default is False.
426
- images: Optional list of images formatted as base64 strings.
427
- files: Optional list of files formatted as base64 strings.
428
- data_source_folders: Optional data source folders information.
429
- data_source_files: Optional data source files information.
430
- in_memory_messages: Optional list of in-memory messages, each with a role and message.
431
- current_date_time: Optional current date and time in ISO format.
432
- save_history: Whether to save the userInput and output to conversation history. Default is True.
433
- additional_info: Optional additional information.
434
- prompt_variables: Optional variables to be used in the prompt.
435
- correlation_id: Optional correlation ID for request tracing. If not provided,
436
- one will be generated automatically.
437
-
438
- Returns:
439
- The API response as a dictionary.
440
-
441
- Raises:
442
- AiriaAPIError: If the API request fails with details about the error.
443
- aiohttp.ClientError: For other request-related errors.
444
-
445
- Example:
446
- >>> client = AiriaAsyncClient(api_key="your_api_key")
447
- ... response = await client.execute_pipeline(
448
- ... pipeline_id="pipeline_123",
449
- ... user_input="Tell me about quantum computing"
450
- ... )
451
- >>> print(response.result)
452
- """
453
- request_data = self._pre_execute_pipeline(
454
- pipeline_id=pipeline_id,
455
- user_input=user_input,
456
- debug=debug,
457
- user_id=user_id,
458
- conversation_id=conversation_id,
459
- async_output=async_output,
460
- include_tools_response=include_tools_response,
461
- images=images,
462
- files=files,
463
- data_source_folders=data_source_folders,
464
- data_source_files=data_source_files,
465
- in_memory_messages=in_memory_messages,
466
- current_date_time=current_date_time,
467
- save_history=save_history,
468
- additional_info=additional_info,
469
- prompt_variables=prompt_variables,
470
- correlation_id=correlation_id,
471
- api_version=ApiVersion.V2.value,
472
- )
473
- resp = (
474
- self._make_request_stream(method="POST", request_data=request_data)
475
- if async_output
476
- else await self._make_request("POST", request_data=request_data)
477
- )
478
-
479
- if not async_output:
480
- if not debug:
481
- return PipelineExecutionResponse(**resp)
482
- return PipelineExecutionDebugResponse(**resp)
483
-
484
- return PipelineExecutionAsyncStreamedResponse(stream=resp)
485
-
486
- async def get_projects(
487
- self, correlation_id: Optional[str] = None
488
- ) -> List[ProjectItem]:
489
- """
490
- Retrieve a list of all projects accessible to the authenticated user.
491
-
492
- This method fetches comprehensive information about all projects that the
493
- current user has access to, including project metadata, creation details,
494
- and status information.
495
-
496
- Args:
497
- correlation_id (str, optional): A unique identifier for request tracing
498
- and logging. If not provided, one will be automatically generated.
499
-
500
- Returns:
501
- List[ProjectItem]: A list of ProjectItem objects containing project
502
- information. Returns an empty list if no projects are accessible
503
- or found.
504
-
505
- Raises:
506
- AiriaAPIError: If the API request fails, including cases where:
507
- - Authentication fails (401)
508
- - Access is forbidden (403)
509
- - Server errors (5xx)
510
-
511
- Example:
512
- ```python
513
- from airia import AiriaAsyncClient
514
-
515
- client = AiriaAsyncClient(api_key="your_api_key")
516
-
517
- # Get all accessible projects
518
- projects = await client.get_projects()
519
-
520
- for project in projects:
521
- print(f"Project: {project.name}")
522
- print(f"ID: {project.id}")
523
- print(f"Description: {project.description}")
524
- print(f"Created: {project.created_at}")
525
- print("---")
526
- ```
527
-
528
- Note:
529
- The returned projects are filtered based on the authenticated user's
530
- permissions. Users will only see projects they have been granted
531
- access to.
532
- """
533
- request_data = self._pre_get_projects(
534
- correlation_id=correlation_id, api_version=ApiVersion.V1.value
535
- )
536
- resp = await self._make_request("GET", request_data)
537
-
538
- if "items" not in resp or len(resp["items"]) == 0:
539
- return []
540
-
541
- return [ProjectItem(**item) for item in resp["items"]]
542
-
543
- async def get_active_pipelines_ids(
544
- self, project_id: Optional[str] = None, correlation_id: Optional[str] = None
545
- ) -> List[str]:
546
- """
547
- Retrieve a list of active pipeline IDs.
548
-
549
- This method fetches the IDs of all active pipelines, optionally filtered by project.
550
- Active pipelines are those that are currently deployed and available for execution.
551
-
552
- Args:
553
- project_id (str, optional): The unique identifier of the project to filter
554
- pipelines by. If not provided, returns active pipelines from all projects
555
- accessible to the authenticated user.
556
- correlation_id (str, optional): A unique identifier for request tracing
557
- and logging. If not provided, one will be automatically generated.
558
-
559
- Returns:
560
- List[str]: A list of pipeline IDs that are currently active. Returns an
561
- empty list if no active pipelines are found.
562
-
563
- Raises:
564
- AiriaAPIError: If the API request fails, including cases where:
565
- - The project_id doesn't exist (404)
566
- - Authentication fails (401)
567
- - Access is forbidden (403)
568
- - Server errors (5xx)
569
-
570
- Example:
571
- ```python
572
- from airia import AiriaAsyncClient
573
-
574
- client = AiriaAsyncClient(api_key="your_api_key")
575
-
576
- # Get all active pipeline IDs
577
- pipeline_ids = await client.get_active_pipelines_ids()
578
- print(f"Found {len(pipeline_ids)} active pipelines")
579
-
580
- # Get active pipeline IDs for a specific project
581
- project_pipelines = await client.get_active_pipelines_ids(
582
- project_id="your_project_id"
583
- )
584
- print(f"Project has {len(project_pipelines)} active pipelines")
585
- ```
586
-
587
- Note:
588
- Only pipelines with active versions are returned. Inactive or archived
589
- pipelines are not included in the results.
173
+ async def close(self):
590
174
  """
591
- request_data = self._pre_get_active_pipelines_ids(
592
- project_id=project_id,
593
- correlation_id=correlation_id,
594
- api_version=ApiVersion.V1.value,
595
- )
596
- resp = await self._make_request("GET", request_data)
597
-
598
- if "items" not in resp or len(resp["items"]) == 0:
599
- return []
175
+ Closes the aiohttp session to free up system resources.
600
176
 
601
- pipeline_ids = [r["activeVersion"]["pipelineId"] for r in resp["items"]]
602
-
603
- return pipeline_ids
604
-
605
- async def get_pipeline_config(
606
- self, pipeline_id: str, correlation_id: Optional[str] = None
607
- ) -> GetPipelineConfigResponse:
177
+ This method should be called when the RequestHandler is no longer needed to ensure
178
+ proper cleanup of the underlying session and its resources.
608
179
  """
609
- Retrieve configuration details for a specific pipeline.
610
-
611
- This method fetches comprehensive information about a pipeline including its
612
- deployment details, execution statistics, version information, and metadata.
613
-
614
- Args:
615
- pipeline_id (str): The unique identifier of the pipeline to retrieve
616
- configuration for.
617
- correlation_id (str, optional): A unique identifier for request tracing
618
- and logging. If not provided, one will be automatically generated.
619
-
620
- Returns:
621
- GetPipelineConfigResponse: A response object containing the pipeline
622
- configuration.
623
-
624
- Raises:
625
- AiriaAPIError: If the API request fails, including cases where:
626
- - The pipeline_id doesn't exist (404)
627
- - Authentication fails (401)
628
- - Access is forbidden (403)
629
- - Server errors (5xx)
630
-
631
- Example:
632
- ```python
633
- from airia import AiriaAsyncClient
634
-
635
- client = AiriaAsyncClient(api_key="your_api_key")
636
-
637
- # Get pipeline configuration
638
- config = await client.get_pipeline_config(
639
- pipeline_id="your_pipeline_id"
640
- )
641
-
642
- print(f"Pipeline: {config.deployment_name}")
643
- print(f"Description: {config.deployment_description}")
644
- print(f"Success rate: {config.execution_stats.success_count}")
645
- print(f"Active version: {config.active_version.version_number}")
646
- ```
647
-
648
- Note:
649
- This method only retrieves configuration information and does not
650
- execute the pipeline. Use execute_pipeline() to run the pipeline.
651
- """
652
- request_data = self._pre_get_pipeline_config(
653
- pipeline_id=pipeline_id,
654
- correlation_id=correlation_id,
655
- api_version=ApiVersion.V1.value,
656
- )
657
- resp = await self._make_request("GET", request_data)
658
-
659
- return GetPipelineConfigResponse(**resp)
660
-
661
- async def create_conversation(
662
- self,
663
- user_id: str,
664
- title: Optional[str] = None,
665
- deployment_id: Optional[str] = None,
666
- data_source_files: Dict[str, Any] = {},
667
- is_bookmarked: bool = False,
668
- correlation_id: Optional[str] = None,
669
- ) -> CreateConversationResponse:
670
- """
671
- Create a new conversation.
672
-
673
- Args:
674
- user_id (str): The unique identifier of the user creating the conversation.
675
- title (str, optional): The title for the conversation. If not provided,
676
- the conversation will be created without a title.
677
- deployment_id (str, optional): The unique identifier of the deployment
678
- to associate with the conversation. If not provided, the conversation
679
- will not be associated with any specific deployment.
680
- data_source_files (dict): Configuration for data source files
681
- to be associated with the conversation. If not provided, no data
682
- source files will be associated.
683
- is_bookmarked (bool): Whether the conversation should be bookmarked.
684
- Defaults to False.
685
- correlation_id (str, optional): A unique identifier for request tracing
686
- and logging. If not provided, one will be automatically generated.
687
-
688
- Returns:
689
- CreateConversationResponse: A response object containing the created
690
- conversation details including its ID, creation timestamp, and
691
- all provided parameters.
692
-
693
- Raises:
694
- AiriaAPIError: If the API request fails, including cases where:
695
- - The user_id doesn't exist (404)
696
- - The deployment_id is invalid (404)
697
- - Authentication fails (401)
698
- - Access is forbidden (403)
699
- - Server errors (5xx)
700
-
701
- Example:
702
- ```python
703
- from airia import AiriaAsyncClient
704
-
705
- client = AiriaAsyncClient(api_key="your_api_key")
706
-
707
- # Create a basic conversation
708
- conversation = await client.create_conversation(
709
- user_id="user_123"
710
- )
711
- print(f"Created conversation: {conversation.conversation_id}")
712
-
713
- # Create a conversation with all options
714
- conversation = await client.create_conversation(
715
- user_id="user_123",
716
- title="My Research Session",
717
- deployment_id="deployment_456",
718
- data_source_files={"documents": ["doc1.pdf", "doc2.txt"]},
719
- is_bookmarked=True
720
- )
721
- print(f"Created bookmarked conversation: {conversation.conversation_id}")
722
- ```
723
-
724
- Note:
725
- The user_id is required and must correspond to a valid user in the system.
726
- All other parameters are optional and can be set to None or their default values.
727
- """
728
- request_data = self._pre_create_conversation(
729
- user_id=user_id,
730
- title=title,
731
- deployment_id=deployment_id,
732
- data_source_files=data_source_files,
733
- is_bookmarked=is_bookmarked,
734
- correlation_id=correlation_id,
735
- api_version=ApiVersion.V1.value,
736
- )
737
- resp = await self._make_request("POST", request_data)
738
-
739
- return CreateConversationResponse(**resp)
180
+ await self._request_handler.close()