|
1 | 1 | import os |
2 | 2 | from typing import Any |
| 3 | +from typing import Callable |
| 4 | +from typing import Optional |
| 5 | +from typing import Union |
3 | 6 |
|
4 | | -from singlestoredb.fusion.handlers.utils import get_workspace_manager |
| 7 | +import httpx |
| 8 | + |
| 9 | +from singlestoredb import manage_workspaces |
5 | 10 |
|
6 | 11 | try: |
7 | 12 | from langchain_openai import ChatOpenAI |
|
11 | 16 | 'Please install it with `pip install langchain_openai`.', |
12 | 17 | ) |
13 | 18 |
|
| 19 | +try: |
| 20 | + from langchain_aws import ChatBedrockConverse |
| 21 | +except ImportError: |
| 22 | + raise ImportError( |
| 23 | + 'Could not import langchain-aws python package. ' |
| 24 | + 'Please install it with `pip install langchain-aws`.', |
| 25 | + ) |
| 26 | + |
| 27 | +import boto3 |
| 28 | +from botocore import UNSIGNED |
| 29 | +from botocore.config import Config |
| 30 | + |
14 | 31 |
|
15 | 32 | class SingleStoreChatOpenAI(ChatOpenAI): |
16 | | - def __init__(self, model_name: str, **kwargs: Any): |
| 33 | + def __init__(self, model_name: str, api_key: Optional[str] = None, **kwargs: Any): |
17 | 34 | inference_api_manger = ( |
18 | | - get_workspace_manager().organizations.current.inference_apis |
| 35 | + manage_workspaces().organizations.current.inference_apis |
19 | 36 | ) |
20 | 37 | info = inference_api_manger.get(model_name=model_name) |
| 38 | + token = ( |
| 39 | + api_key |
| 40 | + if api_key is not None |
| 41 | + else os.environ.get('SINGLESTOREDB_USER_TOKEN') |
| 42 | + ) |
21 | 43 | super().__init__( |
22 | 44 | base_url=info.connection_url, |
23 | | - api_key=os.environ.get('SINGLESTOREDB_USER_TOKEN'), |
| 45 | + api_key=token, |
24 | 46 | model=model_name, |
25 | 47 | **kwargs, |
26 | 48 | ) |
27 | 49 |
|
28 | 50 |
|
29 | 51 | class SingleStoreChat(ChatOpenAI): |
30 | | - def __init__(self, model_name: str, **kwargs: Any): |
| 52 | + def __init__(self, model_name: str, api_key: Optional[str] = None, **kwargs: Any): |
31 | 53 | inference_api_manger = ( |
32 | | - get_workspace_manager().organizations.current.inference_apis |
| 54 | + manage_workspaces().organizations.current.inference_apis |
33 | 55 | ) |
34 | 56 | info = inference_api_manger.get(model_name=model_name) |
| 57 | + token = ( |
| 58 | + api_key |
| 59 | + if api_key is not None |
| 60 | + else os.environ.get('SINGLESTOREDB_USER_TOKEN') |
| 61 | + ) |
35 | 62 | super().__init__( |
36 | 63 | base_url=info.connection_url, |
37 | | - api_key=os.environ.get('SINGLESTOREDB_USER_TOKEN'), |
| 64 | + api_key=token, |
38 | 65 | model=model_name, |
39 | 66 | **kwargs, |
40 | 67 | ) |
| 68 | + |
| 69 | + |
| 70 | +def SingleStoreChatFactory( |
| 71 | + model_name: str, |
| 72 | + api_key: Optional[str] = None, |
| 73 | + streaming: bool = True, |
| 74 | + http_client: Optional[httpx.Client] = None, |
| 75 | + obo_token_getter: Optional[Callable[[], Optional[str]]] = None, |
| 76 | + **kwargs: Any, |
| 77 | +) -> Union[ChatOpenAI, ChatBedrockConverse]: |
| 78 | + """Return a chat model instance (ChatOpenAI or ChatBedrockConverse). |
| 79 | + """ |
| 80 | + inference_api_manager = ( |
| 81 | + manage_workspaces().organizations.current.inference_apis |
| 82 | + ) |
| 83 | + info = inference_api_manager.get(model_name=model_name) |
| 84 | + token_env = os.environ.get('SINGLESTOREDB_USER_TOKEN') |
| 85 | + token = api_key if api_key is not None else token_env |
| 86 | + |
| 87 | + if info.hosting_platform == 'Amazon': |
| 88 | + # Instantiate Bedrock client |
| 89 | + cfg_kwargs = { |
| 90 | + 'signature_version': UNSIGNED, |
| 91 | + 'retries': {'max_attempts': 1, 'mode': 'standard'}, |
| 92 | + } |
| 93 | + if http_client is not None and http_client.timeout is not None: |
| 94 | + cfg_kwargs['read_timeout'] = http_client.timeout |
| 95 | + cfg_kwargs['connect_timeout'] = http_client.timeout |
| 96 | + |
| 97 | + cfg = Config(**cfg_kwargs) |
| 98 | + client = boto3.client( |
| 99 | + 'bedrock-runtime', |
| 100 | + endpoint_url=info.connection_url, |
| 101 | + region_name='us-east-1', |
| 102 | + aws_access_key_id='placeholder', |
| 103 | + aws_secret_access_key='placeholder', |
| 104 | + config=cfg, |
| 105 | + ) |
| 106 | + |
| 107 | + def _inject_headers(request: Any, **_ignored: Any) -> None: |
| 108 | + """Inject dynamic auth/OBO headers prior to Bedrock sending.""" |
| 109 | + if obo_token_getter is not None: |
| 110 | + obo_val = obo_token_getter() |
| 111 | + if obo_val: |
| 112 | + request.headers['X-S2-OBO'] = obo_val |
| 113 | + if token: |
| 114 | + request.headers['Authorization'] = f'Bearer {token}' |
| 115 | + request.headers.pop('X-Amz-Date', None) |
| 116 | + request.headers.pop('X-Amz-Security-Token', None) |
| 117 | + |
| 118 | + emitter = client._endpoint._event_emitter |
| 119 | + emitter.register_first( |
| 120 | + 'before-send.bedrock-runtime.Converse', |
| 121 | + _inject_headers, |
| 122 | + ) |
| 123 | + emitter.register_first( |
| 124 | + 'before-send.bedrock-runtime.ConverseStream', |
| 125 | + _inject_headers, |
| 126 | + ) |
| 127 | + emitter.register_first( |
| 128 | + 'before-send.bedrock-runtime.InvokeModel', |
| 129 | + _inject_headers, |
| 130 | + ) |
| 131 | + emitter.register_first( |
| 132 | + 'before-send.bedrock-runtime.InvokeModelWithResponseStream', |
| 133 | + _inject_headers, |
| 134 | + ) |
| 135 | + |
| 136 | + return ChatBedrockConverse( |
| 137 | + model_id=model_name, |
| 138 | + endpoint_url=info.connection_url, |
| 139 | + region_name='us-east-1', |
| 140 | + aws_access_key_id='placeholder', |
| 141 | + aws_secret_access_key='placeholder', |
| 142 | + disable_streaming=not streaming, |
| 143 | + client=client, |
| 144 | + **kwargs, |
| 145 | + ) |
| 146 | + |
| 147 | + # OpenAI / Azure OpenAI path |
| 148 | + openai_kwargs = dict( |
| 149 | + base_url=info.connection_url, |
| 150 | + api_key=token, |
| 151 | + model=model_name, |
| 152 | + streaming=streaming, |
| 153 | + ) |
| 154 | + if http_client is not None: |
| 155 | + openai_kwargs['http_client'] = http_client |
| 156 | + return ChatOpenAI( |
| 157 | + **openai_kwargs, |
| 158 | + **kwargs, |
| 159 | + ) |
0 commit comments