Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Clean Code
- 함수형 프로그래밍
- JWT
- Stream
- 인텔리제이 단축키
- optional
- Factory Method Pattern
- Java8
- 카프카
- 싱글톤
- Authentication
- Spring Security
- orelse
- junit5
- 디자인패턴
- 패스트캠퍼스 #환급챌린지 #패스트캠퍼스후기 #습관형성 #직장인자기계발 #오공완
- SpringBoot
- #패스트캠퍼스 #환급챌린지 #패스트캠퍼스후기 #습관형성 #직장인자기계발 #오공완
- Java
- TDD
- producer
- orElseGet
- signWith
- consumer
- topic
- git cli
- mokito
- kafka
- effective java
- Functional Programming
Archives
- Today
- Total
goodbye
패스트캠퍼스 환급챌린지 38일차 : 테디노트의 RAG 비법노트 강의 후기 본문
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성하였습니다
https://fastcampus.info/4n8ztzq
(~6/20) 50일의 기적 AI 환급반💫 | 패스트캠퍼스
초간단 미션! 하루 20분 공부하고 수강료 전액 환급에 AI 스킬 장착까지!
fastcampus.co.kr
패스트캠퍼스 환급챌린지 38일차!
1) 공부 시작 시간 인증

2) 공부 종료 시간 인증

3) 강의 수강 클립 인증

4) 학습 인증샷

5) 학습통계

Today I Learned
보고서 작성 정의
다음은 인터뷰 내용을 바탕으로 보고서 작성 가이드라인을 정의하고 보고서 작성 함수를 정의합니다.
# 보고서 작성 지시사항
report_writer_instructions = """You are a technical writer creating a report on this overall topic:
{topic}
You have a team of analysts. Each analyst has done two things:
1. They conducted an interview with an expert on a specific sub-topic.
2. They write up their finding into a memo.
Your task:
1. You will be given a collection of memos from your analysts.
2. Carefully review and analyze the insights from each memo.
3. Consolidate these insights into a detailed and comprehensive summary that integrates the central ideas from all the memos.
4. Organize the key points from each memo into the appropriate sections provided below, ensuring that each section is logical and well-structured.
5. Include all required sections in your report, using `### Section Name` as the header for each.
6. Aim for approximately 250 words per section, providing in-depth explanations, context, and supporting details.
**Sections to consider (including optional ones for greater depth):**
- **Background**: Theoretical foundations, key concepts, and preliminary information necessary to understand the methodology and results.
- **Related Work**: Overview of prior studies and how they compare or relate to the current research.
- **Problem Definition**: A formal and precise definition of the research question or problem the paper aims to address.
- **Methodology (or Methods)**: Detailed description of the methods, algorithms, models, data collection processes, or experimental setups used in the study.
- **Implementation Details**: Practical details of how the methods or models were implemented, including software frameworks, computational resources, or parameter settings.
- **Experiments**: Explanation of experimental protocols, datasets, evaluation metrics, procedures, and configurations employed to validate the methods.
- **Results**: Presentation of experimental outcomes, often with statistical tables, graphs, figures, or qualitative analyses.
To format your report:
1. Use markdown formatting.
2. Include no pre-amble for the report.
3. Use no sub-heading.
4. Start your report with a single title header: ## Insights
5. Do not mention any analyst names in your report.
6. Preserve any citations in the memos, which will be annotated in brackets, for example [1] or [2].
7. Create a final, consolidated list of sources and add to a Sources section with the `## Sources` header.
8. List your sources in order and do not repeat.
[1] Source 1
[2] Source 2
Here are the memos from your analysts to build your report from:
{context}"""
# 보고서 작성 함수 정의
def write_report(state: ResearchGraphState):
# 모든 섹션 가져오기
sections = state["sections"]
topic = state["topic"]
# 모든 섹션을 하나의 문자열로 연결
formatted_str_sections = "\\n\\n".join([f"{section}" for section in sections])
# 섹션을 요약하여 최종 보고서 작성
system_message = report_writer_instructions.format(
topic=topic, context=formatted_str_sections
)
report = llm.invoke(
[SystemMessage(content=system_message)]
+ [HumanMessage(content=f"Write a report based upon these memos.")]
)
return {"content": report.content}
# 서론과 결론 작성 지시사항
intro_conclusion_instructions = """You are a technical writer finishing a report on {topic}
You will be given all of the sections of the report.
You job is to write a crisp and compelling introduction or conclusion section.
The user will instruct you whether to write the introduction or conclusion.
Include no pre-amble for either section.
Target around 200 words, crisply previewing (for introduction), or recapping (for conclusion) all of the sections of the report.
Use markdown formatting.
For your introduction, create a compelling title and use the # header for the title.
For your introduction, use ## Introduction as the section header.
For your conclusion, use ## Conclusion as the section header.
Here are the sections to reflect on for writing: {formatted_str_sections}"""
# 서론 작성 함수 정의
def write_introduction(state: ResearchGraphState):
# 모든 섹션 가져오기
sections = state["sections"]
topic = state["topic"]
# 모든 섹션을 하나의 문자열로 연결
formatted_str_sections = "\\n\\n".join([f"{section}" for section in sections])
# 섹션을 요약하여 서론 작성
instructions = intro_conclusion_instructions.format(
topic=topic, formatted_str_sections=formatted_str_sections
)
intro = llm.invoke(
[instructions] + [HumanMessage(content=f"Write the report introduction")]
)
return {"introduction": intro.content}
# 결론 작성 함수 정의
def write_conclusion(state: ResearchGraphState):
# 모든 섹션 가져오기
sections = state["sections"]
topic = state["topic"]
# 모든 섹션을 하나의 문자열로 연결
formatted_str_sections = "\\n\\n".join([f"{section}" for section in sections])
# 섹션을 요약하여 결론 작성
instructions = intro_conclusion_instructions.format(
topic=topic, formatted_str_sections=formatted_str_sections
)
conclusion = llm.invoke(
[instructions] + [HumanMessage(content=f"Write the report conclusion")]
)
return {"conclusion": conclusion.content}
# 최종 보고서 작성 함수 정의
def finalize_report(state: ResearchGraphState):
# 모든 섹션을 모아 최종 보고서 작성
content = state["content"]
if content.startswith("## Insights"):
content = content.strip("## Insights")
if "## Sources" in content:
try:
content, sources = content.split("\\n## Sources\\n")
except:
sources = None
else:
sources = None
final_report = (
state["introduction"]
+ "\\n\\n---\\n\\n## Main Idea\\n\\n"
+ content
+ "\\n\\n---\\n\\n"
+ state["conclusion"]
)
if sources is not None:
final_report += "\\n\\n## Sources\\n" + sources
return {"final_report": final_report}
그래프 정의
from langgraph.graph import StateGraph
from langgraph.checkpoint.memory import MemorySaver
from langgraph.constants import START, END
from langchain_teddynote.graphs import visualize_graph
# 그래프 생성
builder = StateGraph(ResearchGraphState)
# 노드 정의
builder.add_node("create_analysts", create_analysts)
builder.add_node("human_feedback", human_feedback)
builder.add_node("conduct_interview", interview_builder.compile())
builder.add_node("write_report", write_report)
builder.add_node("write_introduction", write_introduction)
builder.add_node("write_conclusion", write_conclusion)
builder.add_node("finalize_report", finalize_report)
# 엣지 정의
builder.add_edge(START, "create_analysts")
builder.add_edge("create_analysts", "human_feedback")
builder.add_conditional_edges(
"human_feedback", initiate_all_interviews, ["create_analysts", "conduct_interview"]
)
# 인터뷰 결과 보고서 작성
builder.add_edge("conduct_interview", "write_report")
builder.add_edge("conduct_interview", "write_introduction")
builder.add_edge("conduct_interview", "write_conclusion")
# 보고서 최종 정리
builder.add_edge(
["write_conclusion", "write_report", "write_introduction"], "finalize_report"
)
builder.add_edge("finalize_report", END)
# 컴파일
memory = MemorySaver()
graph = builder.compile(interrupt_before=["human_feedback"], checkpointer=memory)
visualize_graph(graph)
그래프 실행
# 입력 데이터 설정
max_analysts = 3
topic = "Explain how Modular RAG differs from traditional Naive RAG and the benefits of using it at the production level."
# config 설정
config = RunnableConfig(
recursion_limit=30,
configurable={"thread_id": random_uuid()},
)
# 입력 데이터 설정
inputs = {"topic": topic, "max_analysts": max_analysts}
# 그래프 실행: 첫 번째 중단 지점까지
invoke_graph(graph, inputs, config)
# human_feedback 을 추가하여 분석가를 설정합니다.
# 새로운 분석가 추가
graph.update_state(
config,
{"human_analyst_feedback": "Add Prof. Jeffrey Hinton as a head of AI analyst"},
as_node="human_feedback",
)
# 그래프 실행
invoke_graph(graph, None, config)
Functional API
- Functional API를 사용하면 기존 코드를 최소한으로 변경하여 LangGraph의 주요 기능을 애플리케이션에 추가할 수 있습니다.
- if이 API는 분기 및 제어 흐름에 명령문, 루프, 함수 호출 과 같은 표준 언어 기본 요소를 사용할 수 있는 기존 코드에 이러한 기능을 통합하도록 설계되었습니다
- for. 코드를 명시적인 파이프라인이나 DAG로 재구성해야 하는 많은 데이터 오케스트레이션 프레임워크와 달리, Functional API를 사용하면 엄격한 실행 모델을 적용하지 않고도 이러한 기능을 통합할 수 있습니다.
- Functional API는 두 가지 주요 구성 요소를 사용합니다.
- @entrypoint
- @task
Functional API vs. Graph API
- 보다 선언적인 접근 방식을 선호하는 사용자를 위해 LangGraph의 Graph API를 사용하면 Graph 패러다임을 사용하여 워크플로를 정의할 수 있습니다.
- 두 API는 동일한 기본 런타임을 공유하므로 동일한 애플리케이션에서 함께 사용할 수 있습니다.
- 몇 가지 주요 차이점은 다음과 같습니다.
- 제어 흐름
- 함수형 API는 그래프 구조에 대해 생각할 필요가 없습니다. 표준 Python 구문을 사용하여 워크플로를 정의할 수 있습니다. 이렇게 하면 일반적으로 작성해야 할 코드 양이 줄어듭니다.
- 단기 메모리
- GraphAPI는 State를리듀서를@entrypoint@tasks선언해야 하며 그래프 상태의 업데이트를 관리하기 위해 정의해야 할 수도 있습니다 . 또한 상태가 함수 범위에 속하고 함수 간에 공유되지 않으므로 명시적인 상태 관리가 필요하지 않습니다.
- 체크포인팅
- 두 API 모두 체크포인트를 생성하고 사용합니다. 그래프 API 에서는 모든 슈퍼스텝 마다 새로운 체크포인트가 생성됩니다 .함수형 API 에서는 작업이 실행될 때 새 체크포인트를 생성하는 대신, 해당 진입점과 연결된 기존 체크포인트에 결과가 저장됩니다.
- 시각화
- Graph API를 사용하면 워크플로를 그래프로 쉽게 시각화할 수 있으며, 이는 디버깅, 워크플로 이해 및 다른 사용자와의 공유에 유용합니다. Functional API는 그래프가 런타임 중에 동적으로 생성되므로 시각화를 지원하지 않습니다.
에세이를 작성하고 인간의 검토를 요청하는 간단한 어플리케이션은 아래와 같습니다
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.types import interrupt
@task
def write_essay(topic: str) -> str:
"""Write an essay about the given topic."""
time.sleep(1) # A placeholder for a long-running task.
return f"An essay about topic: {topic}"
@entrypoint(checkpointer=InMemorySaver())
def workflow(topic: str) -> dict:
"""A simple workflow that writes an essay and asks for a review."""
essay = write_essay("cat").result()
is_approved = interrupt({
# Any json-serializable payload provided to interrupt as argument.
# It will be surfaced on the client side as an Interrupt when streaming data
# from the workflow.
"essay": essay, # The essay we want reviewed.
# We can add any additional information that we need.
# For example, introduce a key called "action" with some instructions.
"action": "Please approve/reject the essay",
})
return {
"essay": essay, # The essay that was generated
"is_approved": is_approved, # Response from HIL
}
'Lecture > 패스트캠퍼스' 카테고리의 다른 글
| 패스트캠퍼스 환급챌린지 40일차 : 테디노트의 RAG 비법노트 강의 후기 (5) | 2025.08.10 |
|---|---|
| 패스트캠퍼스 환급챌린지 39일차 : 테디노트의 RAG 비법노트 강의 후기 (6) | 2025.08.08 |
| 패스트캠퍼스 환급챌린지 37일차 : 테디노트의 RAG 비법노트 강의 후기 (3) | 2025.08.06 |
| 패스트캠퍼스 환급챌린지 36일차 : 테디노트의 RAG 비법노트 강의 후기 (2) | 2025.08.05 |
| 패스트캠퍼스 환급챌린지 35일차 : 테디노트의 RAG 비법노트 강의 후기 (2) | 2025.08.04 |
Comments