{"id":20502056,"url":"https://github.com/higgn/bedrockchat","last_synced_at":"2026-04-16T14:03:40.205Z","repository":{"id":261742941,"uuid":"883876065","full_name":"higgn/bedrockchat","owner":"higgn","description":"Bedrock Chatbot Implementation","archived":false,"fork":false,"pushed_at":"2024-11-11T14:22:39.000Z","size":226,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-05T19:58:44.688Z","etag":null,"topics":["aws","bedrock","python","streamlit"],"latest_commit_sha":null,"homepage":"https://awschat.streamlit.app/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/higgn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-05T18:19:05.000Z","updated_at":"2024-11-11T14:23:53.000Z","dependencies_parsed_at":"2024-11-08T07:31:11.567Z","dependency_job_id":"8f2af07f-175e-404c-b9af-0850ceea6f2c","html_url":"https://github.com/higgn/bedrockchat","commit_stats":null,"previous_names":["zesina/bedrockchat","higgn/bedrockchat"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/higgn/bedrockchat","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/higgn%2Fbedrockchat","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/higgn%2Fbedrockchat/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/higgn%2Fbedrockchat/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/higgn%2Fbedrockchat/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/higgn","download_url":"https://codeload.github.com/higgn/bedrockchat/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/higgn%2Fbedrockchat/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270709038,"owners_count":24631992,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-16T02:00:11.002Z","response_time":91,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","bedrock","python","streamlit"],"created_at":"2024-11-15T19:19:14.762Z","updated_at":"2026-04-16T14:03:40.162Z","avatar_url":"https://github.com/higgn.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"![image](https://github.com/user-attachments/assets/34fbf004-2f48-4abd-87b6-1de5698a8082)\n[AWS COMMUNITY](https://community.aws/content/2oYRwEiblS2EoIuNo6e6ksttkY8/build-your-own-advanced-ai-chatbot-with-aws-bedrock)\nWelcome to step-by-step guide on building an advanced AI chatbot using AWS Bedrock. In this post, you'll learn how to create a powerful chatbot that can answer queries anytime, anywhere. Let's dive into the world of AI and explore the limitless possibilities!\nAnd what excites most is you can modify it as per your choice!\n```bash\nAuthor : Gagan\nLinkedin : Connect 😺\nProject-Link : Github 🫧\n```\n\nLive Demo here 🫧 : https://awschat.streamlit.app/\n\n\n🫧 Setting Up Your Environment\n🫧 Prerequisites Before we start, ensure you have the following:\nAn AWS account\nAWS CLI configured\nAWS Bedrock enabled for your account\nPython 3.6 or later installed\nStreamlit installed (pip install streamlit)\nBoto3 installed (pip install boto3)\nLoad environment variables using python-dotenv (pip install python-dotenv)\n\n🫧AWS Credentials To interact with AWS services, you'll need to set up your AWS credentials. Here's how to configure them:\n\naws configure\nNote : Make sure aws cli is installed by\n```bash\npip install awscli\naws --version\n```\nYou'll be prompted to enter your AWS Access Key ID, Secret Access Key, region, and output format.\nIn that paste your keys\n```bash\nAWS_ACCESS_KEY_ID=AKX........TQGLNYN\nAWS_SECRET_ACCESS_KEY=U...........xKXTVTYr2EG/iyhh\u0026hj\n```\ntype 👉 us-east-1 in region and JSON in output when asked ( and done )\n\n🫧 Installing Required Python Packages Create a requirements.txt file with the following content and install the dependencies:\n```.py\nboto3\nrequests\nstreamlit\nlangchain\nlangchain-community\npython-dotenv\nFlask\n```\nthen run 👇\n```bash\npip install -r requirements.txt\n```\nYou will also need Telegram bot TOKEN and Chat ID for sending logs in TELEGRAM ✨\nhere is how your .env will look like 👇\n```bash\nAWS_ACCESS_KEY_ID=EXAMPKLDLLMLLJL\nAWS_SECRET_ACCESS_KEY=n/EXAMPKLENKND/TuyiKNLDll\nTELEGRAM_TOKEN=248998399:ExamPlerOIJOlkjKJHljhl\n```\nNow here is the code for gagan.py ( main script ) 👇\n```.py\nimport base64\nimport boto3\nimport json\nimport os\nimport requests\nimport streamlit as st\nfrom langchain.chains import LLMChain\nfrom langchain.llms.bedrock import Bedrock\nfrom langchain.prompts import PromptTemplate\nfrom dotenv import load_dotenv\nimport time\nimport logging\nimport streamlit.components.v1 as components\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='a',\n                    format='%(asctime)s - %(levelname)s - %(message)s')\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.DEBUG)\nlogging.getLogger('').addHandler(console)\n\n# Load environment variables from .env file\nload_dotenv()\n\n# Set up Telegram bot\nTELEGRAM_TOKEN = os.getenv(\"TELEGRAM_TOKEN\")\nTELEGRAM_CHAT_ID = \"6581618525\"  # Directly using the chat ID provided\nTELEGRAM_URL = f\"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage\"\n\n# Bedrock client\nbedrock_client = boto3.client(\n    service_name=\"bedrock-runtime\",\n    region_name=\"us-east-1\"\n)\n\n# Model IDs for text and image generation\ntext_model_id = \"amazon.titan-text-premier-v1:0\"\nimage_model_id = \"amazon.titan-image-generator-v2:0\"\n\n# LLM for text generation\nllm_text = Bedrock(\n    model_id=text_model_id,\n    client=bedrock_client,\n    model_kwargs={\"maxTokenCount\": 1000, \"temperature\": 0.5}\n)\n\n# Function for generating chat responses\ndef my_chatbot(language, freeform_text, template):\n    prompt = PromptTemplate(\n        input_variables=[\"language\", \"freeform_text\"],\n        template=template\n    )\n    bedrock_chain = LLMChain(llm=llm_text, prompt=prompt)\n    response = bedrock_chain({'language': language, 'freeform_text': freeform_text})\n    return response['text']\n\n# Function for generating images with backoff logic\ndef create_image(input_text):\n    image_config = {\n        \"textToImageParams\": {\"text\": input_text},\n        \"taskType\": \"TEXT_IMAGE\",\n        \"imageGenerationConfig\": {\n            \"cfgScale\": 8.0,\n            \"seed\": 0,\n            \"quality\": \"standard\",\n            \"width\": 512,\n            \"height\": 512,\n            \"numberOfImages\": 1\n        }\n    }\n\n    max_retries = 5\n    retry_delay = 60  # 1 minute\n\n    for attempt in range(max_retries):\n        try:\n            logging.debug(\"Invoking model for image generation, attempt %d\", attempt + 1)\n            response = bedrock_client.invoke_model(\n                modelId=image_model_id,\n                contentType=\"application/json\",\n                accept=\"application/json\",\n                body=json.dumps(image_config)\n            )\n\n            response_body = json.loads(response['body'].read())\n            logging.debug(f\"Response body: {response_body}\")\n\n            if 'images' in response_body:\n                image_data_base64 = response_body['images'][0]\n                image_data = base64.b64decode(image_data_base64)\n                return image_data\n            else:\n                logging.error(\"No images found in response\")\n                return None\n\n        except Exception as e:\n            logging.error(f\"Error generating image: {e}\")\n            if \"ThrottlingException\" in str(e):\n                logging.debug(f\"ThrottlingException encountered, retrying after {retry_delay} seconds\")\n                time.sleep(retry_delay)\n            else:\n                return None\n\n    logging.error(\"Max retries reached, failed to generate image\")\n    return None\n\n# Function to send logs to Telegram\ndef send_log_to_telegram(message):\n    payload = {\"chat_id\": TELEGRAM_CHAT_ID, \"text\": message}\n    try:\n        response = requests.post(TELEGRAM_URL, json=payload)\n        logging.debug(f\"Telegram response: {response.json()}\")\n    except Exception as e:\n        logging.error(f\"Error sending message to Telegram: {e}\")\n\n# Custom JavaScript for typewriter effect\ntypewriter_js = \"\"\"\n\u003cscript\u003e\nvar index = 0;\nfunction typeWriter() {\n    if (index \u003c fullText.length) {\n        document.getElementById(\"output\").innerHTML += fullText.charAt(index);\n        index++;\n        \n    }\n}\n\u003c/script\u003e\n\"\"\"\n\n# Streamlit UI enhancements\nst.set_page_config(page_title=\"Bedrock FM \", page_icon=\":robot_face:\", layout=\"centered\")\nst.image(\"logo.png\", width=100)\n\nst.title(\"Bedrock Chat 💬\")\n\n# CSS for styling and animations\nst.markdown(\"\"\"\n    \u003cstyle\u003e\n    .stButton button {\n\n        color: white;\n        background: linear-gradient(90deg, #476072, #2B2B2B);\n        border: 2px solid white;\n        padding: 12px 24px;\n        text-align: center;\n        text-decoration: none;\n        display: inline-block;\n        font-size: 16px;\n        margin: 4px 2px;\n        transition-duration: 0.4s;\n        cursor: pointer;\n        border-radius: 12px;\n        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);\n    }\n\n    .stButton button:hover {\n        background-color: white;\n        color: yellow;\n        border: 3px solid white;\n        box-shadow: 0 5px 9px rgba(0, 0, 0, 0.1);\n    }\n\n    .message-card {\n        padding: 16px;\n        margin: 16px 0;\n        border-radius: 8px;\n        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);\n    }\n\n    .message-card h4 {\n        color: #4CAF50;\n        font-family: 'Courier New', Courier, monospace;\n    }\n\n    .typing {\n        display: inline-block;\n        font-size: 16px;\n        font-family: 'Courier New', Courier, monospace;\n        margin: 0;\n        white-space: nowrap;\n        overflow: hidden;\n        animation: typing 3s steps(40, end), blink-caret 0.75s step-end infinite;\n        border-right: 2px solid;\n    }\n\n        @keyframes typing {\n        from { width: 0 }\n        to { width: 100% }\n    }\n\n    @keyframes blink-caret {\n        from, to { border-color: transparent }\n        50% { border-color: black }\n    }\n    \u003c/style\u003e\n\"\"\", unsafe_allow_html=True)\n\n# Sidebar elements\nlanguage = st.sidebar.selectbox(\"Language 📜\", [\"english\", \"hindi\"])\ntemplate = st.sidebar.text_area(\"Customize Chat🧬\", \"You are a chatbot. You are in {language}.\\n\\n{freeform_text}\")\n\nif st.sidebar.button(\"Set Mode\"):\n    st.session_state.template = template  # Save the custom template to the session state\n    st.success(\"✨Template mode set successfully!\")\n\nmax_token_count = st.sidebar.slider(\"Max Token Count\", 50, 2000, 1000)\ntemperature = st.sidebar.slider(\"Temperature\", 0.5, 0.9, 0.5)\n\n# Move this part below the sliders\nllm_text = Bedrock(\n    model_id=text_model_id,\n    client=bedrock_client,\n    model_kwargs={\"maxTokenCount\": max_token_count, \"temperature\": temperature}\n)\n\nsuggested_questions = [\n    \"What is the capital of France?\",\n    \"Who is Buddha?\",\n    \"Hello World in C++?\",\n    \"Top 10 Programming Languages?\",\n    \"How to get a job in Ai era?\",\n    \"Who is Ana de Armas?\",\n    \"What are Top 10 IMDB movies?\"\n]\n\n# Update the following part to correctly display the response with the typing effect\n\nif language:\n    st.sidebar.write(\"Suggested Questions:\")\n    for question in suggested_questions:\n        if st.sidebar.button(question):\n            freeform_text = question\n\n            with st.spinner('Generating response...'):\n                response = my_chatbot(language, freeform_text, template)\n                st.markdown(f\"\u003cdiv class='message-card'\u003e\u003ch4\u003e🫧\u003c/h4\u003e\u003cp\u003e{response}\u003c/p\u003e\u003c/div\u003e\", unsafe_allow_html=True)\n            send_log_to_telegram(f\"Asked: {question}\\nAnswer: {response}\")\n\n    freeform_text = st.text_area(label=\"\", max_chars=500, placeholder=\"Chat with me...\")\n\n    col1, col2 = st.columns(2)\n    with col1:\n        if st.button(\"Ask 💬\"):\n            if freeform_text:\n                \n                with st.spinner('Generating response...'):\n                    response = my_chatbot(language, freeform_text, template)\n                    st.markdown(f\"\u003cdiv class='message-card'\u003e\u003ch4\u003e🫧\u003c/h4\u003e\u003cp\u003e{response}\u003c/p\u003e\u003c/div\u003e\", unsafe_allow_html=True)\n                send_log_to_telegram(f\"Asked: {freeform_text}\\nAnswer: {response}\")\n\n    with col2:\n        if st.button(\"Create Image\"):\n            if freeform_text:\n                with st.spinner('Generating image...'):\n                    image_data = create_image(freeform_text)\n                    if image_data:\n                        st.image(image_data, caption=\"Generated Image\")\n                        send_log_to_telegram(f\"Generated Image for: {freeform_text}\")\n                    else:\n                        st.error(\"Failed to generate image.\")\n                        send_log_to_telegram(f\"Failed to generate image for: {freeform_text}\")\n\n    \nif st.button(\"Clear\"):\n    st.markdown(\"\"\"\n        \u003cscript\u003e\n            window.print(response);\n        \u003c/script\u003e\n    \"\"\", unsafe_allow_html=True)\nand you can run this script by running\n```\n\n```.py\npython -m streamlit run gagan.py\n```\n\nAnd cool ! Your chat bot is running 🫧\nWorking Project Screenshots 🌌\nChatbot in Dark Theme\n![Screenshot 2024-11-08 110854](https://github.com/user-attachments/assets/4d4129a2-38c7-49b7-b5db-b6b856aea22f)\n\nBedrock Chatbot ( White Theme )\n![Screenshot 2024-11-08 110753](https://github.com/user-attachments/assets/856ab80a-57fe-4e8f-8f85-a7181df87098)\n\n![Screenshot 2024-11-08 111141](https://github.com/user-attachments/assets/5833704b-8df0-4aa2-a19f-74846f261619)\n\nBedrock Chatbot ( White Theme ) Mobile\n\n\nOh and you can set the temprature ( creativity of chatbot ) and token ( Output Length ) at run time from sidebar\nYou can also use SET MODE for change behaviour of Chatbot\n\n\n![Screenshot 2024-11-08 111032](https://github.com/user-attachments/assets/35c770f3-ec7d-4b68-9efd-8027db112074)\n![Screenshot 2024-11-08 110920](https://github.com/user-attachments/assets/63513846-7f66-4961-aa1c-a26634d4b20b)\n![Screenshot 2024-11-08 111102](https://github.com/user-attachments/assets/91701335-42d8-4f63-b071-0910e1b6a3c6)\n\n\n\n\nThank You for reading my Post , Take care please fork 🍽️ and Star ⭐the repo it will be really Kind of you ( I have not a job yet haha )\n ✨\nTake care, Bye 🫧\nSee ya\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhiggn%2Fbedrockchat","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhiggn%2Fbedrockchat","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhiggn%2Fbedrockchat/lists"}