시리얼 체인 에이전트 워크플로우 – 콘텐츠 재가공
시리얼 체인 에이전트 워크플로우 – 콘텐츠 재가공 (Serial Chain Agent Workflow - Content Repurposing)
이 구현에서는 일련의 전문 LLM 호출을 이용해 긴 형식의 콘텐츠를 재미있는 Twitter 스레드로 바꿔주는 LLM 에이전트 워크플로우를 만드는 방법을 살펴볼 거예요. 시리얼 체인 패턴은 복잡한 콘텐츠 생성·변환 작업에 아주 강력한 방식이에요.
출처: 문서
본문
소개 (Introduction)
이 구현에서는 일련의 전문 LLM 호출을 사용해서 긴 형식의 콘텐츠를 매력적인 Twitter 스레드로 변환하는 LLM 에이전트 워크플로우를 어떻게 만드는지 살펴볼 거예요.
**시리얼 체인 에이전트 워크플로우(serial chain agent workflow)**는 복잡한 콘텐츠 생성과 변환 작업에서 강력한 패턴을 보여줘요. 핵심은 언어 모델에 순차적으로 호출을 하는 건데, 각 호출이 이전 호출의 출력을 이어받아서 사용해요. 이렇게 하면 콘텐츠를 원하는 결과물 쪽으로 점진적으로 다듬어가는 전문 처리 단계들의 체인이 만들어져요.
우리의 콘텐츠 재가공 워크플로우가 이 패턴을 완벽하게 보여줘요. 블로그 포스트나 영상 대본으로 시작해서, 아래의 순차적인 단계를 거쳐 정성껏 만든 Twitter 스레드로 변환합니다.
LLM Call 1: 핵심 정보 추출 (Extract Key Information)
- 원본 콘텐츠를 분석해서 가장 가치 있는 통찰, 통계, 인용, 핵심 주장을 찾아내요.
LLM Call 2: 스레드 흐름 구조화 (Structure Thread Flow)
- 추출된 정보를 논리적인 스레드 구조로 정리하고, 강력한 훅(hook)과 만족스러운 결말을 만들어요.
LLM Call 3: 트윗 텍스트 생성 (Generate Tweet Text)
- 구조화된 개요를 실제 트윗 텍스트로 바꾸고, 각 트윗이 매력적이고 글자 수 제한 안에 드는지 확인해요.
LLM Call 4: 참여도 향상 (Enhance Engagement)
- 해시태그, 클릭 유도(Call-To-Action), 시각 콘텐츠 제안을 추가해서 참여도를 극대화해요.
시리얼 체인 워크플로우 이해하기 (Understanding Serial Chain Workflow)
시리얼 체인 패턴의 강점은 단순함과 유연성에 있어요. 체인 안의 각 LLM은 전체 과정의 한 측면에 집중하는 전문 작업을 수행해요. 이렇게 나누면 LLM이 복잡한 전체 작업을 한 번에 처리하려고 하지 않고, 특정 작업에서 뛰어난 성과를 낼 수 있어요.
워크플로우는 입력 콘텐츠를 연속적인 LLM 호출로 처리하는데, 각 단계가 이전 호출의 출력을 받아서 더 변형시켜요. 이 순차 처리는 콘텐츠가 매 단계마다 목표 형식에 맞게 점점 더 정제되고 전문화되는 파이프라인을 만들어요.
이제 MistralAI LLM을 이용해 이 시리얼 체인 워크플로우를 구현해서, 장황한 블로그 콘텐츠를 간결하고 매력적인 소셜 미디어 형식으로 바꾸는 강력한 콘텐츠 재가공 시스템을 만들어 볼게요.
솔루션 아키텍처 (Solution Architecture)

설치 (Installation)
Python Output
!pip install -U mistralai
임포트 (Imports)
import os
from mistralai.client import Mistral
from typing import List, Dict, Any, Optional
import json
from IPython.display import display, Markdown
Mistral 클라이언트 초기화 (Initialize the Mistral client)
api_key = "<YOUR MISTRAL API KEY>" # get it from https://console.mistral.ai
model = "mistral-small-latest"
client = Mistral(api_key=api_key)
LLM 쿼리 실행 (Execute LLM Query)
주어진 프롬프트와 선택적인 시스템 프롬프트로 Mistral LLM을 실행하는 함수예요.
def execute_llm_query(prompt: str, system_prompt: Optional[str] = None) -> str:
"""Run Mistral LLM with the given prompt and optional system prompt."""
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
response = client.chat.complete(
model=model,
messages=messages,
)
return response.choices[0].message.content
핵심 정보 추출 (Extract Key Information)
원본 블로그 포스트나 영상 대본에서 핵심 정보를 추출하는 LLM Call 1이에요.
def extract_key_information(content: str) -> str:
"""
LLM Call 1: Extract key information from the original content.
Args:
content: The original blog post or video transcript
Returns:
Extracted key points, insights, and quotable moments
"""
system_prompt = """You are an expert content analyst. Your task is to extract the most important
information from the provided content. Focus on key insights, main arguments,
surprising facts, statistics, and quotable moments that would resonate with a social media audience.
Organize your output as a structured list with priority rankings."""
user_prompt = f"""Please extract the most important and engaging information from the following content.
Focus on extracting:
1. The main thesis or argument
2. Key supporting points (limit to 5-7)
3. Surprising facts or statistics
4. Quotable moments or compelling phrases
5. Any counterintuitive insights
For each extracted item, include a relevance score from 1-10 to indicate its importance.
CONTENT:
{content}
"""
return execute_llm_query(user_prompt, system_prompt)
스레드 구조 만들기 (Create Thread Structure)
추출된 정보로 논리적인 스레드 구조를 만드는 LLM Call 2예요.
def create_thread_structure(extracted_info: str) -> str:
"""
LLM Call 2: Create a logical thread structure from the extracted information.
Args:
extracted_info: The extracted key information from the first LLM call
Returns:
A structured outline for the tweet thread
"""
system_prompt = """You are an expert social media strategist specializing in Twitter/X.
Your task is to organize extracted information into a compelling and logical tweet thread structure.
Focus on creating a strong hook, a clear flow between tweets, and a satisfying conclusion."""
user_prompt = f"""Using the following extracted information, create a structured outline for
a Twitter thread of 5-8 tweets.
Organize the content to maximize engagement with:
1. A powerful hook for the first tweet that captures attention
2. A logical flow of information across the thread
3. Clear transitions between related points
4. A strong conclusion that leaves the reader with something to think about or do
For each tweet in the outline, include a brief note about its purpose in the thread.
EXTRACTED INFORMATION:
{extracted_info}
"""
return execute_llm_query(user_prompt, system_prompt)
트윗 스레드 생성 (Generate Tweet Thread)
스레드 구조를 바탕으로 실제 트윗들을 생성하는 LLM Call 3이에요.
def generate_tweet_thread(thread_structure: str) -> str:
"""
LLM Call 3: Generate the actual tweets based on the thread structure.
Args:
thread_structure: The structured outline from the second LLM call
Returns:
A complete tweet thread with numbered tweets
"""
system_prompt = """You are a master of Twitter communication. Your task is to transform
a structured outline into engaging, shareable tweets for a thread. Ensure each tweet is
compelling on its own while flowing naturally as part of a thread. Keep each tweet under
280 characters. Use clear, concise language with high emotional appeal."""
user_prompt = f"""Using the following thread structure, craft an engaging Twitter thread.
Guidelines:
1. Each tweet must be 280 characters or less
2. First tweet should hook the reader immediately
3. Include a clear way to indicate the tweets are connected (e.g., 1/7, 2/7)
4. Use simple, direct language that's easy to understand
5. Write in a conversational tone
6. Break complex ideas into digestible chunks
7. End the thread with a clear conclusion or call to action
THREAD STRUCTURE:
{thread_structure}
Format your response as a numbered list of tweets, with each tweet ready to copy and paste.
"""
return execute_llm_query(user_prompt, system_prompt)
참여 요소 추가 (Add Engagement Elements)
트윗 스레드에 참여 요소를 더해서 향상시키는 LLM Call 4예요.
def add_engagement_elements(tweet_thread: str) -> str:
"""
LLM Call 4: Enhance the tweet thread with engagement elements.
Args:
tweet_thread: The generated tweet thread from the third LLM call
Returns:
The final enhanced tweet thread with engagement elements
"""
system_prompt = """You are a social media engagement expert. Your task is to enhance
a tweet thread with elements that increase engagement, such as relevant hashtags,
strategic mentions, calls to action."""
user_prompt = f"""Enhance the following tweet thread with elements to maximize engagement.
For each tweet, consider adding:
1. 1-3 relevant hashtags. (where appropriate, not every tweet needs hashtags)
2. Strategic calls to action (asks for replies, retweets, etc.)
3. Emoticons or Unicode symbols to add visual interest (use sparingly)
4. Hashtags should be at the end of the tweet in a new line.
Keep each tweet under 280 characters even after adding these elements.
TWEET THREAD:
{tweet_thread}
Format your response as a numbered list of enhanced tweets, ready to post.
"""
return execute_llm_query(user_prompt, system_prompt)
콘텐츠 재가공 체인 (Content Repurposing Chain)
블로그 포스트나 영상 대본을 Twitter 스레드로 바꾸는 전체 콘텐츠 재가공 체인을 실행해요.
def content_repurposing_chain(content: str) -> Dict[str, str]:
"""
Run the full content repurposing chain to convert a blog post or video transcript
into a Twitter thread.
Args:
content: The original blog post or video transcript
Returns:
A dictionary containing outputs from each step in the chain
"""
print("Step 1: Extracting key information...")
extracted_info = extract_key_information(content)
print("Step 2: Creating thread structure...")
thread_structure = create_thread_structure(extracted_info)
print("Step 3: Generating tweet thread...")
tweet_thread = generate_tweet_thread(thread_structure)
print("Step 4: Adding engagement elements...")
enhanced_thread = add_engagement_elements(tweet_thread)
return {
"extracted_information": extracted_info,
"thread_structure": thread_structure,
"base_tweet_thread": tweet_thread,
"enhanced_tweet_thread": enhanced_thread
}
의료 분야 AI에 대한 샘플 블로그 포스트 (Sample Blog Post on AI in Healthcare)
sample_blog_post = '''# AI and Its Effects on the Medical Industry
Artificial Intelligence (AI) is rapidly transforming various sectors, and the medical industry is at the forefront of this revolution. The integration of AI in healthcare holds immense potential to improve patient outcomes, streamline operations, and drive innovation. However, it also presents challenges that need to be carefully navigated. This blog post delves into the multifaceted impact of AI on the medical industry, exploring its benefits, drawbacks, and the path forward.
## The Promise of AI in Healthcare
AI has the capability to analyze vast amounts of data with unprecedented speed and accuracy. In the medical field, this translates to improved diagnostics, where AI algorithms can detect patterns and anomalies that might go unnoticed by human doctors. For instance, AI can assist in the early detection of diseases such as cancer by analyzing medical images and identifying subtle changes that indicate the presence of tumors. This early detection can significantly improve patient prognoses and increase survival rates.
One of the most exciting applications of AI in healthcare is the development of personalized treatment plans. By analyzing a patient's genetic information, medical history, and lifestyle factors, AI can tailor treatments to individual needs. This personalized approach can lead to more effective treatments and better patient outcomes, as it takes into account the unique characteristics of each patient. For example, AI can help identify the most suitable chemotherapy regimen for a cancer patient based on their genetic profile, reducing the trial-and-error approach that is often necessary in traditional treatment methods.
AI also has the potential to enhance the efficiency of healthcare operations. Administrative tasks such as scheduling appointments, managing patient records, and even assisting in surgeries can be automated through AI. Robotic systems powered by AI can perform surgeries with greater precision and fewer complications, leading to faster recovery times for patients. Additionally, AI-driven chatbots can handle routine inquiries and provide patient education, freeing up healthcare professionals to focus on more complex tasks.
Predictive analytics is another area where AI is making significant strides in the medical industry. By analyzing large datasets, AI can predict disease outbreaks, patient deterioration, and other health trends. This predictive capability allows healthcare providers to be better prepared and proactive in their approach. For example, AI can help hospitals anticipate patient volumes and allocate resources more effectively, ensuring that patients receive timely care.
Remote monitoring is an emerging application of AI in healthcare that is gaining traction. AI-powered wearable devices and remote monitoring systems can track patients' vital signs and health metrics in real-time. This continuous monitoring allows for early intervention, especially for patients with chronic conditions such as diabetes or heart disease. By detecting changes in a patient's health status early, healthcare providers can intervene before a condition worsens, improving patient outcomes and reducing healthcare costs.
## Challenges and Considerations
While the benefits of AI in the medical industry are numerous, there are also challenges that need to be addressed. One of the primary concerns is data privacy. The use of AI in healthcare involves handling sensitive patient data, and there is a risk of data breaches and misuse. Ensuring the security and privacy of patient data is crucial to maintaining trust in AI-driven healthcare solutions. Robust data governance frameworks and stringent security measures are essential to mitigate these risks.
Another challenge is the potential for bias and discrimination in AI algorithms. AI systems are trained on large datasets, and if these datasets contain biases, the AI algorithms can perpetuate these biases in their decision-making processes. This can lead to inaccurate diagnoses or treatment recommendations for certain demographic groups. To address this issue, it is important to ensure that the datasets used to train AI algorithms are diverse and representative of the entire population. Additionally, ongoing monitoring and evaluation of AI systems are necessary to identify and correct any biases that may emerge.
Over-reliance on AI is another concern in the medical industry. As AI tools become more integrated into healthcare practices, there is a risk that healthcare professionals may become too dependent on them, potentially missing critical nuances that require human judgment. It is essential to strike a balance between leveraging the capabilities of AI and maintaining the clinical skills of healthcare professionals. Continuous education and training are necessary to ensure that healthcare professionals can effectively use AI tools while retaining their clinical expertise.
The high initial costs of implementing AI in healthcare can be a barrier, especially for smaller healthcare providers or those in developing regions. Investing in AI technology, infrastructure, and training requires significant resources. However, the long-term benefits of AI in improving patient outcomes and streamlining operations can outweigh these initial costs. Policymakers and healthcare organizations need to work together to make AI more accessible and affordable for all.
Regulatory and ethical challenges also arise with the use of AI in healthcare. Issues such as accountability for AI-driven decisions, informed consent, and the potential for job displacement need to be addressed. Clear guidelines and regulations are necessary to ensure that AI is used responsibly and ethically in the medical industry. Collaboration between healthcare providers, policymakers, and technology companies is essential to develop these guidelines and promote the responsible use of AI.
## Conclusion
AI has the potential to revolutionize the medical industry by improving diagnostics, personalizing treatment plans, enhancing efficiency, and enabling predictive analytics. However, it also presents challenges such as data privacy concerns, bias, over-reliance on technology, high initial costs, and regulatory hurdles. To fully realize the benefits of AI in healthcare, it is crucial to address these challenges through robust data governance, ethical guidelines, and continuous education and training for healthcare professionals. By striking a balance between innovation and caution, AI can become a powerful tool in improving patient care and outcomes, ultimately transforming the medical industry for the better.'''
Python
results = content_repurposing_chain(sample_blog_post)
Python
results.keys()
최종 향상된 트윗 스레드 (Final Enhanced tweet thread)
Python Output
display(Markdown(results['enhanced_tweet_thread']))
각 LLM 호출의 출력을 개별적으로 확인 (We can check each LLM call output individually)
LLM Call-1: 핵심 정보 추출 (Extract key Information)
Python Output
display(Markdown(results['extracted_information']))
LLM Call-2: 스레드 구조 만들기 (Create thread structure)
Python Output
display(Markdown(results['thread_structure']))
LLM Call-3: 기본 트윗 스레드 만들기 (Create base tweet thread)
Python Output
display(Markdown(results['base_tweet_thread']))
LLM Call-4: 향상된 트윗 스레드 (Enhanced Tweet Thread)
Python Output
display(Markdown(results['enhanced_tweet_thread']))