openapiopenai 1.0.0__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 (73) hide show
  1. openapiopenai/__init__.py +93 -0
  2. openapiopenai/api/__init__.py +5 -0
  3. openapiopenai/api/open_ai_api.py +6334 -0
  4. openapiopenai/api_client.py +759 -0
  5. openapiopenai/api_response.py +21 -0
  6. openapiopenai/configuration.py +437 -0
  7. openapiopenai/exceptions.py +200 -0
  8. openapiopenai/models/__init__.py +76 -0
  9. openapiopenai/models/chat_completion_functions.py +92 -0
  10. openapiopenai/models/chat_completion_request_message.py +105 -0
  11. openapiopenai/models/chat_completion_request_message_function_call.py +90 -0
  12. openapiopenai/models/chat_completion_response_message.py +108 -0
  13. openapiopenai/models/chat_completion_stream_response_delta.py +111 -0
  14. openapiopenai/models/create_chat_completion_request.py +178 -0
  15. openapiopenai/models/create_chat_completion_request_function_call.py +141 -0
  16. openapiopenai/models/create_chat_completion_request_function_call_one_of.py +88 -0
  17. openapiopenai/models/create_chat_completion_request_model.py +144 -0
  18. openapiopenai/models/create_chat_completion_request_stop.py +145 -0
  19. openapiopenai/models/create_chat_completion_response.py +110 -0
  20. openapiopenai/models/create_chat_completion_response_choices_inner.py +106 -0
  21. openapiopenai/models/create_chat_completion_stream_response.py +104 -0
  22. openapiopenai/models/create_chat_completion_stream_response_choices_inner.py +106 -0
  23. openapiopenai/models/create_completion_request.py +201 -0
  24. openapiopenai/models/create_completion_request_model.py +144 -0
  25. openapiopenai/models/create_completion_request_prompt.py +185 -0
  26. openapiopenai/models/create_completion_request_stop.py +151 -0
  27. openapiopenai/models/create_completion_response.py +110 -0
  28. openapiopenai/models/create_completion_response_choices_inner.py +110 -0
  29. openapiopenai/models/create_completion_response_choices_inner_logprobs.py +94 -0
  30. openapiopenai/models/create_completion_response_usage.py +92 -0
  31. openapiopenai/models/create_edit_request.py +123 -0
  32. openapiopenai/models/create_edit_request_model.py +144 -0
  33. openapiopenai/models/create_edit_response.py +106 -0
  34. openapiopenai/models/create_edit_response_choices_inner.py +113 -0
  35. openapiopenai/models/create_embedding_request.py +100 -0
  36. openapiopenai/models/create_embedding_request_input.py +179 -0
  37. openapiopenai/models/create_embedding_request_model.py +144 -0
  38. openapiopenai/models/create_embedding_response.py +106 -0
  39. openapiopenai/models/create_embedding_response_data_inner.py +92 -0
  40. openapiopenai/models/create_embedding_response_usage.py +90 -0
  41. openapiopenai/models/create_fine_tune_request.py +170 -0
  42. openapiopenai/models/create_fine_tune_request_model.py +150 -0
  43. openapiopenai/models/create_image_request.py +132 -0
  44. openapiopenai/models/create_moderation_request.py +98 -0
  45. openapiopenai/models/create_moderation_request_input.py +144 -0
  46. openapiopenai/models/create_moderation_request_model.py +144 -0
  47. openapiopenai/models/create_moderation_response.py +100 -0
  48. openapiopenai/models/create_moderation_response_results_inner.py +100 -0
  49. openapiopenai/models/create_moderation_response_results_inner_categories.py +100 -0
  50. openapiopenai/models/create_moderation_response_results_inner_category_scores.py +100 -0
  51. openapiopenai/models/create_transcription_request_model.py +144 -0
  52. openapiopenai/models/create_transcription_response.py +88 -0
  53. openapiopenai/models/create_translation_response.py +88 -0
  54. openapiopenai/models/delete_file_response.py +92 -0
  55. openapiopenai/models/delete_model_response.py +92 -0
  56. openapiopenai/models/error.py +104 -0
  57. openapiopenai/models/error_response.py +92 -0
  58. openapiopenai/models/fine_tune.py +147 -0
  59. openapiopenai/models/fine_tune_event.py +94 -0
  60. openapiopenai/models/images_response.py +98 -0
  61. openapiopenai/models/images_response_data_inner.py +90 -0
  62. openapiopenai/models/list_files_response.py +98 -0
  63. openapiopenai/models/list_fine_tune_events_response.py +98 -0
  64. openapiopenai/models/list_fine_tunes_response.py +98 -0
  65. openapiopenai/models/list_models_response.py +98 -0
  66. openapiopenai/models/model.py +94 -0
  67. openapiopenai/models/open_ai_file.py +107 -0
  68. openapiopenai/py.typed +0 -0
  69. openapiopenai/rest.py +256 -0
  70. openapiopenai-1.0.0.dist-info/METADATA +19 -0
  71. openapiopenai-1.0.0.dist-info/RECORD +73 -0
  72. openapiopenai-1.0.0.dist-info/WHEEL +5 -0
  73. openapiopenai-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,201 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ OpenAI API
5
+
6
+ APIs for sampling from and fine-tuning language models
7
+
8
+ The version of the OpenAPI document: 2.0.0
9
+ Contact: blah+oapicf@cliffano.com
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+
16
+ from __future__ import annotations
17
+ import pprint
18
+ import re # noqa: F401
19
+ import json
20
+
21
+ from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr
22
+ from typing import Any, ClassVar, Dict, List, Optional, Union
23
+ from typing_extensions import Annotated
24
+ from openapiopenai.models.create_completion_request_model import CreateCompletionRequestModel
25
+ from openapiopenai.models.create_completion_request_prompt import CreateCompletionRequestPrompt
26
+ from openapiopenai.models.create_completion_request_stop import CreateCompletionRequestStop
27
+ from typing import Optional, Set
28
+ from typing_extensions import Self
29
+
30
+ class CreateCompletionRequest(BaseModel):
31
+ """
32
+ CreateCompletionRequest
33
+ """ # noqa: E501
34
+ model: CreateCompletionRequestModel
35
+ prompt: Optional[CreateCompletionRequestPrompt]
36
+ suffix: Optional[StrictStr] = Field(default=None, description="The suffix that comes after a completion of inserted text.")
37
+ max_tokens: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=16, description="The maximum number of [tokens](/tokenizer) to generate in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb) for counting tokens. ")
38
+ temperature: Optional[Union[Annotated[float, Field(le=2, strict=True, ge=0)], Annotated[int, Field(le=2, strict=True, ge=0)]]] = Field(default=1, description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. ")
39
+ top_p: Optional[Union[Annotated[float, Field(le=1, strict=True, ge=0)], Annotated[int, Field(le=1, strict=True, ge=0)]]] = Field(default=1, description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. ")
40
+ n: Optional[Annotated[int, Field(le=128, strict=True, ge=1)]] = Field(default=1, description="How many completions to generate for each prompt. **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. ")
41
+ stream: Optional[StrictBool] = Field(default=False, description="Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb). ")
42
+ logprobs: Optional[Annotated[int, Field(le=5, strict=True, ge=0)]] = Field(default=None, description="Include the log probabilities on the `logprobs` most likely tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. ")
43
+ echo: Optional[StrictBool] = Field(default=False, description="Echo back the prompt in addition to the completion ")
44
+ stop: Optional[CreateCompletionRequestStop] = None
45
+ presence_penalty: Optional[Union[Annotated[float, Field(le=2, strict=True, ge=-2)], Annotated[int, Field(le=2, strict=True, ge=-2)]]] = Field(default=0, description="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. [See more information about frequency and presence penalties.](/docs/api-reference/parameter-details) ")
46
+ frequency_penalty: Optional[Union[Annotated[float, Field(le=2, strict=True, ge=-2)], Annotated[int, Field(le=2, strict=True, ge=-2)]]] = Field(default=0, description="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. [See more information about frequency and presence penalties.](/docs/api-reference/parameter-details) ")
47
+ best_of: Optional[Annotated[int, Field(le=20, strict=True, ge=0)]] = Field(default=1, description="Generates `best_of` completions server-side and returns the \"best\" (the one with the highest log probability per token). Results cannot be streamed. When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`. **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. ")
48
+ logit_bias: Optional[Dict[str, Any]] = Field(default=None, description="Modify the likelihood of specified tokens appearing in the completion. Accepts a json object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{\"50256\": -100}` to prevent the <|endoftext|> token from being generated. ")
49
+ user: Optional[StrictStr] = Field(default=None, description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). ")
50
+ __properties: ClassVar[List[str]] = ["model", "prompt", "suffix", "max_tokens", "temperature", "top_p", "n", "stream", "logprobs", "echo", "stop", "presence_penalty", "frequency_penalty", "best_of", "logit_bias", "user"]
51
+
52
+ model_config = ConfigDict(
53
+ populate_by_name=True,
54
+ validate_assignment=True,
55
+ protected_namespaces=(),
56
+ )
57
+
58
+
59
+ def to_str(self) -> str:
60
+ """Returns the string representation of the model using alias"""
61
+ return pprint.pformat(self.model_dump(by_alias=True))
62
+
63
+ def to_json(self) -> str:
64
+ """Returns the JSON representation of the model using alias"""
65
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
66
+ return json.dumps(self.to_dict())
67
+
68
+ @classmethod
69
+ def from_json(cls, json_str: str) -> Optional[Self]:
70
+ """Create an instance of CreateCompletionRequest from a JSON string"""
71
+ return cls.from_dict(json.loads(json_str))
72
+
73
+ def to_dict(self) -> Dict[str, Any]:
74
+ """Return the dictionary representation of the model using alias.
75
+
76
+ This has the following differences from calling pydantic's
77
+ `self.model_dump(by_alias=True)`:
78
+
79
+ * `None` is only added to the output dict for nullable fields that
80
+ were set at model initialization. Other fields with value `None`
81
+ are ignored.
82
+ """
83
+ excluded_fields: Set[str] = set([
84
+ ])
85
+
86
+ _dict = self.model_dump(
87
+ by_alias=True,
88
+ exclude=excluded_fields,
89
+ exclude_none=True,
90
+ )
91
+ # override the default output from pydantic by calling `to_dict()` of model
92
+ if self.model:
93
+ _dict['model'] = self.model.to_dict()
94
+ # override the default output from pydantic by calling `to_dict()` of prompt
95
+ if self.prompt:
96
+ _dict['prompt'] = self.prompt.to_dict()
97
+ # override the default output from pydantic by calling `to_dict()` of stop
98
+ if self.stop:
99
+ _dict['stop'] = self.stop.to_dict()
100
+ # set to None if prompt (nullable) is None
101
+ # and model_fields_set contains the field
102
+ if self.prompt is None and "prompt" in self.model_fields_set:
103
+ _dict['prompt'] = None
104
+
105
+ # set to None if suffix (nullable) is None
106
+ # and model_fields_set contains the field
107
+ if self.suffix is None and "suffix" in self.model_fields_set:
108
+ _dict['suffix'] = None
109
+
110
+ # set to None if max_tokens (nullable) is None
111
+ # and model_fields_set contains the field
112
+ if self.max_tokens is None and "max_tokens" in self.model_fields_set:
113
+ _dict['max_tokens'] = None
114
+
115
+ # set to None if temperature (nullable) is None
116
+ # and model_fields_set contains the field
117
+ if self.temperature is None and "temperature" in self.model_fields_set:
118
+ _dict['temperature'] = None
119
+
120
+ # set to None if top_p (nullable) is None
121
+ # and model_fields_set contains the field
122
+ if self.top_p is None and "top_p" in self.model_fields_set:
123
+ _dict['top_p'] = None
124
+
125
+ # set to None if n (nullable) is None
126
+ # and model_fields_set contains the field
127
+ if self.n is None and "n" in self.model_fields_set:
128
+ _dict['n'] = None
129
+
130
+ # set to None if stream (nullable) is None
131
+ # and model_fields_set contains the field
132
+ if self.stream is None and "stream" in self.model_fields_set:
133
+ _dict['stream'] = None
134
+
135
+ # set to None if logprobs (nullable) is None
136
+ # and model_fields_set contains the field
137
+ if self.logprobs is None and "logprobs" in self.model_fields_set:
138
+ _dict['logprobs'] = None
139
+
140
+ # set to None if echo (nullable) is None
141
+ # and model_fields_set contains the field
142
+ if self.echo is None and "echo" in self.model_fields_set:
143
+ _dict['echo'] = None
144
+
145
+ # set to None if stop (nullable) is None
146
+ # and model_fields_set contains the field
147
+ if self.stop is None and "stop" in self.model_fields_set:
148
+ _dict['stop'] = None
149
+
150
+ # set to None if presence_penalty (nullable) is None
151
+ # and model_fields_set contains the field
152
+ if self.presence_penalty is None and "presence_penalty" in self.model_fields_set:
153
+ _dict['presence_penalty'] = None
154
+
155
+ # set to None if frequency_penalty (nullable) is None
156
+ # and model_fields_set contains the field
157
+ if self.frequency_penalty is None and "frequency_penalty" in self.model_fields_set:
158
+ _dict['frequency_penalty'] = None
159
+
160
+ # set to None if best_of (nullable) is None
161
+ # and model_fields_set contains the field
162
+ if self.best_of is None and "best_of" in self.model_fields_set:
163
+ _dict['best_of'] = None
164
+
165
+ # set to None if logit_bias (nullable) is None
166
+ # and model_fields_set contains the field
167
+ if self.logit_bias is None and "logit_bias" in self.model_fields_set:
168
+ _dict['logit_bias'] = None
169
+
170
+ return _dict
171
+
172
+ @classmethod
173
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
174
+ """Create an instance of CreateCompletionRequest from a dict"""
175
+ if obj is None:
176
+ return None
177
+
178
+ if not isinstance(obj, dict):
179
+ return cls.model_validate(obj)
180
+
181
+ _obj = cls.model_validate({
182
+ "model": CreateCompletionRequestModel.from_dict(obj["model"]) if obj.get("model") is not None else None,
183
+ "prompt": CreateCompletionRequestPrompt.from_dict(obj["prompt"]) if obj.get("prompt") is not None else None,
184
+ "suffix": obj.get("suffix"),
185
+ "max_tokens": obj.get("max_tokens") if obj.get("max_tokens") is not None else 16,
186
+ "temperature": obj.get("temperature") if obj.get("temperature") is not None else 1,
187
+ "top_p": obj.get("top_p") if obj.get("top_p") is not None else 1,
188
+ "n": obj.get("n") if obj.get("n") is not None else 1,
189
+ "stream": obj.get("stream") if obj.get("stream") is not None else False,
190
+ "logprobs": obj.get("logprobs"),
191
+ "echo": obj.get("echo") if obj.get("echo") is not None else False,
192
+ "stop": CreateCompletionRequestStop.from_dict(obj["stop"]) if obj.get("stop") is not None else None,
193
+ "presence_penalty": obj.get("presence_penalty") if obj.get("presence_penalty") is not None else 0,
194
+ "frequency_penalty": obj.get("frequency_penalty") if obj.get("frequency_penalty") is not None else 0,
195
+ "best_of": obj.get("best_of") if obj.get("best_of") is not None else 1,
196
+ "logit_bias": obj.get("logit_bias"),
197
+ "user": obj.get("user")
198
+ })
199
+ return _obj
200
+
201
+
@@ -0,0 +1,144 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ OpenAI API
5
+
6
+ APIs for sampling from and fine-tuning language models
7
+
8
+ The version of the OpenAPI document: 2.0.0
9
+ Contact: blah+oapicf@cliffano.com
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+
16
+ from __future__ import annotations
17
+ import json
18
+ import pprint
19
+ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator
20
+ from typing import Any, List, Optional
21
+ from pydantic import StrictStr, Field
22
+ from typing import Union, List, Optional, Dict
23
+ from typing_extensions import Literal, Self
24
+
25
+ CREATECOMPLETIONREQUESTMODEL_ONE_OF_SCHEMAS = ["str"]
26
+
27
+ class CreateCompletionRequestModel(BaseModel):
28
+ """
29
+ ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.
30
+ """
31
+ # data type: str
32
+ oneof_schema_1_validator: Optional[StrictStr] = None
33
+ # data type: str
34
+ oneof_schema_2_validator: Optional[StrictStr] = None
35
+ actual_instance: Optional[Union[str]] = None
36
+ one_of_schemas: List[str] = Field(default=Literal["str"])
37
+
38
+ model_config = ConfigDict(
39
+ validate_assignment=True,
40
+ protected_namespaces=(),
41
+ )
42
+
43
+
44
+ def __init__(self, *args, **kwargs) -> None:
45
+ if args:
46
+ if len(args) > 1:
47
+ raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
48
+ if kwargs:
49
+ raise ValueError("If a position argument is used, keyword arguments cannot be used.")
50
+ super().__init__(actual_instance=args[0])
51
+ else:
52
+ super().__init__(**kwargs)
53
+
54
+ @field_validator('actual_instance')
55
+ def actual_instance_must_validate_oneof(cls, v):
56
+ instance = CreateCompletionRequestModel.model_construct()
57
+ error_messages = []
58
+ match = 0
59
+ # validate data type: str
60
+ try:
61
+ instance.oneof_schema_1_validator = v
62
+ match += 1
63
+ except (ValidationError, ValueError) as e:
64
+ error_messages.append(str(e))
65
+ # validate data type: str
66
+ try:
67
+ instance.oneof_schema_2_validator = v
68
+ match += 1
69
+ except (ValidationError, ValueError) as e:
70
+ error_messages.append(str(e))
71
+ if match > 1:
72
+ # more than 1 match
73
+ raise ValueError("Multiple matches found when setting `actual_instance` in CreateCompletionRequestModel with oneOf schemas: str. Details: " + ", ".join(error_messages))
74
+ elif match == 0:
75
+ # no match
76
+ raise ValueError("No match found when setting `actual_instance` in CreateCompletionRequestModel with oneOf schemas: str. Details: " + ", ".join(error_messages))
77
+ else:
78
+ return v
79
+
80
+ @classmethod
81
+ def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self:
82
+ return cls.from_json(json.dumps(obj))
83
+
84
+ @classmethod
85
+ def from_json(cls, json_str: str) -> Self:
86
+ """Returns the object represented by the json string"""
87
+ instance = cls.model_construct()
88
+ error_messages = []
89
+ match = 0
90
+
91
+ # deserialize data into str
92
+ try:
93
+ # validation
94
+ instance.oneof_schema_1_validator = json.loads(json_str)
95
+ # assign value to actual_instance
96
+ instance.actual_instance = instance.oneof_schema_1_validator
97
+ match += 1
98
+ except (ValidationError, ValueError) as e:
99
+ error_messages.append(str(e))
100
+ # deserialize data into str
101
+ try:
102
+ # validation
103
+ instance.oneof_schema_2_validator = json.loads(json_str)
104
+ # assign value to actual_instance
105
+ instance.actual_instance = instance.oneof_schema_2_validator
106
+ match += 1
107
+ except (ValidationError, ValueError) as e:
108
+ error_messages.append(str(e))
109
+
110
+ if match > 1:
111
+ # more than 1 match
112
+ raise ValueError("Multiple matches found when deserializing the JSON string into CreateCompletionRequestModel with oneOf schemas: str. Details: " + ", ".join(error_messages))
113
+ elif match == 0:
114
+ # no match
115
+ raise ValueError("No match found when deserializing the JSON string into CreateCompletionRequestModel with oneOf schemas: str. Details: " + ", ".join(error_messages))
116
+ else:
117
+ return instance
118
+
119
+ def to_json(self) -> str:
120
+ """Returns the JSON representation of the actual instance"""
121
+ if self.actual_instance is None:
122
+ return "null"
123
+
124
+ if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json):
125
+ return self.actual_instance.to_json()
126
+ else:
127
+ return json.dumps(self.actual_instance)
128
+
129
+ def to_dict(self) -> Optional[Union[Dict[str, Any], str]]:
130
+ """Returns the dict representation of the actual instance"""
131
+ if self.actual_instance is None:
132
+ return None
133
+
134
+ if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict):
135
+ return self.actual_instance.to_dict()
136
+ else:
137
+ # primitive type
138
+ return self.actual_instance
139
+
140
+ def to_str(self) -> str:
141
+ """Returns the string representation of the actual instance"""
142
+ return pprint.pformat(self.model_dump())
143
+
144
+
@@ -0,0 +1,185 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ OpenAI API
5
+
6
+ APIs for sampling from and fine-tuning language models
7
+
8
+ The version of the OpenAPI document: 2.0.0
9
+ Contact: blah+oapicf@cliffano.com
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+
16
+ from __future__ import annotations
17
+ import json
18
+ import pprint
19
+ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator
20
+ from typing import Any, List, Optional
21
+ from typing_extensions import Annotated
22
+ from pydantic import StrictStr, Field
23
+ from typing import Union, List, Optional, Dict
24
+ from typing_extensions import Literal, Self
25
+
26
+ CREATECOMPLETIONREQUESTPROMPT_ONE_OF_SCHEMAS = ["List[List[int]]", "List[int]", "List[str]", "str"]
27
+
28
+ class CreateCompletionRequestPrompt(BaseModel):
29
+ """
30
+ The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.
31
+ """
32
+ # data type: str
33
+ oneof_schema_1_validator: Optional[StrictStr] = ''
34
+ # data type: List[str]
35
+ oneof_schema_2_validator: Optional[List[StrictStr]] = None
36
+ # data type: List[int]
37
+ oneof_schema_3_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None
38
+ # data type: List[List[int]]
39
+ oneof_schema_4_validator: Optional[Annotated[List[Annotated[List[StrictInt], Field(min_length=1)]], Field(min_length=1)]] = None
40
+ actual_instance: Optional[Union[List[List[int]], List[int], List[str], str]] = None
41
+ one_of_schemas: List[str] = Field(default=Literal["List[List[int]]", "List[int]", "List[str]", "str"])
42
+
43
+ model_config = ConfigDict(
44
+ validate_assignment=True,
45
+ protected_namespaces=(),
46
+ )
47
+
48
+
49
+ def __init__(self, *args, **kwargs) -> None:
50
+ if args:
51
+ if len(args) > 1:
52
+ raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
53
+ if kwargs:
54
+ raise ValueError("If a position argument is used, keyword arguments cannot be used.")
55
+ super().__init__(actual_instance=args[0])
56
+ else:
57
+ super().__init__(**kwargs)
58
+
59
+ @field_validator('actual_instance')
60
+ def actual_instance_must_validate_oneof(cls, v):
61
+ if v is None:
62
+ return v
63
+
64
+ instance = CreateCompletionRequestPrompt.model_construct()
65
+ error_messages = []
66
+ match = 0
67
+ # validate data type: str
68
+ try:
69
+ instance.oneof_schema_1_validator = v
70
+ match += 1
71
+ except (ValidationError, ValueError) as e:
72
+ error_messages.append(str(e))
73
+ # validate data type: List[str]
74
+ try:
75
+ instance.oneof_schema_2_validator = v
76
+ match += 1
77
+ except (ValidationError, ValueError) as e:
78
+ error_messages.append(str(e))
79
+ # validate data type: List[int]
80
+ try:
81
+ instance.oneof_schema_3_validator = v
82
+ match += 1
83
+ except (ValidationError, ValueError) as e:
84
+ error_messages.append(str(e))
85
+ # validate data type: List[List[int]]
86
+ try:
87
+ instance.oneof_schema_4_validator = v
88
+ match += 1
89
+ except (ValidationError, ValueError) as e:
90
+ error_messages.append(str(e))
91
+ if match > 1:
92
+ # more than 1 match
93
+ raise ValueError("Multiple matches found when setting `actual_instance` in CreateCompletionRequestPrompt with oneOf schemas: List[List[int]], List[int], List[str], str. Details: " + ", ".join(error_messages))
94
+ elif match == 0:
95
+ # no match
96
+ raise ValueError("No match found when setting `actual_instance` in CreateCompletionRequestPrompt with oneOf schemas: List[List[int]], List[int], List[str], str. Details: " + ", ".join(error_messages))
97
+ else:
98
+ return v
99
+
100
+ @classmethod
101
+ def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self:
102
+ return cls.from_json(json.dumps(obj))
103
+
104
+ @classmethod
105
+ def from_json(cls, json_str: Optional[str]) -> Self:
106
+ """Returns the object represented by the json string"""
107
+ instance = cls.model_construct()
108
+ if json_str is None:
109
+ return instance
110
+
111
+ error_messages = []
112
+ match = 0
113
+
114
+ # deserialize data into str
115
+ try:
116
+ # validation
117
+ instance.oneof_schema_1_validator = json.loads(json_str)
118
+ # assign value to actual_instance
119
+ instance.actual_instance = instance.oneof_schema_1_validator
120
+ match += 1
121
+ except (ValidationError, ValueError) as e:
122
+ error_messages.append(str(e))
123
+ # deserialize data into List[str]
124
+ try:
125
+ # validation
126
+ instance.oneof_schema_2_validator = json.loads(json_str)
127
+ # assign value to actual_instance
128
+ instance.actual_instance = instance.oneof_schema_2_validator
129
+ match += 1
130
+ except (ValidationError, ValueError) as e:
131
+ error_messages.append(str(e))
132
+ # deserialize data into List[int]
133
+ try:
134
+ # validation
135
+ instance.oneof_schema_3_validator = json.loads(json_str)
136
+ # assign value to actual_instance
137
+ instance.actual_instance = instance.oneof_schema_3_validator
138
+ match += 1
139
+ except (ValidationError, ValueError) as e:
140
+ error_messages.append(str(e))
141
+ # deserialize data into List[List[int]]
142
+ try:
143
+ # validation
144
+ instance.oneof_schema_4_validator = json.loads(json_str)
145
+ # assign value to actual_instance
146
+ instance.actual_instance = instance.oneof_schema_4_validator
147
+ match += 1
148
+ except (ValidationError, ValueError) as e:
149
+ error_messages.append(str(e))
150
+
151
+ if match > 1:
152
+ # more than 1 match
153
+ raise ValueError("Multiple matches found when deserializing the JSON string into CreateCompletionRequestPrompt with oneOf schemas: List[List[int]], List[int], List[str], str. Details: " + ", ".join(error_messages))
154
+ elif match == 0:
155
+ # no match
156
+ raise ValueError("No match found when deserializing the JSON string into CreateCompletionRequestPrompt with oneOf schemas: List[List[int]], List[int], List[str], str. Details: " + ", ".join(error_messages))
157
+ else:
158
+ return instance
159
+
160
+ def to_json(self) -> str:
161
+ """Returns the JSON representation of the actual instance"""
162
+ if self.actual_instance is None:
163
+ return "null"
164
+
165
+ if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json):
166
+ return self.actual_instance.to_json()
167
+ else:
168
+ return json.dumps(self.actual_instance)
169
+
170
+ def to_dict(self) -> Optional[Union[Dict[str, Any], List[List[int]], List[int], List[str], str]]:
171
+ """Returns the dict representation of the actual instance"""
172
+ if self.actual_instance is None:
173
+ return None
174
+
175
+ if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict):
176
+ return self.actual_instance.to_dict()
177
+ else:
178
+ # primitive type
179
+ return self.actual_instance
180
+
181
+ def to_str(self) -> str:
182
+ """Returns the string representation of the actual instance"""
183
+ return pprint.pformat(self.model_dump())
184
+
185
+