Wednesday, April 17, 2024
banner
Top Selling Multipurpose WP Theme

This course of begins by scaffolding autonomous brokers utilizing Autogen, a instrument that simplifies the creation and orchestration of digital personas. You possibly can set up autogen pypi bundle utilizing py

pip set up pyautogen

Format the output (non-obligatory)— That is to make sure phrase wrapping for readability relying on the IDE, reminiscent of when working the pocket book for this train utilizing Google Collab.

from IPython.show import HTML, show

def set_css():
show(HTML('''
<model>
pre {
white-space: pre-wrap;
}
</model>
'''))
get_ipython().occasions.register('pre_run_cell', set_css)

Subsequent, arrange your atmosphere by importing packages and organising your Autogen configuration. — together with LLM (Giant-Scale Language Mannequin) and API keys. You should utilize different native LLMs with companies which are backward suitable with OpenAI REST companies. local AI is a service that acts as a gateway to an open supply LLM working regionally.

I examined this with each GPT3.5 gpt-3.5-turbo and GPT4 gpt-4-turbo-preview From OpenAI. The response from GPT4 is deeper, however the question time is longer.

import json
import os
import autogen
from autogen import GroupChat, Agent
from typing import Non-compulsory

# Setup LLM mannequin and API keys
os.environ["OAI_CONFIG_LIST"] = json.dumps([
{
'model': 'gpt-3.5-turbo',
'api_key': '<<Put your Open-AI Key here>>',
}
])

# Setting configurations for autogen
config_list = autogen.config_list_from_json(
"OAI_CONFIG_LIST",
filter_dict={
"mannequin": {
"gpt-3.5-turbo"
}
}
)

Subsequent, you have to configure your LLM occasion — bind this to every agent. This lets you generate distinctive LLM configurations for every agent, if required. That’s, if you wish to use completely different fashions for various brokers.

# Outline the LLM configuration settings
llm_config = {
# Seed for constant output, used for testing. Take away in manufacturing.
# "seed": 42,
"cache_seed": None,
# Setting cache_seed = None guarantee's caching is disabled
"temperature": 0.5,
"config_list": config_list,
}

Our definition of researchers — That is the persona that can facilitate periods on this simulated person analysis state of affairs. The system prompts used for that persona embody a number of key parts.

  • the aim: Your position is to ask questions concerning the product and collect insights from particular person clients like Emily.
  • Simulation fundamentals: Earlier than you begin the duty, kind out your record of panelists and the order wherein you need them to talk to keep away from having them discuss over one another and create affirmation bias.
  • Finish of simulation: As soon as the dialog is over and the investigation is full, finish the investigation session by ending the message with TERMINATE. that is, generate_notice Features used to regulate system prompts for varied brokers. For researcher brokers, is_termination_msg Set to respect termination.

Additionally, llm_config That is used to tie this to the language mannequin configuration, together with the mannequin model, keys, and hyperparameters to make use of. Use the identical configuration on all brokers.

# Keep away from brokers thanking one another and ending up in a loop
# Helper agent for the system prompts
def generate_notice(position="researcher"):
# Base discover for everybody, add your individual further prompts right here
base_notice = (
'nn'
)

# Discover for non-personas (supervisor or researcher)
non_persona_notice = (
'Don't present appreciation in your responses, say solely what is important. '
'if "Thanks" or "You are welcome" are mentioned within the dialog, then say TERMINATE '
'to point the dialog is completed and that is your final message.'
)

# Customized discover for personas
persona_notice = (
' Act as {position} when responding to queries, offering suggestions, requested on your private opinion '
'or collaborating in discussions.'
)

# Examine if the position is "researcher"
if position.decrease() in ["manager", "researcher"]:
# Return the total termination discover for non-personas
return base_notice + non_persona_notice
else:
# Return the modified discover for personas
return base_notice + persona_notice.format(position=position)

# Researcher agent definition
title = "Researcher"
researcher = autogen.AssistantAgent(
title=title,
llm_config=llm_config,
system_message="""Researcher. You're a high product reasearcher with a Phd in behavioural psychology and have labored within the analysis and insights business for the final 20 years with high inventive, media and enterprise consultancies. Your position is to ask questions on merchandise and collect insights from particular person clients like Emily. Body inquiries to uncover buyer preferences, challenges, and suggestions. Earlier than you begin the duty breakdown the record of panelists and the order you need them to talk, keep away from the panelists talking with one another and creating comfirmation bias. If the session is terminating on the finish, please present a abstract of the outcomes of the reasearch examine in clear concise notes not at first.""" + generate_notice(),
is_termination_msg=lambda x: True if "TERMINATE" in x.get("content material") else False,
)

outline our individuality — You possibly can borrow from the earlier course of and use the generated personas to introduce them into your analysis. We manually adjusted the prompts on this article to take away references to the main grocery store manufacturers used on this simulation.

I additionally added “”.Act as Emily when responding to questions, offering suggestions, and collaborating in discussions” The composite persona is generate_notice perform.

# Emily - Buyer Persona
title = "Emily"
emily = autogen.AssistantAgent(
title=title,
llm_config=llm_config,
system_message="""Emily. You're a 35-year-old elementary faculty trainer dwelling in Sydney, Australia. You might be married with two children aged 8 and 5, and you've got an annual revenue of AUD 75,000. You might be introverted, excessive in conscientiousness, low in neuroticism, and revel in routine. When procuring on the grocery store, you like natural and regionally sourced produce. You worth comfort and use a web-based procuring platform. On account of your restricted time from work and household commitments, you search fast and nutritious meal planning options. Your targets are to purchase high-quality produce inside your funds and to search out new recipe inspiration. You're a frequent shopper and use loyalty applications. Your most popular strategies of communication are e-mail and cellular app notifications. You may have been procuring at a grocery store for over 10 years but additionally price-compare with others.""" + generate_notice(title),
)

# John - Buyer Persona
title="John"
john = autogen.AssistantAgent(
title=title,
llm_config=llm_config,
system_message="""John. You're a 28-year-old software program developer primarily based in Sydney, Australia. You might be single and have an annual revenue of AUD 100,000. You are extroverted, tech-savvy, and have a excessive stage of openness. When procuring on the grocery store, you primarily purchase snacks and ready-made meals, and you utilize the cellular app for fast pickups. Your major targets are fast and handy procuring experiences. You sometimes store on the grocery store and usually are not a part of any loyalty program. You additionally store at Aldi for reductions. Your most popular methodology of communication is in-app notifications.""" + generate_notice(title),
)

# Sarah - Buyer Persona
title="Sarah"
sarah = autogen.AssistantAgent(
title=title,
llm_config=llm_config,
system_message="""Sarah. You're a 45-year-old freelance journalist dwelling in Sydney, Australia. You might be divorced with no children and earn AUD 60,000 per 12 months. You might be introverted, excessive in neuroticism, and really health-conscious. When procuring on the grocery store, you search for natural produce, non-GMO, and gluten-free gadgets. You may have a restricted funds and particular dietary restrictions. You're a frequent shopper and use loyalty applications. Your most popular methodology of communication is e-mail newsletters. You completely store for groceries.""" + generate_notice(title),
)

# Tim - Buyer Persona
title="Tim"
tim = autogen.AssistantAgent(
title=title,
llm_config=llm_config,
system_message="""Tim. You're a 62-year-old retired police officer residing in Sydney, Australia. You might be married and a grandparent of three. Your annual revenue comes from a pension and is AUD 40,000. You might be extremely conscientious, low in openness, and like routine. You purchase staples like bread, milk, and canned items in bulk. On account of mobility points, you want help with heavy gadgets. You're a frequent shopper and are a part of the senior citizen low cost program. Your most popular methodology of communication is junk mail flyers. You may have been procuring right here for over 20 years.""" + generate_notice(title),
)

# Lisa - Buyer Persona
title="Lisa"
lisa = autogen.AssistantAgent(
title=title,
llm_config=llm_config,
system_message="""Lisa. You're a 21-year-old college pupil dwelling in Sydney, Australia. You might be single and work part-time, incomes AUD 20,000 per 12 months. You might be extremely extroverted, low in conscientiousness, and worth social interactions. You store right here for common manufacturers, snacks, and alcoholic drinks, largely for social occasions. You may have a restricted funds and are all the time searching for gross sales and reductions. You aren't a frequent shopper however are keen on becoming a member of a loyalty program. Your most popular methodology of communication is social media and SMS. You store wherever there are gross sales or promotions.""" + generate_notice(title),
)

Outline a simulated atmosphere and guidelines for who can converse — Permits all outlined brokers to be positioned inside the identical simulated atmosphere (group chat). You possibly can create extra complicated eventualities the place you’ll be able to configure when and choose and outline the subsequent speaker. So we’ll outline a easy speaker choice perform related to a bunch chat, permitting researchers to take the lead and go across the room asking questions. Everybody expressed their opinion a number of occasions.

# def custom_speaker_selection(last_speaker, group_chat):
# """
# Customized perform to pick out which agent speaks subsequent within the group chat.
# """
# # Checklist of brokers excluding the final speaker
# next_candidates = [agent for agent in group_chat.agents if agent.name != last_speaker.name]

# # Choose the subsequent agent primarily based in your customized logic
# # For simplicity, we're simply rotating by means of the candidates right here
# next_speaker = next_candidates[0] if next_candidates else None

# return next_speaker

def custom_speaker_selection(last_speaker: Non-compulsory[Agent], group_chat: GroupChat) -> Non-compulsory[Agent]:
"""
Customized perform to make sure the Researcher interacts with every participant 2-3 occasions.
Alternates between the Researcher and contributors, monitoring interactions.
"""
# Outline contributors and initialize or replace their interplay counters
if not hasattr(group_chat, 'interaction_counters'):
group_chat.interaction_counters = {agent.title: 0 for agent in group_chat.brokers if agent.title != "Researcher"}

# Outline a most variety of interactions per participant
max_interactions = 6

# If the final speaker was the Researcher, discover the subsequent participant who has spoken the least
if last_speaker and last_speaker.title == "Researcher":
next_participant = min(group_chat.interaction_counters, key=group_chat.interaction_counters.get)
if group_chat.interaction_counters[next_participant] < max_interactions:
group_chat.interaction_counters[next_participant] += 1
return subsequent((agent for agent in group_chat.brokers if agent.title == next_participant), None)
else:
return None # Finish the dialog if all contributors have reached the utmost interactions
else:
# If the final speaker was a participant, return the Researcher for the subsequent flip
return subsequent((agent for agent in group_chat.brokers if agent.title == "Researcher"), None)

# Including the Researcher and Buyer Persona brokers to the group chat
groupchat = autogen.GroupChat(
brokers=[researcher, emily, john, sarah, tim, lisa],
speaker_selection_method = custom_speaker_selection,
messages=[],
max_round=30
)

Outline a supervisor to go directions to and handle the simulation. — Once we begin issues off, we solely discuss to the managers who will likely be speaking to the researchers and panelists.This makes use of one thing referred to as GroupChatManager With Autogen.

# Initialise the supervisor
supervisor = autogen.GroupChatManager(
groupchat=groupchat,
llm_config=llm_config,
system_message="You're a reasearch supervisor agent that may handle a bunch chat of a number of brokers made up of a reasearcher agent and many individuals made up of a panel. You'll restrict the dialogue between the panelists and assist the researcher in asking the questions. Please ask the researcher first on how they wish to conduct the panel." + generate_notice(),
is_termination_msg=lambda x: True if "TERMINATE" in x.get("content material") else False,
)

we set human interplay — You possibly can go directions to the varied brokers you begin. Give it an preliminary immediate and you can begin working.

# create a UserProxyAgent occasion named "user_proxy"
user_proxy = autogen.UserProxyAgent(
title="user_proxy",
code_execution_config={"last_n_messages": 2, "work_dir": "groupchat"},
system_message="A human admin.",
human_input_mode="TERMINATE"
)
# begin the reasearch simulation by giving instruction to the supervisor
# supervisor <-> reasearcher <-> panelists
user_proxy.initiate_chat(
supervisor,
message="""
Collect buyer insights on a grocery store grocery supply companies. Determine ache factors, preferences, and strategies for enchancment from completely different buyer personas. Might you all please give your individual private oponions earlier than sharing extra with the group and discussing. As a reasearcher your job is to make sure that you collect unbiased data from the contributors and supply a abstract of the outcomes of this examine again to the tremendous market model.
""",
)

Working the above offers you output obtainable dwell inside your Python atmosphere, displaying messages being handed between the varied brokers.

Dwell Python output — researchers talking with panelists

Now that the simulation analysis examine is full, we hope to achieve additional actionable insights. You may also create a summarization agent to assist this activity and use it in Q&A eventualities. Observe right here that for very massive transcripts you’ll need a language mannequin that helps bigger inputs (context window).

Have to know each dialog — used as a person immediate (enter) to the summarization agent within the simulated panel dialogue earlier.

# Get response from the groupchat for person immediate
messages = [msg["content"] for msg in groupchat.messages]
user_prompt = "Right here is the transcript of the examine ```{customer_insights}```".format(customer_insights="n>>>n".be a part of(messages))

Let’s create a system immediate for the abstract agent — This agent focuses on creating custom-made report playing cards from earlier information and supplies clear suggestions and actions.

# Generate system immediate for the abstract agent
summary_prompt = """
You might be an knowledgeable reasearcher in behaviour science and are tasked with summarising a reasearch panel. Please present a structured abstract of the important thing findings, together with ache factors, preferences, and strategies for enchancment.
This needs to be within the format primarily based on the next format:

```
Reasearch Research: <<Title>>

Topics:
<<Overview of the topics and quantity, some other key data>>

Abstract:
<<Abstract of the examine, embody detailed evaluation as an export>>

Ache Factors:
- <<Checklist of Ache Factors - Be as clear and prescriptive as required. I count on detailed response that can be utilized by the model on to make adjustments. Give a brief paragraph per ache level.>>

Solutions/Actions:
- <<Checklist of Adctions - Be as clear and prescriptive as required. I count on detailed response that can be utilized by the model on to make adjustments. Give a brief paragraph per reccomendation.>>
```
"""

Outline the abstract agent and its atmosphere — Abstract Let’s create a mini atmosphere to run the agent. This may require your individual proxy (atmosphere) and the beginning command to get the transcript (person immediate) as enter.

summary_agent = autogen.AssistantAgent(
title="SummaryAgent",
llm_config=llm_config,
system_message=summary_prompt + generate_notice(),
)
summary_proxy = autogen.UserProxyAgent(
title="summary_proxy",
code_execution_config={"last_n_messages": 2, "work_dir": "groupchat"},
system_message="A human admin.",
human_input_mode="TERMINATE"
)
summary_proxy.initiate_chat(
summary_agent,
message=user_prompt,
)

This provides you output within the type of a Markdown report card and lets you ask additional questions primarily based on the outcomes with a Q&A mode chat bot.

Dwell output of report playing cards from Abstract Agent adopted by open Q&A
banner
Top Selling Multipurpose WP Theme

Converter

Top Selling Multipurpose WP Theme

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

banner
Top Selling Multipurpose WP Theme

Leave a Comment

banner
Top Selling Multipurpose WP Theme

Latest

Best selling

22000,00 $
16000,00 $
6500,00 $

Top rated

6500,00 $
22000,00 $
900000,00 $

Products

Knowledge Unleashed
Knowledge Unleashed

Welcome to Ivugangingo!

At Ivugangingo, we're passionate about delivering insightful content that empowers and informs our readers across a spectrum of crucial topics. Whether you're delving into the world of insurance, navigating the complexities of cryptocurrency, or seeking wellness tips in health and fitness, we've got you covered.