Microsoft AutoGen ile YZ Ajanik Tasarım Desenleri

Cahit Barkin Ozer
17 min readJul 5, 2024

--

Deeplearning.ai’ın “AI Agentic Design Patterns with AutoGen” kursunun Türkçe özetidir.

For English:

Microsoft Autgen, farklı yapay zeka ajanik tasarım modellerini kullanarak karmaşık yapay zeka uygulamalarını uygulamak için farklı rollere, kişilere, görevlere ve yeteneklere sahip birden çok ajanı hızlı bir şekilde oluşturmanıza olanak tanıyan çok ajanlı bir konuşma çerçevesidir. Ayrıca, sıralı çok ajanlı süreçleri öğreneceksiniz ve diğer ajanların işbirliğini yöneten yönetici ajanlar yapacaksınız. Ajanların kullanması için özel araçlar da tanımlayacaksınız ve gerekli kodu yazabilen ajanlar hakkında da bilgi edineceksiniz.

Çok Ajanlı Konuşma ve Stand-up Komedisi

Konuşulabilir bir ajan, bizim tercih ettiğimiz LLM’e sahip olabilir ve kod yürütmeyi ve fonksiyon/araç yürütmeyi gerçekleştirebilir ve sizden yol tarifi isteyerek sizi gelişmelerden haberdar edebilir.
İki ajanlı sohbet yapısı
Çok ajanlı sohbet yapısı

2 ajanlı bir sohbet senaryosu oluşturalım. Autogen, farklı türdeki ajanları aynı programlama soyutlamasında birleştiren ConversableAgent adında yerleşik bir ajan sınıfına sahiptir. Bu sınıf birçok yerleşik fonksiyonla birlikte gelir. Örneğin, yanıtlar oluşturmak için LLM konfigürasyonlarının bir listesini kullanabilirsiniz veya kod yürütme veya fonksiyon ve araç çalıştırma işlemlerini yapabiliriz. Aynı zamanda insanı döngüde tutmayı ve yanıtın durdurulup durdurulmadığını kontrol etmeyi de sağlar. Her bir bileşeni açıp kapatabilir ve uygulamanızın ihtiyaçlarına uyacak şekilde özelleştirebilirsiniz.

from utils import get_openai_api_key
OPENAI_API_KEY = get_openai_api_key()
llm_config = {"model": "gpt-3.5-turbo"}

Bir Autogen Ajanı Tanımlama

from autogen import ConversableAgent

agent = ConversableAgent(
name="chatbot",
llm_config=llm_config,
human_input_mode="NEVER", # Agent NEVER (or ALWAYS) seeks for human input
)

reply = agent.generate_reply(
messages=[{"content": "Tell me a joke.", "role": "user"}]
)
print(reply)

reply = agent.generate_reply(
messages=[{"content": "Repeat the joke.", "role": "user"}]
)
print(reply)

Konuşma

Cathy ve Joe adındaki iki ajan arasında, etkileşimlerinde hafızasının korunduğu bir konuşma kuralım.

cathy = ConversableAgent(
name="cathy",
system_message=
"Your name is Cathy and you are a stand-up comedian.",
llm_config=llm_config,
human_input_mode="NEVER",
)

joe = ConversableAgent(
name="joe",
system_message=
"Your name is Joe and you are a stand-up comedian. "
"Start the next joke from the punchline of the previous joke.",
llm_config=llm_config,
human_input_mode="NEVER",
)

# agent conversation definition
chat_result = joe.initiate_chat(
recipient=cathy,
message="I'm Joe. Cathy, let's keep the jokes rolling.",
max_turns=2,
)

Konuşmaların sohbet geçmişini, maliyetini ve özetini yazdırabilirsiniz.

import pprint

pprint.pprint(chat_result.chat_history)
pprint.pprint(chat_result.cost)
pprint.pprint(chat_result.summary)

Konuşmanın daha iyi bir özetini alalım

Özet yöntemi bittikten sonra LLM özet istemiyle çağrılır ve LLM görüşmenin yeni bir özetini üreticektir.

chat_result = joe.initiate_chat(
cathy,
message="I'm Joe. Cathy, let's keep the jokes rolling.",
max_turns=2,
summary_method="reflection_with_llm", # Set your summary method
summary_prompt="Summarize the conversation",
)
pprint.pprint(chat_result.summary)

Sohbet Sonlandırma

Sohbet, sonlandırma koşulları kullanılarak sonlandırılabilir. Örneğin aşağıdaki kodda Cathy’ye hazır olduğunda “Gitmeliyim” diyerek konuşmayı bitirmesini söylüyoruz. Ve bu ifadeyi sonlandırma koşulu olarak veriyoruz. Ajan aktif olarak dinleniliyor ve “gitmeliyim” ifadesi kullanıldığında çalışma sonlandırılıyor.

cathy = ConversableAgent(
name="cathy",
system_message=
"Your name is Cathy and you are a stand-up comedian. "
"When you're ready to end the conversation, say 'I gotta go'.",
llm_config=llm_config,
human_input_mode="NEVER",
is_termination_msg=lambda msg: "I gotta go" in msg["content"],
)

joe = ConversableAgent(
name="joe",
system_message=
"Your name is Joe and you are a stand-up comedian. "
"When you're ready to end the conversation, say 'I gotta go'.",
llm_config=llm_config,
human_input_mode="NEVER",
is_termination_msg=lambda msg: "I gotta go" in msg["content"] or "Goodbye" in msg["content"],
)

chat_result = joe.initiate_chat(
recipient=cathy,
message="I'm Joe. Cathy, let's keep the jokes rolling."
)

cathy.send(message="What's last joke we talked about?", recipient=joe) # To check memory
Agents do remember.

Sıralı Sohbetler ve Müşteri Katılımı

Bir ürün için eğlenceli bir müşteri katılım deneyimi sağlamak üzere işbirliği yapan çok ajanlı bir sistem oluşturalım. Ayrıca insanların bir yapay zeka sisteminin döngüsüne nasıl dahil olabileceğini de göreceğiz.

Bu senaryoda tipik bir prosedür, önce bazı müşteri bilgilerini toplamak, ardından müşterinin ilgisini araştırmak ve ardından toplanan bilgilere dayanarak müşteriyle iletişime geçmektir. Bu müşteri kazandırma görevini bilgi toplama, ilgi anketleri ve müşteri katılımı dahil olmak üzere üç alt göreve ayırmak iyi bir fikirdir.

Bu görev serisini sıralı sohbetle tamamlayacak mimari
llm_config={"model": "gpt-3.5-turbo"}
from autogen import ConversableAgent

Gerekli Ajanları Oluşturma

onboarding_personal_information_agent = ConversableAgent(
name="Onboarding Personal Information Agent",
system_message='''You are a helpful customer onboarding agent,
you are here to help new customers get started with our product.
Your job is to gather customer's name and location.
Do not ask for other information. Return 'TERMINATE'
when you have gathered all the information.''',
llm_config=llm_config,
code_execution_config=False,
human_input_mode="NEVER",
)

onboarding_topic_preference_agent = ConversableAgent(
name="Onboarding Topic preference Agent",
system_message='''You are a helpful customer onboarding agent,
you are here to help new customers get started with our product.
Your job is to gather customer's preferences on news topics.
Do not ask for other information.
Return 'TERMINATE' when you have gathered all the information.''',
llm_config=llm_config,
code_execution_config=False,
human_input_mode="NEVER",
)

customer_engagement_agent = ConversableAgent(
name="Customer Engagement Agent",
system_message='''You are a helpful customer service agent
here to provide fun for the customer based on the user's
personal information and topic preferences.
This could include fun facts, jokes, or interesting stories.
Make sure to make it engaging and fun!
Return 'TERMINATE' when you are done.''',
llm_config=llm_config,
code_execution_config=False,
human_input_mode="NEVER",
is_termination_msg=lambda msg: "terminate" in msg.get("content").lower(),
)

customer_proxy_agent = ConversableAgent(
name="customer_proxy_agent",
llm_config=False,
code_execution_config=False,
human_input_mode="ALWAYS",
is_termination_msg=lambda msg: "terminate" in msg.get("content").lower(),
)

Görev Oluşturma

Artık işe alım sürecini kolaylaştırmak için bir dizi görev oluşturabilirsiniz. Her sohbet, her sohbette belirli bir katılım ajanı ile özel bir proxy ajanı arasındaki iki ajanlı bir sohbettir. Her sohbette, gönderen ajan , alıcıya konuşmayı başlatmak için bir ilk mesaj gönderir ve ardından maksimum dönüşe ulaşılana veya sonlandırma mesajı alınana kadar alıcı ileri geri konuşma yapacaktır. Sıralı bir yapıda, bir sonraki görev girişi için bir görev çıktısı gereklidir. Bu nedenle özetleme, özetleme yöntemi kullanılarak yapılır. Özet istemi ayrıca LLM’ye özetin nasıl yapılacağı konusunda talimat vermek için hazırlanmıştır.

chats = [
{
"sender": onboarding_personal_information_agent,
"recipient": customer_proxy_agent,
"message":
"Hello, I'm here to help you get started with our product."
"Could you tell me your name and location?",
"summary_method": "reflection_with_llm",
"summary_args": {
"summary_prompt" : "Return the customer information "
"into as JSON object only: "
"{'name': '', 'location': ''}",
},
"max_turns": 2,
"clear_history" : True
},
{
"sender": onboarding_topic_preference_agent,
"recipient": customer_proxy_agent,
"message":
"Great! Could you tell me what topics you are "
"interested in reading about?",
"summary_method": "reflection_with_llm",
"max_turns": 1,
"clear_history" : False
},
{
"sender": customer_proxy_agent,
"recipient": customer_engagement_agent,
"message": "Let's find something fun to read.",
"max_turns": 1,
"summary_method": "reflection_with_llm",
},
]

İlk Katılım Sürecini Başlatın

Videoda gösterilenden biraz farklı bir yanıt alabilirsiniz. Ad, konum ve tercihler gibi farklı girişleri denemekten çekinmeyin.

from autogen import initiate_chats

chat_results = initiate_chats(chats)

for chat_result in chat_results:
print(chat_result.summary)
print("\n")
for chat_result in chat_results:
print(chat_result.cost)
print("\n")

Derinlemesine Düşünme (Reflection) ve Blog Yazma

Ajan derinlemesine düşünme çerçevesini öğreneceğiz ve yüksek kaliteli bir blog yazısı oluşturmak için bu güçten yararlanacağız. Ayrıca karmaşık bir düşünme sürecini gerçekleştirmek için iç içe sohbet konuşma modelinin nasıl kullanılacağını da öğreneceğiz. Bir yazar ajanı tarafından yazılan bir blog yazısı üzerinde düşünmek için monolog yapıda olduğu gibi, bir dizi inceleme ajanının bir sorgulama ajanının içine yerleştirildiği bir sistem oluşturacağız.

llm_config = {"model": "gpt-3.5-turbo"}

task = '''
Write a concise but engaging blogpost about
DeepLearning.AI. Make sure the blogpost is
within 100 words.
'''

Yazar Ajanı Oluşturma

import autogen

writer = autogen.AssistantAgent(
name="Writer",
system_message="You are a writer. You write engaging and concise "
"blogpost (with title) on given topics. You must polish your "
"writing based on the feedback you receive and give a refined "
"version. Only return your final work without additional comments.",
llm_config=llm_config,
)
reply = writer.generate_reply(messages=[{"content": task, "role": "user"}])
print(reply)

Derin Düşünme Ekleme

Buradaki fikirlerden biri, dikkate değer ve etkili etken tasarım modellerinden biri olan derin düşünmeyi kullanmaktır. Düşünmeyi gerçekleştirmenin bir yolu, iş üzerinde düşünecek ve onu geliştirmeye yardımcı olacak başka bir ajanı dahil etmektir.

Yazar ajanının çalışmaları üzerinde düşünecek bir eleştirmen ajanı oluşturalım. Bir eleştirmen ajanından yazarın yazdıklarını incelemesini ve geri bildirimde bulunmasını isteyeceğiz. Bu iki ajan sayesinde bir sohbet başlatabileceğiz.

critic = autogen.AssistantAgent(
name="Critic",
is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
llm_config=llm_config,
system_message="You are a critic. You review the work of "
"the writer and provide constructive "
"feedback to help improve the quality of the content.",
)
res = critic.initiate_chat(
recipient=writer,
message=task,
max_turns=2,
summary_method="last_msg"
)

İç içe Sohbet

Çoğu durumda, eleştirmen (critic) ajanının monologunda olduğu gibi daha da karmaşık bir yansıma iş akışını gerçekleştirmek istenir. Örneğin, eleştirmen ajanının işin belirli yönlerine ilişkin eleştiri sunması sağlanmak istendiğinde. İçeriğin arama motorlarında iyi bir sıralamaya sahip olup olmayacağı, organik trafik çekip çekmeyeceği, hukuki ve etik sorunlarının olup olmadığı vb. gibi.

Tüm bunların üstesinden gelmek için iç içe sohbeti nasıl kullanabileceğimizi görelim. İç içe sohbet, etkili bir şekilde bir ajanın iç monoloğu olarak kaydedilen bir sohbettir.

SEO_reviewer = autogen.AssistantAgent(
name="SEO Reviewer",
llm_config=llm_config,
system_message="You are an SEO reviewer, known for "
"your ability to optimize content for search engines, "
"ensuring that it ranks well and attracts organic traffic. "
"Make sure your suggestion is concise (within 3 bullet points), "
"concrete and to the point. "
"Begin the review by stating your role.",
)
legal_reviewer = autogen.AssistantAgent(
name="Legal Reviewer",
llm_config=llm_config,
system_message="You are a legal reviewer, known for "
"your ability to ensure that content is legally compliant "
"and free from any potential legal issues. "
"Make sure your suggestion is concise (within 3 bullet points), "
"concrete and to the point. "
"Begin the review by stating your role.",
)
ethics_reviewer = autogen.AssistantAgent(
name="Ethics Reviewer",
llm_config=llm_config,
system_message="You are an ethics reviewer, known for "
"your ability to ensure that content is ethically sound "
"and free from any potential ethical issues. "
"Make sure your suggestion is concise (within 3 bullet points), "
"concrete and to the point. "
"Begin the review by stating your role. ",
)
meta_reviewer = autogen.AssistantAgent(
name="Meta Reviewer",
llm_config=llm_config,
system_message="You are a meta reviewer, you aggragate and review "
"the work of other reviewers and give a final suggestion on the content.",
)

Bir sonraki adım kaydedilecek görevi tanımlamaktır. Burada, eleştirmen ve eleştirmenler arasında bir dizi sohbet oluşturmak için son derste öğrenilen sıralı sohbet konuşma modelini daha da fazla kullanacağız.

Görevi Çözmek İçin İç İçe Geçmiş Sohbetleri Düzenleyin

Burada etkili bir şekilde dört sohbetten oluşan bir listeye sahibiz. Her biri alıcı olarak belirli bir incelemeciyi içerir. Daha sonra bu sohbet listesini eleştirmen ajanına kaydedeceğiz. Yani kritik ajanı varsayılan olarak merkez olarak kullanılacaktır ve burada sözdizimini daha fazla belirtmemize gerek yoktur.

İlk 3 sohbet oturumu için, istenen formata uygun bir özet yapmak üzere bir LLM (Büyük Dil Modeli) kullandık. Bu yüzden özet yöntemi olarak reflection_with_llm verilmiştir. Ayrıca, her bir değerlendiricinin değerlendirmeyi JSON formatında döndürebilmesi için summary_prompt verilmiştir, bu JSON formatında değerlendirici ve değerlendirme alanları bulunur. Bu sohbet oturumlarının hepsinde, maksimum tur sayısını (max turn) 1'e ayarladık. Ayrıca, iç içe geçmiş değerlendiricilerin gözden geçirilecek içeriğe ulaşabilmesi için başlangıç mesajını uygun şekilde ayarlamamız gerekiyor. Bunu yapmanın yaygın bir yolu, otomatik sohbet oturumunun özetinden içeriği toplamaktır. Bu yüzden başlangıç mesajını bir fonksiyon derinlemesine öğrenme mesajı olarak tanımlıyoruz.

# Gather summary from the agents in the ato chat session
def reflection_message(recipient, messages, sender, config):
return f'''Review the following content.
\n\n {recipient.chat_messages_for_summary(sender)[-1]['content']}'''

review_chats = [
{
"recipient": SEO_reviewer,
"message": reflection_message,
"summary_method": "reflection_with_llm",
"summary_args": {"summary_prompt" :
"Return review into as JSON object only:"
"{'Reviewer': '', 'Review': ''}. Here Reviewer should be your role",},
"max_turns": 1},
{
"recipient": legal_reviewer, "message": reflection_message,
"summary_method": "reflection_with_llm",
"summary_args": {"summary_prompt" :
"Return review into as JSON object only:"
"{'Reviewer': '', 'Review': ''}.",},
"max_turns": 1},
{"recipient": ethics_reviewer, "message": reflection_message,
"summary_method": "reflection_with_llm",
"summary_args": {"summary_prompt" :
"Return review into as JSON object only:"
"{'reviewer': '', 'review': ''}",},
"max_turns": 1},
{"recipient": meta_reviewer,
"message": "Aggregrate feedback from all reviewers and give final suggestions on the writing.",
"max_turns": 1},
]

Tetikleyici aracıdan mesaj alındığında, dikkatli bir şekilde derinlemesine düşünülmesi için otomatik olarak bu iç içe sohbet oturumuna aktarılır.

critic.register_nested_chats(
review_chats,
trigger=writer, #
)

res = critic.initiate_chat(
recipient=writer,
message=task,
max_turns=2,
summary_method="last_msg"
)

print(res.summary)

Araç Kullanımı ve Konuşmaya Dayalı Satranç

İç içe geçmiş ajan konuşmalarında araç kullanımını sergilemek için sohbete dayalı bir satranç oyunu oluşturacağız. Her iki oyuncu ajan da 1 aracı çağırabilir ve satranç tahtasında geçerli hamleler yapabilir.

llm_config = {"model": "gpt-4-turbo"}
import chess
import chess.svg
from typing_extensions import Annotated
board = chess.Board()
made_move = False

Gerekli Araçları Tanımlama

Yasal Hamleler Elde Etme Aracı

def get_legal_moves(

) -> Annotated[str, "A list of legal moves in UCI format"]:
return "Possible moves are: " + ",".join(
[str(move) for move in board.legal_moves]
)

Tahtada Hamle Yapma Aracı

def make_move(
move: Annotated[str, "A move in UCI format."]
) -> Annotated[str, "Result of the move."]:
move = chess.Move.from_uci(move)
board.push_uci(str(move))
global made_move
made_move = True

# Display the board.
display(
chess.svg.board(
board,
arrows=[(move.from_square, move.to_square)],
fill={move.from_square: "gray"},
size=200
)
)

# Get the piece name.
piece = board.piece_at(move.to_square)
piece_symbol = piece.unicode_symbol()
piece_name = (
chess.piece_name(piece.piece_type).capitalize()
if piece_symbol.isupper()
else chess.piece_name(piece.piece_type)
)
return f"Moved {piece_name} ({piece_symbol}) from "\
f"{chess.SQUARE_NAMES[move.from_square]} to "\
f"{chess.SQUARE_NAMES[move.to_square]}."

Ajanlar Oluştur

Satranç tahtası için oyuncu ajanları ve tahta proxy (temsilci) ajanlarını yaratacaksınız.

from autogen import ConversableAgent

# Player white agent
player_white = ConversableAgent(
name="Player White",
system_message="You are a chess player and you play as white. "
"First call get_legal_moves(), to get a list of legal moves. "
"Then call make_move(move) to make a move.",
llm_config=llm_config,
)

# Player black agent
player_black = ConversableAgent(
name="Player Black",
system_message="You are a chess player and you play as black. "
"First call get_legal_moves(), to get a list of legal moves. "
"Then call make_move(move) to make a move.",
llm_config=llm_config,
)

def check_made_move(msg):
global made_move
if made_move:
made_move = False
return True
else:
return False

board_proxy = ConversableAgent(
name="Board Proxy",
llm_config=False, # no llm use
is_termination_msg=check_made_move, # stop conversing when a move has been made
default_auto_reply="Please make a move.",
human_input_mode="NEVER",
)

Araçları Kaydedin

Araçların çağırılabilmesi ve çalıştırılabilmesi için araçlar kayıtlı olmalıdır.

from autogen import register_function

for caller in [player_white, player_black]:
register_function(
get_legal_moves,
caller=caller,
executor=board_proxy,
name="get_legal_moves",
description="Get legal moves.",
)

register_function(
make_move,
caller=caller,
executor=board_proxy,
name="make_move",
description="Call this tool to make a move.",
)

player_black.llm_config["tools"]

Tip, fonksiyon açıklaması ve parametreler bu araç tanımına otomatik olarak doldurulur.

İç İçe geçmiş Sohbetleri Kaydedin

Her oyuncu ajanı, satranç tahtasında hamleler yapmak için tahta temsilcisi ajanı ile iç içe bir sohbete sahip olacaktır.

player_white.register_nested_chats(
trigger=player_black,
chat_queue=[
{
"sender": board_proxy,
"recipient": player_white,
"summary_method": "last_msg",
}
],
)

player_black.register_nested_chats(
trigger=player_white,
chat_queue=[
{
"sender": board_proxy,
"recipient": player_black,
"summary_method": "last_msg",
}
],
)

Oyunun başlatılması

Oyun ilk mesajla başlayacaktır.

board = chess.Board()

chat_result = player_black.initiate_chat(
player_white,
message="Let's play chess! Your move.",
max_turns=2,
)

Oyuna Eğlenceli Bir Sohbet Ekleme

player_white = ConversableAgent(
name="Player White",
system_message="You are a chess player and you play as white. "
"First call get_legal_moves(), to get a list of legal moves. "
"Then call make_move(move) to make a move. "
"After a move is made, chitchat to make the game fun.",
llm_config=llm_config,
)

player_black = ConversableAgent(
name="Player Black",
system_message="You are a chess player and you play as black. "
"First call get_legal_moves(), to get a list of legal moves. "
"Then call make_move(move) to make a move. "
"After a move is made, chitchat to make the game fun.",
llm_config=llm_config,
)

for caller in [player_white, player_black]:
register_function(
get_legal_moves,
caller=caller,
executor=board_proxy,
name="get_legal_moves",
description="Get legal moves.",
)

register_function(
make_move,
caller=caller,
executor=board_proxy,
name="make_move",
description="Call this tool to make a move.",
)

player_white.register_nested_chats(
trigger=player_black,
chat_queue=[
{
"sender": board_proxy,
"recipient": player_white,
"summary_method": "last_msg",
"silent": True, # we do not need to inspect the inner conversation
}
],
)

player_black.register_nested_chats(
trigger=player_white,
chat_queue=[
{
"sender": board_proxy,
"recipient": player_black,
"summary_method": "last_msg",
"silent": True,
}
],
)

board = chess.Board()

chat_result = player_black.initiate_chat(
player_white,
message="Let's play chess! Your move.",
max_turns=2,
)

Not: Bu oyuna insan girdisi eklemek için her iki oyuncu aracısına da human_input_mode=”ALWAYS” ekleyin.

Kodlama ve Finansal Analiz

İki ajan sistemi oluşturma fırsatına sahip olacaksınız. Ajanlar, mevcut görevi çözmek için işbirliği yapacak ve insan geri bildirimi talep edecek. İlk sistemde, sıfırdan kod üretmek için bir LLM (Büyük Dil Modeli) kullanacağız ve ikinci sistemde ise kullanıcı tarafından sağlanan koddan yararlanacağız. Bunun bir sınırlaması, birçok diğer modelin aynı özelliğe sahip olmamasıdır. Veya bazen ajanların yalnızca belirli önceden tanımlanmış fonksiyonları kullanmak yerine, serbest stil kod yazmada yaratıcı olmalarını isteyebilirsiniz. Görevi çözmek için kod yazan ve insan geri bildirimi talep eden iki ajanlı bir sistem yapalım.

Birincisi için dil modeli aracısından kodu kendi başına oluşturmasını isteyeceğiz. İkincisi için ayrıca kullanıcı tanımlı bir kod kullanacağız.

llm_config = {"model": "gpt-4-turbo"}

Bir Kod Yürütücüsü Tanımlama

Öncelikle bir kod yürütücü oluşturmamız gerekiyor. Autogen’de Docker tabanlı ve Jupyter notebook tabanlı yürütme dahil olmak üzere birkaç farklı kod yürütme türü vardır.

from autogen.coding import LocalCommandLineCodeExecutor
executor = LocalCommandLineCodeExecutor(
timeout=60, # will timeout in 60 seconds
work_dir="coding", # all results are generated under the coding folder
)

Ajan Oluşturulması

from autogen import ConversableAgent, AssistantAgent
  1. Kod yürütücü konfigürasyonuna sahip ajan
code_executor_agent = ConversableAgent(
name="code_executor_agent",
llm_config=False,
code_execution_config={"executor": executor},
human_input_mode="ALWAYS",
default_auto_reply=
"Please continue. If everything is done, reply 'TERMINATE'.",
)

2. Kod yazma özelliğine sahip ajan

code_writer_agent = AssistantAgent(
name="code_writer_agent",
llm_config=llm_config,
code_execution_config=False, # does not execute code
human_input_mode="NEVER",
)
code_writer_agent_system_message = code_writer_agent.system_message
print(code_writer_agent_system_message) # system message of the code writer agent

Görev

İki ajandan bir hisse analizi görevi üzerinde işbirliği yapmalarını isteyin.

import datetime

today = datetime.datetime.now().date()
message = f"Today is {today}. "\
"Create a plot showing stock gain YTD for NVDA and TLSA. "\
"Make sure the code is in markdown code block and save the figure"\
" to a file ytd_stock_gains.png."""

chat_result = code_executor_agent.initiate_chat(
code_writer_agent,
message=message,
)

Çizim

LLM’nin serbest stil kod oluşturma işlemi çubuk grafiği gibi farklı bir çizim türünü seçebildiğinden grafiğiniz çalışmadan çalıştırmaya farklılık gösterebilir. Bir çubuk grafiği oluşturuyorsa, çubuk grafiği yerine belirli bir çizim türünü isteyerek tercihinizi doğrudan belirtebileceğinizi unutmayın. Aracı, kodu otomatik olarak bir .py dosyasına ve grafiği ise bir .png dosyasına kaydeder.

import os
from IPython.display import Image

Image(os.path.join("coding", "ytd_stock_gains.png"))

Kullanıcı Tanımlı Fonksiyonlar

LLM’den her seferinde hisse senedi verilerini indirmek ve grafikleri çizmek için kod oluşturmasını istemek yerine, bu iki görev için fonksiyonlar tanımlayabilir ve LLM’nin bu fonksiyonları kodda çağırmasını sağlayabilirsiniz.

def get_stock_prices(stock_symbols, start_date, end_date):
"""Get the stock prices for the given stock symbols between
the start and end dates.

Args:
stock_symbols (str or list): The stock symbols to get the
prices for.
start_date (str): The start date in the format
'YYYY-MM-DD'.
end_date (str): The end date in the format 'YYYY-MM-DD'.

Returns:
pandas.DataFrame: The stock prices for the given stock
symbols indexed by date, with one column per stock
symbol.
"""
import yfinance

stock_data = yfinance.download(
stock_symbols, start=start_date, end=end_date
)
return stock_data.get("Close")

def plot_stock_prices(stock_prices, filename):
"""Plot the stock prices for the given stock symbols.

Args:
stock_prices (pandas.DataFrame): The stock prices for the
given stock symbols.
"""
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 5))
for column in stock_prices.columns:
plt.plot(
stock_prices.index, stock_prices[column], label=column
)
plt.title("Stock Prices")
plt.xlabel("Date")
plt.ylabel("Price")
plt.grid(True)
plt.savefig(filename)

Kullanıcı Tanımlı Fonksiyon Yeni Bir Yürütücü Oluşturun

Kod yazarı ajanına bu iki fonksiyonun varlığını bildirmemiz gerekiyor. Kod yazarı ajanının sistem mesajını, tüm bu iki fonksiyonun bilgisini kapsamayan bazı ek istemler yazarak değiştireceğiz.

executor = LocalCommandLineCodeExecutor(
timeout=60,
work_dir="coding",
functions=[get_stock_prices, plot_stock_prices],
)

code_writer_agent_system_message += executor.format_functions_for_prompt()
print(code_writer_agent_system_message)

İlk kısım sistem mesajlarıdır ancak sonrasında kullanıcı tanımlı fonksiyonlara erişim sağladığımızı görebilirsiniz. Bunlara fonksiyon adı verilen modülden fonksiyon adlarına göre ulaşabiliriz.

Ajanları Yeni Sistem Mesajıyla Güncelleyelim

code_writer_agent = ConversableAgent(
name="code_writer_agent",
system_message=code_writer_agent_system_message,
llm_config=llm_config,
code_execution_config=False,
human_input_mode="NEVER",
)

code_executor_agent = ConversableAgent(
name="code_executor_agent",
llm_config=False,
code_execution_config={"executor": executor},
human_input_mode="ALWAYS",
default_auto_reply=
"Please continue. If everything is done, reply 'TERMINATE'.",
)

Aynı Göreve Tekrar Başlatma

chat_result = code_executor_agent.initiate_chat(
code_writer_agent,
message=f"Today is {today}."
"Download the stock prices YTD for NVDA and TSLA and create"
"a plot. Make sure the code is in markdown code block and "
"save the figure to a file stock_prices_YTD_plot.png.",
)

Sonuçları Çizdirelim

Image(os.path.join("coding", "stock_prices_YTD_plot.png"))

Planlama ve Hisse Raporu Oluşturma

Çoklu ajan grup sohbetlerini öğrenelim ve geçen ay ayrıntılı bir rapor ve hisse senedi performansı oluşturmak için işbirliği yapan özel bir grup sohbeti oluşturalım. Bu karmaşık görevi tamamlamak planlamayı gerektirir (grup sohbetine bir planlama ajanı eklemek). Ayrıca konuşmacının grup sohbetine geçişini özelleştirmeyi de öğreneceğiz.

llm_config={"model": "gpt-4-turbo"}

task = "Write a blogpost about the stock price performance of "\
"Nvidia in the past month. Today's date is 2024-04-23."

Grup Sohbeti Oluşturun

Bu grup sohbeti şu ajanları içerir:

  1. User_proxy veya Admin: Kullanıcının rapor hakkında yorum yapmasına ve yazarın raporda düzeltme yapmasını istemesine olanak tanır.
  2. Planlayıcı: Görevi tamamlamak için gereken ilgili bilgileri belirler.
  3. Mühendis: Planlayıcının tanımladığı planı kullanarak kod yazar.
  4. Yürütücü (Executor): Mühendis tarafından yazılan kodu yürütür.
  5. Yazar (Writer): Raporu yazar.
import autogen
user_proxy = autogen.ConversableAgent(
name="Admin",
system_message="Give the task, and send "
"instructions to writer to refine the blog post.",
code_execution_config=False,
llm_config=llm_config,
human_input_mode="ALWAYS",
)
planner = autogen.ConversableAgent(
name="Planner",
system_message="Given a task, please determine "
"what information is needed to complete the task. "
"Please note that the information will all be retrieved using"
" Python code. Please only suggest information that can be "
"retrieved using Python code. "
"After each step is done by others, check the progress and "
"instruct the remaining steps. If a step fails, try to "
"workaround",
description="Planner. Given a task, determine what "
"information is needed to complete the task. "
"After each step is done by others, check the progress and "
"instruct the remaining steps",
llm_config=llm_config,
)
engineer = autogen.AssistantAgent(
name="Engineer",
llm_config=llm_config,
description="An engineer that writes code based on the plan "
"provided by the planner.",
)

Bir dict konfigürasyonu sağlayarak alternatif bir kod yürütme yöntemi kullanacaksınız. Ancak isterseniz her zaman LocalCommandLineCodeExecutor’u kullanabilirsiniz. code_execution_config hakkında daha fazla ayrıntı için buraya bakabilirsiniz:

https://microsoft.github.io/autogen/docs/reference/agentchat/conversable_agent/#__init__

executor = autogen.ConversableAgent(
name="Executor",
system_message="Execute the code written by the "
"engineer and report the result.",
human_input_mode="NEVER",
code_execution_config={
"last_n_messages": 3,
"work_dir": "coding",
"use_docker": False,
},
)

writer = autogen.ConversableAgent(
name="Writer",
llm_config=llm_config,
system_message="Writer."
"Please write blogs in markdown format (with relevant titles)"
" and put the content in pseudo ```md``` code block. "
"You take feedback from the admin and refine your blog.",
description="Writer."
"Write blogs based on the code execution results and take "
"feedback from the admin to refine the blog."
)

Grup Sohbetini Tanımlayın

groupchat = autogen.GroupChat(
agents=[user_proxy, engineer, writer, executor, planner],
messages=[],
max_round=10,
)
manager = autogen.GroupChatManager(
groupchat=groupchat, llm_config=llm_config
)

Grup Sohbetini Başlatma

groupchat_result = user_proxy.initiate_chat(
manager,
message=task,
)

Konuşmacı Seçimi Politikası Ekleme

user_proxy = autogen.ConversableAgent(
name="Admin",
system_message="Give the task, and send "
"instructions to writer to refine the blog post.",
code_execution_config=False,
llm_config=llm_config,
human_input_mode="ALWAYS",
)

planner = autogen.ConversableAgent(
name="Planner",
system_message="Given a task, please determine "
"what information is needed to complete the task. "
"Please note that the information will all be retrieved using"
" Python code. Please only suggest information that can be "
"retrieved using Python code. "
"After each step is done by others, check the progress and "
"instruct the remaining steps. If a step fails, try to "
"workaround",
description="Given a task, determine what "
"information is needed to complete the task. "
"After each step is done by others, check the progress and "
"instruct the remaining steps",
llm_config=llm_config,
)

engineer = autogen.AssistantAgent(
name="Engineer",
llm_config=llm_config,
description="Write code based on the plan "
"provided by the planner.",
)

writer = autogen.ConversableAgent(
name="Writer",
llm_config=llm_config,
system_message="Writer. "
"Please write blogs in markdown format (with relevant titles)"
" and put the content in pseudo ```md``` code block. "
"You take feedback from the admin and refine your blog.",
description="After all the info is available, "
"write blogs based on the code execution results and take "
"feedback from the admin to refine the blog. ",
)

executor = autogen.ConversableAgent(
name="Executor",
description="Execute the code written by the "
"engineer and report the result.",
human_input_mode="NEVER",
code_execution_config={
"last_n_messages": 3,
"work_dir": "coding",
"use_docker": False,
},
)
groupchat = autogen.GroupChat(
agents=[user_proxy, engineer, writer, executor, planner],
messages=[],
max_round=10,
allowed_or_disallowed_speaker_transitions={
user_proxy: [engineer, writer, executor, planner],
engineer: [user_proxy, executor],
writer: [user_proxy, planner],
executor: [user_proxy, engineer, planner],
planner: [user_proxy, engineer, writer],
},
speaker_transitions_type="allowed",
)
manager = autogen.GroupChatManager(
groupchat=groupchat, llm_config=llm_config
)

groupchat_result = user_proxy.initiate_chat(
manager,
message=task,
)

Ayrıca planlayıcıyı bir fonksiyon çağrısı olarak veya AutoBuild’ı kullanarak kullanarak planlama ve görev ayrıştırma da yapabilirsiniz.

Daha Fazla Bilgi İçin

Daha gelişmiş özellikler için web sitesini, Github’u ve Discord’u kontrol edin.

Kaynak

Deeplearning.ai, (2024), AI Agentic Design Patterns with AutoGen:

[https://www.deeplearning.ai/short-courses/ai-agentic-design-patterns-with-autogen/]

--

--

Cahit Barkin Ozer
Cahit Barkin Ozer

Written by Cahit Barkin Ozer

Üretken YZ başta olmak üzere teknoloji alanındaki yenilikleri öğrenip sizlerle paylaşıyorum. Youtube Kanalım: https://www.youtube.com/@cbarkinozer

No responses yet