truefoundry 0.5.0rc7__py3-none-any.whl → 0.5.1rc2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of truefoundry might be problematic. Click here for more details.
- truefoundry/common/utils.py +73 -1
- truefoundry/deploy/__init__.py +5 -0
- truefoundry/deploy/cli/cli.py +2 -0
- truefoundry/deploy/cli/commands/__init__.py +1 -0
- truefoundry/deploy/cli/commands/deploy_init_command.py +22 -0
- truefoundry/deploy/lib/dao/application.py +2 -1
- truefoundry/deploy/v2/lib/patched_models.py +8 -0
- truefoundry/ml/__init__.py +14 -12
- truefoundry/ml/autogen/client/__init__.py +5 -0
- truefoundry/ml/autogen/client/api/mlfoundry_artifacts_api.py +161 -0
- truefoundry/ml/autogen/client/models/__init__.py +5 -0
- truefoundry/ml/autogen/client/models/artifact_version_manifest.py +2 -2
- truefoundry/ml/autogen/client/models/export_deployment_files_request_dto.py +82 -0
- truefoundry/ml/autogen/client/models/infer_method_name.py +34 -0
- truefoundry/ml/autogen/client/models/model_server.py +34 -0
- truefoundry/ml/autogen/client/models/model_version_environment.py +1 -1
- truefoundry/ml/autogen/client/models/model_version_manifest.py +3 -3
- truefoundry/ml/autogen/client/models/sklearn_framework.py +17 -1
- truefoundry/ml/autogen/client/models/transformers_framework.py +2 -2
- truefoundry/ml/autogen/client/models/xg_boost_framework.py +6 -1
- truefoundry/ml/autogen/client_README.md +4 -0
- truefoundry/ml/autogen/entities/artifacts.py +29 -7
- truefoundry/ml/cli/commands/model_init.py +97 -0
- truefoundry/ml/cli/utils.py +34 -0
- truefoundry/ml/log_types/artifacts/model.py +63 -24
- truefoundry/ml/log_types/artifacts/utils.py +37 -1
- truefoundry/ml/mlfoundry_api.py +74 -78
- truefoundry/ml/mlfoundry_run.py +0 -30
- truefoundry/ml/model_framework.py +257 -3
- truefoundry/ml/validation_utils.py +2 -0
- {truefoundry-0.5.0rc7.dist-info → truefoundry-0.5.1rc2.dist-info}/METADATA +1 -5
- {truefoundry-0.5.0rc7.dist-info → truefoundry-0.5.1rc2.dist-info}/RECORD +34 -46
- truefoundry/deploy/function_service/__init__.py +0 -3
- truefoundry/deploy/function_service/__main__.py +0 -27
- truefoundry/deploy/function_service/app.py +0 -92
- truefoundry/deploy/function_service/build.py +0 -45
- truefoundry/deploy/function_service/remote/__init__.py +0 -6
- truefoundry/deploy/function_service/remote/context.py +0 -3
- truefoundry/deploy/function_service/remote/method.py +0 -67
- truefoundry/deploy/function_service/remote/remote.py +0 -144
- truefoundry/deploy/function_service/route.py +0 -137
- truefoundry/deploy/function_service/service.py +0 -113
- truefoundry/deploy/function_service/utils.py +0 -53
- truefoundry/langchain/__init__.py +0 -12
- truefoundry/langchain/deprecated.py +0 -302
- truefoundry/langchain/truefoundry_chat.py +0 -130
- truefoundry/langchain/truefoundry_embeddings.py +0 -171
- truefoundry/langchain/truefoundry_llm.py +0 -106
- truefoundry/langchain/utils.py +0 -44
- truefoundry/ml/log_types/artifacts/model_extras.py +0 -48
- {truefoundry-0.5.0rc7.dist-info → truefoundry-0.5.1rc2.dist-info}/WHEEL +0 -0
- {truefoundry-0.5.0rc7.dist-info → truefoundry-0.5.1rc2.dist-info}/entry_points.txt +0 -0
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
from typing import Any, Dict, List, Optional
|
|
2
|
-
|
|
3
|
-
from langchain.chat_models.base import SimpleChatModel
|
|
4
|
-
from langchain.pydantic_v1 import Extra, Field, root_validator
|
|
5
|
-
from langchain.schema.messages import (
|
|
6
|
-
AIMessage,
|
|
7
|
-
BaseMessage,
|
|
8
|
-
ChatMessage,
|
|
9
|
-
HumanMessage,
|
|
10
|
-
SystemMessage,
|
|
11
|
-
)
|
|
12
|
-
|
|
13
|
-
from truefoundry.common.request_utils import requests_retry_session
|
|
14
|
-
from truefoundry.langchain.utils import (
|
|
15
|
-
validate_tfy_environment,
|
|
16
|
-
)
|
|
17
|
-
from truefoundry.logger import logger
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
class TrueFoundryChat(SimpleChatModel):
|
|
21
|
-
"""`TrueFoundry LLM Gateway` chat models API.
|
|
22
|
-
|
|
23
|
-
To use, you must have the environment variable ``TFY_API_KEY`` set with your API key and ``TFY_HOST`` set with your host or pass it as a named parameter to the constructor.
|
|
24
|
-
"""
|
|
25
|
-
|
|
26
|
-
model: str = Field(description="The model to use for chat.")
|
|
27
|
-
"""The model to use for chat."""
|
|
28
|
-
tfy_llm_gateway_url: Optional[str] = Field(default=None)
|
|
29
|
-
"""TrueFoundry LLM Gateway endpoint URL. Automatically inferred from env var `TFY_LLM_GATEWAY_URL` if not provided."""
|
|
30
|
-
tfy_api_key: Optional[str] = Field(default=None)
|
|
31
|
-
"""TrueFoundry API Key. Automatically inferred from env var `TFY_API_KEY` if not provided."""
|
|
32
|
-
model_parameters: Optional[dict] = Field(default_factory=dict)
|
|
33
|
-
"""Model parameters"""
|
|
34
|
-
request_timeout: int = Field(default=30)
|
|
35
|
-
"""The timeout for the request in seconds."""
|
|
36
|
-
max_retries: int = Field(default=5)
|
|
37
|
-
"""The number of retries for HTTP requests."""
|
|
38
|
-
retry_backoff_factor: float = Field(default=0.3)
|
|
39
|
-
"""The backoff factor for exponential backoff during retries."""
|
|
40
|
-
system_prompt: str = Field(default="You are a AI assistant")
|
|
41
|
-
|
|
42
|
-
class Config:
|
|
43
|
-
"""Configuration for this pydantic object."""
|
|
44
|
-
|
|
45
|
-
extra = Extra.forbid
|
|
46
|
-
allow_population_by_field_name = True
|
|
47
|
-
|
|
48
|
-
@root_validator()
|
|
49
|
-
def validate_environment(cls, values: Dict) -> Dict:
|
|
50
|
-
values = validate_tfy_environment(values)
|
|
51
|
-
if not values["tfy_api_key"]:
|
|
52
|
-
raise ValueError(
|
|
53
|
-
"Did not find `tfy_api_key`, please add an environment variable"
|
|
54
|
-
" `TFY_API_KEY` which contains it, or pass"
|
|
55
|
-
" `tfy_api_key` as a named parameter."
|
|
56
|
-
)
|
|
57
|
-
if not values["tfy_llm_gateway_url"]:
|
|
58
|
-
raise ValueError(
|
|
59
|
-
"Did not find `tfy_llm_gateway_url`, please add an environment variable"
|
|
60
|
-
" `TFY_LLM_GATEWAY_URL` which contains it, or pass"
|
|
61
|
-
" `tfy_llm_gateway_url` as a named parameter."
|
|
62
|
-
)
|
|
63
|
-
return values
|
|
64
|
-
|
|
65
|
-
@property
|
|
66
|
-
def _llm_type(self) -> str:
|
|
67
|
-
"""Return type of chat model."""
|
|
68
|
-
return "truefoundry-chat"
|
|
69
|
-
|
|
70
|
-
def _call(
|
|
71
|
-
self,
|
|
72
|
-
messages: List[BaseMessage],
|
|
73
|
-
stop: Optional[List[str]] = None,
|
|
74
|
-
**kwargs: Any,
|
|
75
|
-
) -> str:
|
|
76
|
-
if len(messages) == 0:
|
|
77
|
-
raise ValueError("No messages provided to chat.")
|
|
78
|
-
|
|
79
|
-
if not isinstance(messages[0], SystemMessage):
|
|
80
|
-
messages.insert(0, SystemMessage(content=self.system_prompt))
|
|
81
|
-
|
|
82
|
-
message_dicts = [
|
|
83
|
-
TrueFoundryChat._convert_message_to_dict(message) for message in messages
|
|
84
|
-
]
|
|
85
|
-
|
|
86
|
-
payload = {**self.model_parameters} if self.model_parameters else {}
|
|
87
|
-
|
|
88
|
-
if stop:
|
|
89
|
-
payload["stop_sequences"] = stop
|
|
90
|
-
|
|
91
|
-
payload["messages"] = message_dicts
|
|
92
|
-
payload["model"] = self.model
|
|
93
|
-
|
|
94
|
-
session = requests_retry_session(
|
|
95
|
-
retries=self.max_retries, backoff_factor=self.retry_backoff_factor
|
|
96
|
-
)
|
|
97
|
-
|
|
98
|
-
url = f"{self.tfy_llm_gateway_url}/openai/chat/completions"
|
|
99
|
-
logger.debug(f"Chat using - model: {self.model} at endpoint: {url}")
|
|
100
|
-
response = session.post(
|
|
101
|
-
url=url,
|
|
102
|
-
json=payload,
|
|
103
|
-
headers={
|
|
104
|
-
"Authorization": f"Bearer {self.tfy_api_key}",
|
|
105
|
-
},
|
|
106
|
-
timeout=self.request_timeout,
|
|
107
|
-
)
|
|
108
|
-
response.raise_for_status()
|
|
109
|
-
output = response.json()
|
|
110
|
-
return output["choices"][0]["message"]["content"]
|
|
111
|
-
|
|
112
|
-
@staticmethod
|
|
113
|
-
def _convert_message_to_dict(message: BaseMessage) -> dict:
|
|
114
|
-
if isinstance(message, ChatMessage):
|
|
115
|
-
message_dict = {"role": message.role, "content": message.content}
|
|
116
|
-
elif isinstance(message, HumanMessage):
|
|
117
|
-
message_dict = {"role": "user", "content": message.content}
|
|
118
|
-
elif isinstance(message, AIMessage):
|
|
119
|
-
message_dict = {"role": "assistant", "content": message.content}
|
|
120
|
-
elif isinstance(message, SystemMessage):
|
|
121
|
-
message_dict = {"role": "system", "content": message.content}
|
|
122
|
-
else:
|
|
123
|
-
raise ValueError(f"Got unknown message type: {message}")
|
|
124
|
-
if message.additional_kwargs:
|
|
125
|
-
logger.debug(
|
|
126
|
-
"Additional message arguments are unsupported by TrueFoundry LLM Gateway "
|
|
127
|
-
" and will be ignored: %s",
|
|
128
|
-
message.additional_kwargs,
|
|
129
|
-
)
|
|
130
|
-
return message_dict
|
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
import concurrent.futures
|
|
2
|
-
import math
|
|
3
|
-
from typing import Dict, List, Optional
|
|
4
|
-
|
|
5
|
-
import tqdm
|
|
6
|
-
from langchain.embeddings.base import Embeddings
|
|
7
|
-
from langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator
|
|
8
|
-
|
|
9
|
-
from truefoundry.common.request_utils import requests_retry_session
|
|
10
|
-
from truefoundry.langchain.utils import (
|
|
11
|
-
validate_tfy_environment,
|
|
12
|
-
)
|
|
13
|
-
from truefoundry.logger import logger
|
|
14
|
-
|
|
15
|
-
EMBEDDER_BATCH_SIZE = 32
|
|
16
|
-
PARALLEL_WORKERS = 4
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class TrueFoundryEmbeddings(BaseModel, Embeddings):
|
|
20
|
-
"""`TrueFoundry LLM Gateway` embedding models API.
|
|
21
|
-
|
|
22
|
-
To use, you must have the environment variable ``TFY_API_KEY`` set with your API key and ``TFY_HOST`` set with your host or pass it
|
|
23
|
-
as a named parameter to the constructor.
|
|
24
|
-
"""
|
|
25
|
-
|
|
26
|
-
model: str = Field(description="The model to use for embedding.")
|
|
27
|
-
"""The model to use for embedding."""
|
|
28
|
-
tfy_llm_gateway_url: Optional[str] = Field(default=None)
|
|
29
|
-
"""TrueFoundry LLM Gateway endpoint URL. Automatically inferred from env var `TFY_LLM_GATEWAY_URL` if not provided."""
|
|
30
|
-
tfy_api_key: Optional[str] = Field(default=None)
|
|
31
|
-
"""TrueFoundry API Key. Automatically inferred from env var `TFY_API_KEY` if not provided."""
|
|
32
|
-
model_parameters: Optional[dict] = Field(default_factory=dict)
|
|
33
|
-
"""Model parameters"""
|
|
34
|
-
request_timeout: int = Field(default=30)
|
|
35
|
-
"""The timeout for the request in seconds."""
|
|
36
|
-
max_retries: int = Field(default=5)
|
|
37
|
-
"""The number of retries for HTTP requests."""
|
|
38
|
-
retry_backoff_factor: float = Field(default=0.3)
|
|
39
|
-
"""The backoff factor for exponential backoff during retries."""
|
|
40
|
-
batch_size: int = Field(default=EMBEDDER_BATCH_SIZE)
|
|
41
|
-
"""The batch size to use for embedding."""
|
|
42
|
-
parallel_workers: int = Field(default=PARALLEL_WORKERS)
|
|
43
|
-
"""The number of parallel workers to use for embedding."""
|
|
44
|
-
|
|
45
|
-
__private_attributes__ = {"_executor"}
|
|
46
|
-
|
|
47
|
-
class Config:
|
|
48
|
-
"""Configuration for this pydantic object."""
|
|
49
|
-
|
|
50
|
-
extra = Extra.forbid
|
|
51
|
-
allow_population_by_field_name = True
|
|
52
|
-
|
|
53
|
-
@root_validator()
|
|
54
|
-
def validate_environment(cls, values: Dict) -> Dict:
|
|
55
|
-
values = validate_tfy_environment(values)
|
|
56
|
-
if not values["tfy_api_key"]:
|
|
57
|
-
raise ValueError(
|
|
58
|
-
"Did not find `tfy_api_key`, please add an environment variable"
|
|
59
|
-
" `TFY_API_KEY` which contains it, or pass"
|
|
60
|
-
" `tfy_api_key` as a named parameter."
|
|
61
|
-
)
|
|
62
|
-
if not values["tfy_llm_gateway_url"]:
|
|
63
|
-
raise ValueError(
|
|
64
|
-
"Did not find `tfy_llm_gateway_url`, please add an environment variable"
|
|
65
|
-
" `TFY_LLM_GATEWAY_URL` which contains it, or pass"
|
|
66
|
-
" `tfy_llm_gateway_url` as a named parameter."
|
|
67
|
-
)
|
|
68
|
-
return values
|
|
69
|
-
|
|
70
|
-
def _init_private_attributes(self):
|
|
71
|
-
self._executor = concurrent.futures.ThreadPoolExecutor(
|
|
72
|
-
max_workers=self.parallel_workers
|
|
73
|
-
)
|
|
74
|
-
|
|
75
|
-
@property
|
|
76
|
-
def _llm_type(self) -> str:
|
|
77
|
-
"""Return type of embedding model."""
|
|
78
|
-
return "truefoundry-embeddings"
|
|
79
|
-
|
|
80
|
-
def __del__(self):
|
|
81
|
-
"""
|
|
82
|
-
Destructor method to clean up the executor when the object is deleted.
|
|
83
|
-
|
|
84
|
-
Returns:
|
|
85
|
-
None
|
|
86
|
-
"""
|
|
87
|
-
self._executor.shutdown()
|
|
88
|
-
|
|
89
|
-
def _remote_embed(self, texts, query_mode=False):
|
|
90
|
-
"""
|
|
91
|
-
Perform remote embedding using a HTTP POST request to a designated endpoint.
|
|
92
|
-
|
|
93
|
-
Args:
|
|
94
|
-
texts (List[str]): A list of text strings to be embedded.
|
|
95
|
-
query_mode (bool): A flag to indicate if running in query mode or in embed mode (indexing).
|
|
96
|
-
Returns:
|
|
97
|
-
List[List[float]]: A list of embedded representations of the input texts.
|
|
98
|
-
"""
|
|
99
|
-
session = requests_retry_session(
|
|
100
|
-
retries=self.max_retries, backoff_factor=self.retry_backoff_factor
|
|
101
|
-
)
|
|
102
|
-
|
|
103
|
-
payload = {
|
|
104
|
-
"input": texts,
|
|
105
|
-
"model": self.model,
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
url = f"{self.tfy_llm_gateway_url}/openai/embeddings"
|
|
109
|
-
logger.debug(
|
|
110
|
-
f"Embedding using - model: {self.model} at endpoint: {url}, for {len(texts)} texts"
|
|
111
|
-
)
|
|
112
|
-
response = session.post(
|
|
113
|
-
url=url,
|
|
114
|
-
json=payload,
|
|
115
|
-
headers={
|
|
116
|
-
"Authorization": f"Bearer {self.tfy_api_key}",
|
|
117
|
-
},
|
|
118
|
-
timeout=self.request_timeout,
|
|
119
|
-
)
|
|
120
|
-
response.raise_for_status()
|
|
121
|
-
output = response.json()
|
|
122
|
-
return [data["embedding"] for data in output["data"]]
|
|
123
|
-
|
|
124
|
-
def _embed(self, texts: List[str], query_mode: bool):
|
|
125
|
-
"""
|
|
126
|
-
Perform embedding on a list of texts using remote embedding in chunks.
|
|
127
|
-
|
|
128
|
-
Args:
|
|
129
|
-
texts (List[str]): A list of text strings to be embedded.
|
|
130
|
-
query_mode (bool): A flag to indicate if running in query mode or in embed mode (indexing).
|
|
131
|
-
Returns:
|
|
132
|
-
List[List[float]]: A list of embedded representations of the input texts.
|
|
133
|
-
"""
|
|
134
|
-
embeddings = []
|
|
135
|
-
|
|
136
|
-
def _feeder():
|
|
137
|
-
for i in range(0, len(texts), self.batch_size):
|
|
138
|
-
chunk = texts[i : i + self.batch_size]
|
|
139
|
-
yield chunk
|
|
140
|
-
|
|
141
|
-
embeddings = list(
|
|
142
|
-
tqdm.tqdm(
|
|
143
|
-
self._executor.map(self._remote_embed, _feeder()),
|
|
144
|
-
total=int(math.ceil(len(texts) / self.batch_size)),
|
|
145
|
-
)
|
|
146
|
-
)
|
|
147
|
-
return [item for batch in embeddings for item in batch]
|
|
148
|
-
|
|
149
|
-
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
150
|
-
"""
|
|
151
|
-
Embed a list of text documents.
|
|
152
|
-
|
|
153
|
-
Args:
|
|
154
|
-
texts (List[str]): A list of text documents to be embedded.
|
|
155
|
-
|
|
156
|
-
Returns:
|
|
157
|
-
List[List[float]]: A list of embedded representations of the input documents.
|
|
158
|
-
"""
|
|
159
|
-
return self._embed(texts, query_mode=False)
|
|
160
|
-
|
|
161
|
-
def embed_query(self, text: str) -> List[float]:
|
|
162
|
-
"""
|
|
163
|
-
Embed a query text.
|
|
164
|
-
|
|
165
|
-
Args:
|
|
166
|
-
text (str): The query text to be embedded.
|
|
167
|
-
|
|
168
|
-
Returns:
|
|
169
|
-
List[float]: The embedded representation of the input query text.
|
|
170
|
-
"""
|
|
171
|
-
return self._embed([text], query_mode=True)[0]
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
from typing import Any, Dict, List, Optional
|
|
2
|
-
|
|
3
|
-
from langchain.llms.base import LLM
|
|
4
|
-
from langchain.pydantic_v1 import Extra, Field, root_validator
|
|
5
|
-
|
|
6
|
-
from truefoundry.common.request_utils import requests_retry_session
|
|
7
|
-
from truefoundry.langchain.utils import (
|
|
8
|
-
validate_tfy_environment,
|
|
9
|
-
)
|
|
10
|
-
from truefoundry.logger import logger
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
class TrueFoundryLLM(LLM):
|
|
14
|
-
"""`TrueFoundry LLM Gateway` completion models API.
|
|
15
|
-
|
|
16
|
-
To use, you must have the environment variable ``TFY_API_KEY`` set with your API key and ``TFY_HOST`` set with your host or pass it as a named parameter to the constructor.
|
|
17
|
-
"""
|
|
18
|
-
|
|
19
|
-
model: str = Field(description="The model to use for completion.")
|
|
20
|
-
"""The model to use for completion."""
|
|
21
|
-
tfy_llm_gateway_url: Optional[str] = Field(default=None)
|
|
22
|
-
"""TrueFoundry LLM Gateway endpoint URL. Automatically inferred from env var `TFY_LLM_GATEWAY_URL` if not provided."""
|
|
23
|
-
tfy_api_key: Optional[str] = Field(default=None)
|
|
24
|
-
"""TrueFoundry API Key. Automatically inferred from env var `TFY_API_KEY` if not provided."""
|
|
25
|
-
model_parameters: Optional[dict] = Field(default_factory=dict)
|
|
26
|
-
"""Model parameters"""
|
|
27
|
-
request_timeout: int = Field(default=30)
|
|
28
|
-
"""The timeout for the request in seconds."""
|
|
29
|
-
max_retries: int = Field(default=5)
|
|
30
|
-
"""The number of retries for HTTP requests."""
|
|
31
|
-
retry_backoff_factor: float = Field(default=0.3)
|
|
32
|
-
"""The backoff factor for exponential backoff during retries."""
|
|
33
|
-
|
|
34
|
-
class Config:
|
|
35
|
-
"""Configuration for this pydantic object."""
|
|
36
|
-
|
|
37
|
-
extra = Extra.forbid
|
|
38
|
-
allow_population_by_field_name = True
|
|
39
|
-
|
|
40
|
-
@root_validator()
|
|
41
|
-
def validate_environment(cls, values: Dict) -> Dict:
|
|
42
|
-
values = validate_tfy_environment(values)
|
|
43
|
-
if not values["tfy_api_key"]:
|
|
44
|
-
raise ValueError(
|
|
45
|
-
"Did not find `tfy_api_key`, please add an environment variable"
|
|
46
|
-
" `TFY_API_KEY` which contains it, or pass"
|
|
47
|
-
" `tfy_api_key` as a named parameter."
|
|
48
|
-
)
|
|
49
|
-
if not values["tfy_llm_gateway_url"]:
|
|
50
|
-
raise ValueError(
|
|
51
|
-
"Did not find `tfy_llm_gateway_url`, please add an environment variable"
|
|
52
|
-
" `TFY_LLM_GATEWAY_URL` which contains it, or pass"
|
|
53
|
-
" `tfy_llm_gateway_url` as a named parameter."
|
|
54
|
-
)
|
|
55
|
-
return values
|
|
56
|
-
|
|
57
|
-
@property
|
|
58
|
-
def _llm_type(self) -> str:
|
|
59
|
-
"""Return type of llm model."""
|
|
60
|
-
return "truefoundry-llm"
|
|
61
|
-
|
|
62
|
-
def _call(
|
|
63
|
-
self,
|
|
64
|
-
prompt: str,
|
|
65
|
-
stop: Optional[List[str]] = None,
|
|
66
|
-
**kwargs: Any,
|
|
67
|
-
) -> str:
|
|
68
|
-
"""Call out to the deployed model
|
|
69
|
-
|
|
70
|
-
Args:
|
|
71
|
-
prompt: The prompt to pass into the model.
|
|
72
|
-
stop: Optional list of stop words to use when generating.
|
|
73
|
-
|
|
74
|
-
Returns:
|
|
75
|
-
The string generated by the model.
|
|
76
|
-
|
|
77
|
-
Example:
|
|
78
|
-
.. code-block:: python
|
|
79
|
-
|
|
80
|
-
response = model("I have a joke for you...")
|
|
81
|
-
"""
|
|
82
|
-
|
|
83
|
-
payload = {**self.model_parameters} if self.model_parameters else {}
|
|
84
|
-
if stop:
|
|
85
|
-
payload["stop_sequences"] = stop
|
|
86
|
-
|
|
87
|
-
payload["prompt"] = prompt
|
|
88
|
-
payload["model"] = self.model
|
|
89
|
-
|
|
90
|
-
session = requests_retry_session(
|
|
91
|
-
retries=self.max_retries, backoff_factor=self.retry_backoff_factor
|
|
92
|
-
)
|
|
93
|
-
|
|
94
|
-
url = f"{self.tfy_llm_gateway_url}/openai/completions"
|
|
95
|
-
logger.debug(f"Completion using - model: {self.model} at endpoint: {url}")
|
|
96
|
-
response = session.post(
|
|
97
|
-
url=url,
|
|
98
|
-
json=payload,
|
|
99
|
-
headers={
|
|
100
|
-
"Authorization": f"Bearer {self.tfy_api_key}",
|
|
101
|
-
},
|
|
102
|
-
timeout=self.request_timeout,
|
|
103
|
-
)
|
|
104
|
-
response.raise_for_status()
|
|
105
|
-
output = response.json()
|
|
106
|
-
return output["choices"][0]["text"]
|
truefoundry/langchain/utils.py
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import os
|
|
2
|
-
from typing import Dict, List, Optional
|
|
3
|
-
from urllib.parse import urljoin
|
|
4
|
-
|
|
5
|
-
from langchain.pydantic_v1 import BaseModel
|
|
6
|
-
|
|
7
|
-
from truefoundry.deploy.lib.auth.servicefoundry_session import ServiceFoundrySession
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
class ModelParameters(BaseModel):
|
|
11
|
-
temperature: Optional[float]
|
|
12
|
-
maximum_length: Optional[int]
|
|
13
|
-
top_p: Optional[float]
|
|
14
|
-
top_k: Optional[int]
|
|
15
|
-
repetition_penalty: Optional[float]
|
|
16
|
-
frequency_penalty: Optional[float]
|
|
17
|
-
presence_penalty: Optional[float]
|
|
18
|
-
stop_sequences: Optional[List[str]]
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def validate_tfy_environment(values: Dict):
|
|
22
|
-
gateway_url = values["tfy_llm_gateway_url"] or os.getenv("TFY_LLM_GATEWAY_URL")
|
|
23
|
-
api_key = values["tfy_api_key"] or os.getenv("TFY_API_KEY")
|
|
24
|
-
|
|
25
|
-
if gateway_url and api_key:
|
|
26
|
-
values["tfy_llm_gateway_url"] = gateway_url
|
|
27
|
-
values["tfy_api_key"] = api_key
|
|
28
|
-
return values
|
|
29
|
-
|
|
30
|
-
sfy_session = ServiceFoundrySession()
|
|
31
|
-
if not sfy_session:
|
|
32
|
-
raise Exception(
|
|
33
|
-
"Unauthenticated: Please login using truefoundry login --host <https://example-domain.com>"
|
|
34
|
-
)
|
|
35
|
-
|
|
36
|
-
if not gateway_url:
|
|
37
|
-
gateway_url = urljoin(sfy_session.base_url, "/api/llm")
|
|
38
|
-
|
|
39
|
-
if not api_key:
|
|
40
|
-
api_key = sfy_session.access_token
|
|
41
|
-
|
|
42
|
-
values["tfy_llm_gateway_url"] = gateway_url
|
|
43
|
-
values["tfy_api_key"] = api_key
|
|
44
|
-
return values
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import enum
|
|
2
|
-
from typing import List, Type, TypeVar
|
|
3
|
-
|
|
4
|
-
from truefoundry.ml.autogen.client import ( # type: ignore[attr-defined]
|
|
5
|
-
ModelSchemaDto,
|
|
6
|
-
)
|
|
7
|
-
from truefoundry.ml.exceptions import MlFoundryException
|
|
8
|
-
from truefoundry.pydantic_v1 import BaseModel
|
|
9
|
-
|
|
10
|
-
T = TypeVar("T")
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
class BaseEnum(enum.Enum):
|
|
14
|
-
@classmethod
|
|
15
|
-
def values(cls: Type[T]) -> List[T]:
|
|
16
|
-
return [member.value for member in cls]
|
|
17
|
-
|
|
18
|
-
@classmethod
|
|
19
|
-
def _missing_(cls: Type[T], value: object):
|
|
20
|
-
raise MlFoundryException(
|
|
21
|
-
f"Unknown value for type {cls.__name__}: {value}", status_code=400
|
|
22
|
-
)
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
@enum.unique
|
|
26
|
-
class CustomMetricValueType(str, BaseEnum):
|
|
27
|
-
FLOAT = "float"
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
@enum.unique
|
|
31
|
-
class CustomMetricType(str, BaseEnum):
|
|
32
|
-
METRIC = "metric"
|
|
33
|
-
PROJECTION = "projection"
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
class CustomMetric(BaseModel):
|
|
37
|
-
class Config:
|
|
38
|
-
validate_assignment = True
|
|
39
|
-
use_enum_values = True
|
|
40
|
-
extra = "allow"
|
|
41
|
-
|
|
42
|
-
name: str
|
|
43
|
-
value_type: CustomMetricValueType
|
|
44
|
-
type: CustomMetricType
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
class ModelSchema(ModelSchemaDto):
|
|
48
|
-
pass
|
|
File without changes
|
|
File without changes
|