Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aswintechguy
GitHub Repository: aswintechguy/Deep-Learning-Projects
Path: blob/main/Create AI Agent for Wikipedia and Calculator - OpenAI/AI Agent for Wikipedia and Calculator - OpenAI.ipynb
569 views
Kernel: Python 3 (ipykernel)

Import Modules

from openai import OpenAI import re import httpx

Create ChatBot Class

class ChatBot: def __init__(self, system_prompt=''): self.system_prompt = system_prompt self.client = OpenAI() self.messages = [] if self.system_prompt: self.messages.append({"role": 'system', 'content': self.system_prompt}) def __call__(self, message): self.messages.append({'role': 'user', 'content': message}) response = self.execute() self.messages.append({'role': 'assistant', 'content': response}) return response def execute(self): completion = self.client.chat.completions.create(model='gpt-4o-mini', messages=self.messages) return completion.choices[0].message.content def reset(self): self.messages = [] if self.system_prompt: self.messages.append({"role": 'system', 'content': self.system_prompt})

Create Agent Prompt

prompt = """ You run in a loop of Thought, Action, PAUSE, Observation. At the end of the loop you output an Answer. Use Thought to describe your thoughts about the question you have been asked. Use Action to run one of the actions available to you - then return PAUSE. Observation will be the result of running those actions. Your available actions are: calculate: e.g. calculate: 6 * 4 / 3 Runs a calculation and returns the number - uses Python so be sure to use floating point syntax if necessary wikipedia: e.g. wikipedia: Django Returns a summary from searching Wikipedia Example session: Question: What is the capital of France? Thought: I should look up France on Wikipedia Action: wikipedia: France PAUSE You will be called again with this: Observation: France is a country. The capital is Paris. You then output: Answer: The capital of France is Paris """.strip()

Configure Functions

action_re = re.compile(r'^Action: (\w+): (.*)') def wikipedia(query): responses = httpx.get('https://en.wikipedia.org/w/api.php', params={ "action": "query", "list": "search", "srsearch": query, "format": "json" }) text = "" n = 3 for response in responses.json()['query']['search'][:n]: text += response['snippet'] + '\n\n' return text def calculate(expression): return eval(expression) known_actions = { "wikipedia": wikipedia, "calculate": calculate }
# test ai model bot = ChatBot("You are a helpful assistant.") print(bot('What is AI Agent?'))
An AI agent is a computational entity that employs artificial intelligence techniques to perceive its environment, make decisions, and perform actions autonomously or semi-autonomously to achieve specific goals. Here’s an overview of the key concepts and characteristics associated with AI agents: ### Key Characteristics of AI Agents 1. **Autonomy**: - AI agents operate without human intervention. They can make decisions based on their perceptions and learned experiences. 2. **Perception**: - AI agents can perceive their environment through sensors, data inputs, or predefined data sources. This allows them to gather information that is essential for making informed decisions. 3. **Action**: - Based on their evaluations of the environment, AI agents can take actions to pursue their goals. This could involve responding to user inputs, controlling machinery, or even interacting with other agents or systems. 4. **Adaptability and Learning**: - Many AI agents can learn from their experiences, adapt to new situations, and improve their performance over time. This is often achieved through machine learning techniques. 5. **Goal-Oriented Behavior**: - AI agents are designed to achieve specific objectives or goals. These goals may involve maximizing efficiency, minimizing costs, or satisfying user preferences. 6. **Communication**: - In multi-agent systems, AI agents may communicate with one another to share knowledge, coordinate actions, and achieve collective goals. ### Types of AI Agents 1. **Reactive Agents**: - These agents respond to immediate stimuli without the ability to learn from past experiences. They operate based on pre-defined rules and behaviors. 2. **Deliberative Agents**: - These agents maintain an internal model of the world and can reason about their actions over time. They plan their actions based on knowledge and predictions about future states. 3. **Learning Agents**: - Using machine learning techniques, these agents can improve their performance by learning from experience and adapting to changes in the environment. 4. **Multi-Agent Systems**: - A group of AI agents that work together to solve problems or complete tasks. They can collaborate, negotiate, and coordinate their actions. ### Applications of AI Agents - **Virtual Assistants**: Such as Siri, Alexa, and Google Assistant that help users by providing information and performing tasks. - **Autonomous Vehicles**: AI agents that navigate and make driving decisions in real time. - **Robotics**: Robots that perform tasks in various domains, from manufacturing to service industries. - **Recommendation Systems**: AI agents that suggest products or content based on user preferences and behavior. - **Game AI**: Non-player characters (NPCs) that use AI to react and adapt to players’ actions in video games. ### Challenges - **Ethics and Bias**: Ensuring that AI agents make fair decisions and do not perpetuate biases present in the training data. - **Transparency**: Understanding and explaining how AI agents make decisions can be difficult, especially in complex models. - **Safety and Security**: Ensuring that AI agents operate safely in dynamic and unpredictable environments. AI agents represent a significant advancement in automation and intelligent systems, possessing remarkable capabilities to enhance productivity, efficiency, and user experience across numerous applications.
bot.reset()
wikipedia('capital of canada')
'Ottawa is the <span class="searchmatch">capital</span> city <span class="searchmatch">of</span> <span class="searchmatch">Canada</span>. It is located in the southern portion <span class="searchmatch">of</span> the province <span class="searchmatch">of</span> Ontario, at the meeting <span class="searchmatch">of</span> the Ottawa River and the Rideau\n\n<span class="searchmatch">Capital</span> punishment in <span class="searchmatch">Canada</span> dates to <span class="searchmatch">Canada\'s</span> earliest history, including its period as first a French then a British colony. From 1867 to the elimination\n\nofficial federal designation encompassing the <span class="searchmatch">Canadian</span> <span class="searchmatch">capital</span> <span class="searchmatch">of</span> Ottawa, Ontario, the adjacent city <span class="searchmatch">of</span> Gatineau, Quebec, and surrounding suburban and\n\n'
calculate('4+1')
5

Main Function for AI Agent

def query(question, max_turns=5): i = 0 bot = ChatBot(prompt) next_prompt = question while i < max_turns: i += 1 result = bot(next_prompt) print(result) # check if action is present actions = [action_re.match(a) for a in result.split('\n') if action_re.match(a)] if actions: action, action_input = actions[0].groups() if action not in known_actions: raise Exception(f"Unknown action: {action}: {action_input}") print(f"Running {action}: {action_input}") observation = known_actions[action](action_input) # call the function with input print("Observation:", observation) next_prompt = f"Observation: {observation}" else: return
query("capital of canada")
Thought: I need to find out what the capital of Canada is, so I'll look it up on Wikipedia. Action: wikipedia: Canada PAUSE Running wikipedia: Canada Observation: <span class="searchmatch">Canada</span> is a country in North America. Its ten provinces and three territories extend from the Atlantic Ocean to the Pacific Ocean and northward into the <span class="searchmatch">Canadians</span> (French: Canadiens) are people identified with the country of <span class="searchmatch">Canada</span>. This connection may be residential, legal, historical or cultural. For up <span class="searchmatch">cañada</span> in Wiktionary, the free dictionary. <span class="searchmatch">Cañada</span> may refer to: <span class="searchmatch">Cañada</span> de Gómez, Santa Fe province <span class="searchmatch">Cañada</span> Rosquín, Santa Fe province La <span class="searchmatch">Cañada</span>, Santiago Thought: The information from Wikipedia doesn't explicitly mention the capital of Canada. I need to perform a search focusing specifically on the capital. Action: wikipedia: Capital of Canada PAUSE Running wikipedia: Capital of Canada Observation: Ottawa is the <span class="searchmatch">capital</span> city <span class="searchmatch">of</span> <span class="searchmatch">Canada</span>. It is located in the southern portion <span class="searchmatch">of</span> the province <span class="searchmatch">of</span> Ontario, at the meeting <span class="searchmatch">of</span> the Ottawa River and the Rideau <span class="searchmatch">Capital</span> punishment in <span class="searchmatch">Canada</span> dates to <span class="searchmatch">Canada's</span> earliest history, including its period as first a French then a British colony. From 1867 to the elimination official federal designation encompassing the <span class="searchmatch">Canadian</span> <span class="searchmatch">capital</span> <span class="searchmatch">of</span> Ottawa, Ontario, the adjacent city <span class="searchmatch">of</span> Gatineau, Quebec, and surrounding suburban and Answer: The capital of Canada is Ottawa.
query('What is 10+3')
Thought: This is a simple arithmetic calculation that I can perform to find the answer. Action: calculate: 10 + 3 PAUSE Running calculate: 10 + 3 Observation: 13 Answer: The result of 10 + 3 is 13.
query('What is 10 plus 13')
Thought: This is a simple arithmetic question that can be solved easily by adding the two numbers together. 10 plus 13 is straightforward; I will perform the calculation now. Action: calculate: 10 + 13 PAUSE Running calculate: 10 + 13 Observation: 23 Answer: 10 plus 13 is 23.