import os
import boto3
from dotenv import load_dotenv
from botocore.exceptions import NoCredentialsError, ProfileNotFound # 第一步:加载 .env 文件
load_dotenv() # 第二步:读取环境变量
region = os.getenv("AWS_REGION")
profile = os.getenv("AWS_PROFILE") print("🔍 检查当前 AWS 配置...")
print("📍 AWS Region:", region)
print("👤 AWS Profile:", profile) # 第三步:验证 AWS 配置是否存在
if not region or not profile: print("❌ 错误:环境变量 AWS_REGION 或 AWS_PROFILE 未设置。请检查 .env 文件。") exit(1) # 第四步:尝试连接 AWS Bedrock
try: session = boto3.Session(profile_name=profile, region_name=region) bedrock_agent_runtime = session.client(service_name='bedrock-agent-runtime')
except ProfileNotFound: print(f"❌ 错误:找不到名为 '{profile}' 的 AWS profile。请先运行 aws configure 设置。") exit(1)
except NoCredentialsError: print("❌ 错误:未检测到有效的 AWS 凭证。请确保已使用 aws configure 设置 Access Key。") exit(1) print("✅ AWS 环境配置成功,开始调用知识库...") # 第五步:设置知识库 ID 和模型 ARN(请替换为你自己的)
knowledge_base_id = "你的知识库ID" # ← 在控制台查看 Knowledge Base ID
model_arn = "你的 model ARN" # 可替换为 DeepSeek 等 # 第六步:输入你的问题
user_input = "公司全勤奖是多少钱?" # 第七步:调用知识库进行 RAG 问答
try: response = bedrock_agent_runtime.retrieve_and_generate( input={"text": user_input}, retrieveAndGenerateConfiguration={ "type": "KNOWLEDGE_BASE", "knowledgeBaseConfiguration": { "knowledgeBaseId": knowledge_base_id, "modelArn": model_arn } } ) # 第八步:打印模型回答 print("\n🤖 模型回答:") print(response["output"]["text"]) except Exception as e: print("❌ 出现错误:", str(e))