mirror of
https://github.com/infiniflow/ragflow.git
synced 2025-12-08 20:42:30 +08:00
Add Support for AWS Bedrock (#1408)
### What problem does this PR solve? #308 ### Type of change - [x] New Feature (non-breaking change which adds functionality) --------- Co-authored-by: KevinHuSh <kevinhu.sh@gmail.com>
This commit is contained in:
@ -31,7 +31,8 @@ EmbeddingModel = {
|
||||
"BaiChuan": BaiChuanEmbed,
|
||||
"Jina": JinaEmbed,
|
||||
"BAAI": DefaultEmbedding,
|
||||
"Mistral": MistralEmbed
|
||||
"Mistral": MistralEmbed,
|
||||
"Bedrock": BedrockEmbed
|
||||
}
|
||||
|
||||
|
||||
@ -58,7 +59,8 @@ ChatModel = {
|
||||
"VolcEngine": VolcEngineChat,
|
||||
"BaiChuan": BaiChuanChat,
|
||||
"MiniMax": MiniMaxChat,
|
||||
"Mistral": MistralChat
|
||||
"Mistral": MistralChat,
|
||||
"Bedrock": BedrockChat
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -533,3 +533,90 @@ class MistralChat(Base):
|
||||
yield ans + "\n**ERROR**: " + str(e)
|
||||
|
||||
yield total_tokens
|
||||
|
||||
|
||||
class BedrockChat(Base):
|
||||
|
||||
def __init__(self, key, model_name, **kwargs):
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
self.bedrock_ak = eval(key).get('bedrock_ak', '')
|
||||
self.bedrock_sk = eval(key).get('bedrock_sk', '')
|
||||
self.bedrock_region = eval(key).get('bedrock_region', '')
|
||||
self.model_name = model_name
|
||||
self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
|
||||
aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
|
||||
|
||||
def chat(self, system, history, gen_conf):
|
||||
if system:
|
||||
history.insert(0, {"role": "system", "content": system})
|
||||
for k in list(gen_conf.keys()):
|
||||
if k not in ["temperature", "top_p", "max_tokens"]:
|
||||
del gen_conf[k]
|
||||
if "max_tokens" in gen_conf:
|
||||
gen_conf["maxTokens"] = gen_conf["max_tokens"]
|
||||
_ = gen_conf.pop("max_tokens")
|
||||
if "top_p" in gen_conf:
|
||||
gen_conf["topP"] = gen_conf["top_p"]
|
||||
_ = gen_conf.pop("top_p")
|
||||
|
||||
try:
|
||||
# Send the message to the model, using a basic inference configuration.
|
||||
response = self.client.converse(
|
||||
modelId=self.model_name,
|
||||
messages=history,
|
||||
inferenceConfig=gen_conf
|
||||
)
|
||||
|
||||
# Extract and print the response text.
|
||||
ans = response["output"]["message"]["content"][0]["text"]
|
||||
return ans, num_tokens_from_string(ans)
|
||||
|
||||
except (ClientError, Exception) as e:
|
||||
return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
|
||||
|
||||
def chat_streamly(self, system, history, gen_conf):
|
||||
if system:
|
||||
history.insert(0, {"role": "system", "content": system})
|
||||
for k in list(gen_conf.keys()):
|
||||
if k not in ["temperature", "top_p", "max_tokens"]:
|
||||
del gen_conf[k]
|
||||
if "max_tokens" in gen_conf:
|
||||
gen_conf["maxTokens"] = gen_conf["max_tokens"]
|
||||
_ = gen_conf.pop("max_tokens")
|
||||
if "top_p" in gen_conf:
|
||||
gen_conf["topP"] = gen_conf["top_p"]
|
||||
_ = gen_conf.pop("top_p")
|
||||
|
||||
if self.model_name.split('.')[0] == 'ai21':
|
||||
try:
|
||||
response = self.client.converse(
|
||||
modelId=self.model_name,
|
||||
messages=history,
|
||||
inferenceConfig=gen_conf
|
||||
)
|
||||
ans = response["output"]["message"]["content"][0]["text"]
|
||||
return ans, num_tokens_from_string(ans)
|
||||
|
||||
except (ClientError, Exception) as e:
|
||||
return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
|
||||
|
||||
ans = ""
|
||||
try:
|
||||
# Send the message to the model, using a basic inference configuration.
|
||||
streaming_response = self.client.converse_stream(
|
||||
modelId=self.model_name,
|
||||
messages=history,
|
||||
inferenceConfig=gen_conf
|
||||
)
|
||||
|
||||
# Extract and print the streamed response text in real-time.
|
||||
for resp in streaming_response["stream"]:
|
||||
if "contentBlockDelta" in resp:
|
||||
ans += resp["contentBlockDelta"]["delta"]["text"]
|
||||
yield ans
|
||||
|
||||
except (ClientError, Exception) as e:
|
||||
yield ans + f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}"
|
||||
|
||||
yield num_tokens_from_string(ans)
|
||||
|
||||
@ -374,3 +374,48 @@ class MistralEmbed(Base):
|
||||
res = self.client.embeddings(input=[truncate(text, 8196)],
|
||||
model=self.model_name)
|
||||
return np.array(res.data[0].embedding), res.usage.total_tokens
|
||||
|
||||
|
||||
class BedrockEmbed(Base):
|
||||
def __init__(self, key, model_name,
|
||||
**kwargs):
|
||||
import boto3
|
||||
self.bedrock_ak = eval(key).get('bedrock_ak', '')
|
||||
self.bedrock_sk = eval(key).get('bedrock_sk', '')
|
||||
self.bedrock_region = eval(key).get('bedrock_region', '')
|
||||
self.model_name = model_name
|
||||
self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
|
||||
aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
|
||||
|
||||
def encode(self, texts: list, batch_size=32):
|
||||
texts = [truncate(t, 8196) for t in texts]
|
||||
embeddings = []
|
||||
token_count = 0
|
||||
for text in texts:
|
||||
if self.model_name.split('.')[0] == 'amazon':
|
||||
body = {"inputText": text}
|
||||
elif self.model_name.split('.')[0] == 'cohere':
|
||||
body = {"texts": [text], "input_type": 'search_document'}
|
||||
|
||||
response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
|
||||
model_response = json.loads(response["body"].read())
|
||||
embeddings.extend([model_response["embedding"]])
|
||||
token_count += num_tokens_from_string(text)
|
||||
|
||||
return np.array(embeddings), token_count
|
||||
|
||||
def encode_queries(self, text):
|
||||
|
||||
embeddings = []
|
||||
token_count = num_tokens_from_string(text)
|
||||
if self.model_name.split('.')[0] == 'amazon':
|
||||
body = {"inputText": truncate(text, 8196)}
|
||||
elif self.model_name.split('.')[0] == 'cohere':
|
||||
body = {"texts": [truncate(text, 8196)], "input_type": 'search_query'}
|
||||
|
||||
response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
|
||||
model_response = json.loads(response["body"].read())
|
||||
embeddings.extend([model_response["embedding"]])
|
||||
|
||||
return np.array(embeddings), token_count
|
||||
|
||||
|
||||
Reference in New Issue
Block a user