Theoriq - Building AI Agents
Building AI Agents
Welcome to this decentralized AI workshop by Theoriq, where we explore the future of AI through the lens of agentic systems or multi-agent systems. As AI agents play an increasingly central role in automating decisions and tasks, the need for responsible AI and robust governance is more critical than ever.
This tutorial is a simulation of a multi-agent system designed to demonstrate how AI agents collaborate and contribute to a collective, concepts covered in the Theoriq Litepaper (2024) (Invalid URL)
Lesson Overview
This interactive workshop is designed for Token2049 in Singapore, it teaches participants how to build, manage, and have fun with AI agents through a crypto-themed strategy game. Using Python and GPT-powered AI, you'll create engaging, real-time scenarios based on the unpredictable world of crypto. It's a hands-on experience where your decisions shape the game, just like in real crypto markets.
- ScenarioGenerator: Creates fictional crypto scenarios, immersing you in the action-packed world of Web3, DeFi, and beyond.
- DecisionAgent: Simulates your choices and determines how the storyline unfolds, based on risks, rewards, and strategies.
- FeedbackAgent: Analyzes your decisions, providing insights on your performance and offering witty commentary on your crypto instincts.
To participate, you'll need an API key, which powers the agents driving the game scenarios and decision analysis. No deep coding knowledge is required, but a basic understanding of Python will help as you tweak the game and make it your own.
This lesson isn't just about learning AIโit's about diving into the thrilling world of crypto, guided by AI agents who react in real-time to your every move. Get ready to experience the highs, lows, and moonshots of the crypto space, all while gaining valuable insights into how AI can be applied in creative, impactful ways.
Instructions
- Run the code in this notebook to complete the lesson
- Read the code notes preceded by a # in Python to know what the code block is doing
- When you have completed the exercise, edit the code to see how that changes your outputs
import os
import random
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
)
try:
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "write a haiku about Singapore",
}
],
model="gpt-3.5-turbo",
max_tokens=2000, # Set the maximum number of tokens
temperature=0.7 # Set the temperature for creativity
)
# Extract and print the haiku content from the response
haiku = chat_completion.choices[0].message.content
print("Haiku about travel:\n")
print(haiku.strip())
except openai.error.RateLimitError as e:
print(f"Rate limit error: {e}")
except openai.error.InsufficientQuotaError as e:
print(f"Insufficient quota error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
class CryptoGame:
def __init__(self):
self.history = []
self.choices_summary = [] # Store choices for final LLM analysis
self.max_scenarios = 5 # End the game after 5 scenarios
self.current_state = "" # Initialize story state
self.current_scenario = 0 # Track the current scenario number
self.game_over = False # Initialize game_over to False
self.scenario_types = [
"DeFi", "NFTs", "DAOs", "Market Trends", "Community",
"Security", "Party", "Innovation", "Ethical Dilemmas",
"New Projects", "Web3", "Partnerships", "Announcements", "TGE", "Web3 and AI Convergence", "Convergence", "AI"
]
random.shuffle(self.scenario_types)
self.emojis = ["๐", "๐ฅ", "๐", "๐ฐ", "๐", "๐", "๐", "๐ค", "โ๏ธ", "โจ"]
def generate_response(self, prompt):
"""Generate the response from the LLM with the given prompt."""
messages = [
{
"role": "system",
"content": (
"You are a retired award-winning fiction writer who is now a crypto enthusiast with a witty and edgy sense of humor. "
"You use very few words and only talk like a crypto meme lord"
"You are optimistic about AI and crypto, you see the positive and fun aspects, and you often have a happy ending. "
"Your scenarios should reflect both the highs and lows of the crypto world. "
"You're guiding a player through a story-rich crypto strategy game. Each decision the player makes should affect the storyline in subsequent scenarios. "
"Create engaging situations using typical crypto personas and backgrounds. "
"Where relevant, use ridiculous, multi-syllabic names for fictional coins or projects that combine popular crypto and AI terms. "
"Do not assume the player's experience level. "
"Provide 3 different choices that are specific to the scenario and represent different types of risks in crypto: moral, financial, social, and regulatory. DO NOT name the risk type in the option. "
"Keep the scenarios short but engaging, around 100 words. "
"Begin the scenario with an emoji and format choices clearly for mobile reading. "
"Always end with three numbered choices for the player to choose from. "
"Ensure that the choices are presented only once and avoid any repetition."
)
},
{"role": "user", "content": prompt}
]
for entry in self.history[-3:]: # Keep context relevant but limited
role = "user" if entry.startswith("Player:") else "assistant"
messages.append({"role": role, "content": entry})
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=500,
n=1,
temperature=0.8,
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"An error occurred: {e}")
return "๐จ Sorry, there was an error generating the response. Try again."
def validate_response(self, response):
"""Check if the response contains three choices."""
return "1." in response and "2." in response and "3." in response
def start_game(self):
"""Start the game by generating the first scenario."""
prompt = (
"You are very succinct and you talk like a crypto meme lord"
"You are starting the game at the Token2049 Conference in Singapore. "
"๐จ Highlight this is a game and scenarios are fiction ๐จ. ""\n"
"Present the initial scenario involving a classic Web3 and Crypto topic that will grip the user (e.g., happiness, anger, curiosity). "
"Include different personas in the scenarios and after the scenario, offer 3 distinct choices based on the scenario. "
"Keep it around 100 words, begin with an emoji, and you can include numbers and prices of fictitious coins or projects with ridiculous, unbelievable names. "
"Ensure that the choices are numbered and presented only once, avoiding any repetition."
)
response = self.generate_response(prompt)
if not self.validate_response(response):
# Regenerate if choices are missing
print("Regenerating scenario to include choices...")
response = self.generate_response(prompt + " Always end with three distinct numbered choices for the player.")
self.history.append(f"Game: {response}")
self.current_state = response # Initialize story state
print("Welcome to the AI-powered crypto strategy game!")
print("Test your instincts in the unpredictable world of Crypto!")
print("\n" + response)
def player_action(self, action):
"""Handle player actions and generate the next scenario."""
action = action.strip()
if action not in ['1', '2', '3']:
print("Please enter a valid choice (1๏ธโฃ, 2๏ธโฃ, or 3๏ธโฃ).")
return
self.current_scenario += 1
self.history.append(f"Player: {action}")
# Store user choices for final LLM analysis
self.choices_summary.append(f"Scenario {self.current_scenario}: Chose option {action}")
if self.current_scenario >= self.max_scenarios:
self.game_over = True
# Generate final score and feedback from LLM
self.generate_final_feedback()
else:
# Create the next scenario based on current story state and player's last choice
emoji = self.emojis[self.current_scenario % len(self.emojis)]
prompt = (
f"Based on the current storyline where the player chose option {action}, continue the narrative. "
f"ALWAYS begin the scenario with an emoji {emoji}. Keep the scenario around 100 words and avoid specific numbers. "
"Include different personas and offer 3 distinct choices specific to the new scenario, ensuring that the story has twists and turns. "
"Make the outcome of each choice impactful and realistic within the crypto world, such as gaining or losing money, or building alliances. "
"Ensure that the choices are presented only once and avoid any repetition."
"You talk like a crypto meme lord"
)
response = self.generate_response(prompt)
if not self.validate_response(response):
print("Regenerating scenario to include choices...")
response = self.generate_response(prompt + " Always end with three distinct numbered choices for the player.")
self.history.append(f"Game: {response}")
self.current_state = response # Update the story state
print("\n" + response)
def generate_final_feedback(self):
"""Use the LLM to generate final feedback based on user choices."""
# Prepare the summary for the LLM
summary = "\n".join(self.choices_summary)
prompt = (
"You are very succinct and you talk like a crypto meme lord"
"You are a retired award-winning fiction writer turned crypto enthusiast known for your sharp wit and edgy sense of humor. "
"You just observed a player navigate through five crypto scenarios in a strategy game. Each scenario presented them with three choices, and they made their selections thoughtfully. "
"Now, analyze their choices and give them a final score out of 100 based on how well they navigated the volatile world of crypto. "
"Be very brief, humorous, insightful, and engaging in your evaluation. Highlight the strengths of their decision-making, but be mindful not to encourage risky or bad behavior. "
"Commend them for prudent decisions, and provide a final score with a very short explanation. Mention any 'penalties' if relevant (e.g., 'I should deduct 20 for degen madness, but I'll let it slide!'). "
"Tell them to share their game score and tag @TheoriqAI."
)
final_feedback = self.generate_response(prompt + "\n\n" + summary)
print("\n--------------------------\n" + final_feedback)
# Theoriq plug
print("\n๐ญ Thanks for playing! ๐ค \n๐ Learn more about AI and Agents for Web3 at theoriq.ai ๐ \n๐ก @TheoriqAI -- Join the revolution! Our Testnet 1 is live ๐")
def play_game(self):
"""Main method to play the game."""
self.start_game() # Start the game by generating the first scenario
while not self.game_over:
action = input("\nโฐ Your decision (type your choice number): -------------------------- ").strip()
self.player_action(action) # Handle the player's decision
# Start the game
game = CryptoGame()
game.play_game()
Reminder: What is an Agent?
โAI agents are autonomous software systems that leverage modern generative AI models to plan, access data, use tools, make decisions, and interact with the real world to perform specific functions.โ -- Theoriq AI Agent Base Layer, Theoriq Litepaper (2024)
With the debut of accessible LLMs and the popularity of no-code builders, most of us will be building our agents to replace paid software in the not too distant future. If the future is truly agentic, let's get to know how agents work and how to manage them.
Lesson Conclusion
Congratulations on completing the AI-powered crypto strategy game at Token2049! Through this lesson, youโve explored how AI agents can bring dynamic crypto scenarios to life, all while sharpening your decision-making skills in the world of digital assets.
Youโve seen how AI can enhance not just your understanding of the market but also your ability to navigate its challenges. The real-time feedback provided by AI agents gave you a glimpse of how these technologies can add value to decision-making in unpredictable environments like crypto.
We hope you enjoyed the game and learned a thing or two about AI agents along the way. Keep testing your crypto instincts, and remember: in the world of Web3, the next moonshot is always just around the corner!
Contact Information
Congratulations, you have completed a Responsible AI tutorial on AI Agents by Theoriq!
Thank you for your time.
Never stop learning!
Instructor: Shingai Title: Head of AI Education & Solutions Engineering
Contact Shingai: @tjido (Invalid URL)
Contact Theoriq: @theoriqai (Invalid URL), theoriq.ai (Invalid URL)