Created
August 14, 2025 06:03
-
-
Save debugmodedotnet/ba5e95bf5e4cd50d1bb91c5122540f93 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| from dotenv import load_dotenv | |
| from openai import OpenAI | |
| import requests | |
| from langchain_openai import ChatOpenAI | |
| from langchain.schema import HumanMessage | |
| from langchain_core.messages import AIMessage, SystemMessage | |
| from langchain_core.prompts import PromptTemplate | |
| load_dotenv() | |
| def fetch_data(): | |
| try: | |
| api_url = "http://localhost:3000/product" | |
| response = requests.get(api_url) | |
| if response.status_code == 200: | |
| return response.json() | |
| else: | |
| print(f"API call failed with status: {response.status_code}") | |
| return None | |
| except Exception as e: | |
| print(f"Error making API call: {e}") | |
| return None | |
| prompt = PromptTemplate( | |
| input_variables=["data", "user_name"], | |
| template=""" | |
| hello {user_name}. | |
| IMPORTANT RULES: | |
| - Only answer questions about data {data} | |
| - Do not answer any other question about any other data | |
| - Always be helpful and provide accurate information | |
| - Greet the user by name: {user_name} | |
| """ | |
| , | |
| validate_template=True | |
| ) | |
| model = ChatOpenAI( | |
| model="gpt-3.5-turbo", | |
| api_key=os.getenv("OPENAI_API_KEY") | |
| ) | |
| def chat(): | |
| data = fetch_data() | |
| sytem_prompt = prompt.invoke({"data":str(data),"user_name":"DJ"}).text | |
| messages = [ | |
| SystemMessage(content=sytem_prompt), | |
| HumanMessage(content="I am DJ"), | |
| AIMessage(content="Hello DJ, how can I assist you today?"), | |
| ] | |
| print('chat started press q to exit.....') | |
| print('-' *30) | |
| while True: | |
| user_input = input("You: ").strip() | |
| if user_input.lower() in ['q']: | |
| print("Goodbye!") | |
| break | |
| messages.append(HumanMessage(content=user_input)) | |
| response = model.invoke(messages) | |
| messages.append(response) | |
| print(f"AI: {response.content}") | |
| print('-' * 30) | |
| if __name__ == "__main__": | |
| print(chat()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment