from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain_decorators import llm_prompt
from langchain.prompts import PromptTemplate
from langchain.schema import StrOutputParser
from langchain.chains.summarize import load_summarize_chain
from langchain.document_loaders import PyPDFLoader
from langchain.callbacks import get_openai_callback
from pydantic import BaseModel, Field
from typing import Optional,List, Literal
from langchain.chains import create_extraction_chain_pydantic
# Information Retrieval
from langchain.agents import (
AgentExecutor,AgentType, initialize_agent, load_tools
)
from langchain.chains import LLMChain
from langchain.tools import Tool
# Exploring reasoning strategies
from langchain_experimental.plan_and_execute import (
load_chat_planner, load_agent_executor, PlanAndExecute
)
from dotenv import load_dotenv
load_dotenv()
True
Summarizing information¶
text="""In today’s fast-paced business and research landscape, keeping up with the ever-increasing volume of information can be a daunting task.
For engineers and researchers in fields like computer science and artificial intelligence, staying updated with the latest developments is crucial.
However, reading and comprehending numerous papers can be time-consuming and labor-intensive.
This is where automation comes into play.
As engineers, we are driven by the desire to build and innovate and avoid repetitive tasks by automating them through the creation of pipelines and processes.
This approach, often mistaken for laziness, allows engineers to focus on more complex challenges and utilize their skills more efficiently.
"""
prompt = """
Summarize the following text in one sentence as Korean:
{text}
"""
llm = OpenAI()
summary = llm(prompt.format(text=text))
print(summary)
오늘날 빠르게 변화하는 비즈니스와 연구 환경에서 정보의 증가에 대처하는 것은 어려운 일이지만, 자동화를 통해 엔지니어들은 반복적인 작업을 피하고 더 복잡한 문제에 집중할 수 있다.
@llm_prompt
doc string 프롬프트로 변환하고 실행을 처리합니다. 매개변수가 깔끔하게 전달되고 출력이 구문 분석됩니다. 이 추상화를 통해 자연스러운 Python 스타일로 메시지를 표시하는 동시에 이면의 복잡성을 처리할 수 있으므로효과적인 프롬프트를 만드는 데 집중하세요.
llm까지 불러서 실행함
기본 llm은 ChatOpenAI(temperature=0.0, model="gpt-3.5-turbo-1106", request_timeout=30)
- 패키지 설치
-
pip install langchain-decorators
from langchain_decorators import llm_prompt
@llm_prompt(llm=ChatOpenAI(temperature=0.7,model="gpt-4-1106-preview"))
def summarize(text:str, length="short") -> str:
"""
Summarize the following text in {length} as Korean:
{text}
"""
return
summary = summarize(text=text, length="one line")
print(summary)
오늘날 빠르게 변화하는 비즈니스 및 연구 환경에서, 컴퓨터 과학 및 인공지능 분야의 엔지니어와 연구자들은 자동화를 통해 반복적인 작업을 줄이고 더 복잡한 도전에 집중하여 효율적으로 기술을 활용한다.
@llm_prompt
def summarize2(text:str, length="short") -> str:
"""
Summarize the following text in {length} as Korean:
{text}
"""
return
print(summarize2(text=text, length="one line"))
급변하는 비즈니스와 연구 환경에서 최신 정보를 이해하는 것은 중요하나, 자동화를 통해 더 복잡한 과제에 집중할 수 있다.
Prompt Template¶
LangChain Expression Language (LCEL)
LCEL은 코드를 직접 작성하는 것보다 더 직관적이고 생산적인 체인을 구성하는 선언적 방법을 제공합니다.
LCEL의 주요 이점에는 비동기 처리, 일괄 처리, 스트리밍, 폴백, 병렬 처리 및 LangSmith 추적과의 원활한 통합에 대한 기본 지원이 포함됩니다.
llm = OpenAI()
prompt = PromptTemplate.from_template("Summarize this text in {length} as Korean: {text}")
runnable = prompt | llm | StrOutputParser()
summary = runnable.invoke({"text":text,"length":"100 characters"})
print(summary)
"빠른 비즈니스와 연구 환경에서 정보 양 증가에 대처하기 어려우나 자동화를 통해 시간과 노력 절약. 파이프라인과 프로세스를 생성하여 엔지니어의 창의력과 능력을 더욱 효율적으로 활용."
Chain of desity (CoD) - 밀도 체인¶
Salesforce의 연구원들(Adams와 동료들, 2023; From Sparse to Dense: 밀도 체인 프롬프트를 사용한 GPT-4 요약)은 길이를 제어하면서 GPT-4 생성 요약의 정보 밀도를 점진적으로 높이기 위해 밀도 체인(CoD)이라는 프롬프트 안내 기법을 개발했습니다.
CoD 프롬프트GPT-4와 같은 강력한 LLM에 소수의 엔터티만 포함된 기사의 초기 희박하고 자세한 요약을 생성하도록 지시합니다. 그런 다음 1~3개의 누락된 엔터티를 반복적으로 식별하고 이를 다시 작성하여 융합합니다.같은 수의 단어로 된 이전 요약.
길이 제약 하에서 이러한 반복적인 재작성은 각 단계에서 추가 엔터티를 위한 공간을 만들기 위해 추상화, 세부 사항 융합 및 압축을 증가시킵니다. 저자는 밀도화 효과를 특성화하기 위해 엔터티 밀도 및 소스 문장 정렬과 같은 통계를 측정합니다.
5개의 반복 단계를 통해 요약은 창의적인 재작성을 통해 토큰당 더 많은 엔터티로 압축되어 고도로 압축됩니다. 저자는 인간 선호도 연구와 GPT-4 채점을 모두 수행하여 밀도 스펙트럼 전반에 걸쳐 전반적인 품질에 미치는 영향을 평가합니다.
결과는밀도를 통해 얻은 정보성과 과도한 압축으로 인한 일관성 감소 사이의 균형. 최적의 밀도는 표현을 압도하는 엔터티가 너무 많아 간결성과 명확성의 균형을 유지합니다. 이 방법과 분석은 AI 텍스트 생성에서 정보 밀도를 제어하는 방법을 밝힙니다.
template = """기사: { 텍스트 }
위의 기사에 대해 점점 더 간결하고 항목이 밀집된 요약을 생성합니다.
다음 2단계를 5회 반복합니다.
1단계. 이전에 생성한 요약에서 누락된 정보 엔티티(";" 구분)를 기사에서 1~3개 찾아냅니다.
2단계. 이전 요약의 모든 개체와 세부 정보에 누락된 개체를 더하여 동일한 길이의 새롭고 밀도 높은 요약을 작성합니다.
누락된 엔티티는
- 메인 스토리와 관련이 있어야 합니다,
- 구체적이면서도 간결해야 합니다(5단어 이하),
- 새롭다(이전 요약에 없음),
- 충실함(글에 있음)
- 어디서나(기사 어디에서나 찾을 수 있음).
가이드라인:
- 첫 번째 요약은 길어야 하지만(4~5문장, 80단어 이내) 매우 구체적이지 않아야 하며, 누락된 것으로 표시된 항목 이외의 정보는 거의 포함하지 않아야 합니다. 지나치게 장황한 언어와 필러(예: "이 문서에서는 논의합니다")를 사용하여 80단어 이내로 작성하세요.
- 모든 단어를 중요하게 생각하세요: 이전 요약을 다시 작성하여 흐름을 개선하고 추가 엔터티를 위한 공간을 확보하세요.
- "이 문서에서는 논의합니다"와 같이 정보성이 없는 문구를 융합, 압축, 제거하여 공간을 확보하세요.
- 요약은 매우 밀도 있고 간결하면서도 독립적으로, 즉 문서 없이도 쉽게 이해할 수 있도록 작성해야 합니다.
- 누락된 항목은 새 요약의 어느 곳에나 나타날 수 있습니다.
- 이전 요약에서 엔티티를 삭제하지 마세요. 공간을 확보할 수 없는 경우에는 새 엔티티를 적게 추가하세요.
각 요약에 정확히 같은 수의 단어를 사용해야 한다는 점을 기억하세요.
JSON으로 답안 작성. JSON은 키가 "Missing_Entities" 및 "Denser_Summary"인 사전의 목록(길이 5)이어야 합니다.
"""
template = """Article: {text}
You will generate increasingly concise, entity-dense summaries of the above article.
Repeat the following 2 steps 5 times.
Step 1. Identify 1-3 informative entities (";" delimited) from the article which ara missing from the previous generated summary.
Step 2. Write a new, denser summary of identical length to which covers every entity and detail from the previous summary plus the missing entities.
A missing entity is:
- relevent to the main story ,
- specific yet concise (5 words or fewer),
- novel (not in the previous summary),
- faithful (present in the article).
- anywhere (can be located anywhere in the article).
Guidelines:
- The first summary should be long (4-5 sentences, ~80 words) yet highly non-specific, containing little information beyond the entities marked as missing. Use overly verbose language and fillers (e.g., "this article discusses") to reach ~80 words.
- Make every word count: rewrite the previous summary to improve flow and make space for additional entities.
- The summary should become highly dense and consise yet self-contained, i.e., easily understood without the article.
- Missing entities can apperar anywhere in new summary.
- Never drop entities from the previous summary. If space cannot be made, add fewer new entities.
Remember, use exact same number of words for each summary.
Answer in JSON. The JSON should be a list (length 5) of dictionaries who keys are "Missing_Entities" and "Denser_Summary".
Please answer in Korean.
"""
llm = ChatOpenAI(model="gpt-4-1106-preview")
prompt = PromptTemplate.from_template(template)
runnable = prompt | llm | StrOutputParser()
summary = runnable.invoke({"text":text})
print(summary)
```json [ { "Missing_Entities": "자동화; 엔지니어; 최신 발전", "Denser_Summary": "이 기사는 현대 사회에서 정보의 양이 급증하고 있어 이를 따라잡는 것이 어렵다고 언급합니다. 특히 컴퓨터 과학과 인공지능 분야의 엔지니어나 연구자에게는 최신 발전을 파악하는 것이 중요합니다. 많은 문서를 읽고 이해하는 일은 많은 시간과 노력이 필요합니다. 이러한 과정의 자동화는 반복적인 작업을 피하고 더 복잡한 문제에 집중할 수 있게 해줍니다." }, { "Missing_Entities": "비즈니스; 연구 환경; 복잡한 문제", "Denser_Summary": "이 기사는 현대 비즈니스와 연구 환경에서 정보의 대량 처리가 어려움을 강조합니다. 컴퓨터 과학 및 인공지능과 같은 분야에서는 엔지니어와 연구자들이 최신 발전을 빠르게 파악해야 합니다. 자동화는 문서 읽기와 같은 시간 소모적인 작업을 줄여 복잡한 문제에 더 집중하게 하는 방법으로 제시됩니다." }, { "Missing_Entities": "정보 볼륨; 정보 따라잡기; 연구자", "Denser_Summary": "이 기사에서는 비즈니스 및 연구 환경에서 처리해야 할 정보 볼륨 증가가 연구자와 엔지니어에게 큰 도전이라고 설명합니다. 특히 컴퓨터 과학, 인공지능 분야에서 정보 따라잡기는 필수적입니다. 자동화는 반복적인 업무를 줄이고 복잡한 문제에 집중할 수 있는 효율적 수단입니다." }, { "Missing_Entities": "컴퓨터 과학; 인공지능; 시간 소모적인 작업", "Denser_Summary": "비즈니스 및 연구 환경에서의 정보 볼륨 증가는 컴퓨터 과학과 인공지능 분야의 연구자들에게 정보 따라잡기가 중대한 과제로 부상합니다. 자동화는 시간 소모적인 작업을 줄이며, 복잡한 문제 해결에 엔지니어의 집중을 가능하게 합니다." }, { "Missing_Entities": "정보 처리; 중대한 과제; 업무 효율성", "Denser_Summary": "엔지니어와 연구자들은 컴퓨터 과학, 인공지능 분야에서 증가하는 정보 처리를 중대한 과제로 인식합니다. 자동화로 시간 소모적인 작업을 최소화하여 업무 효율성을 높이고 복잡한 문제에 더 집중할 수 있습니다." } ] ```
Map-Reduce piplines¶
LangChain은 처리를 위해 맵 축소 접근 방식을 지원합니다.문서를 효율적으로 처리하고 분석할 수 있는 LLM을 사용하는 문서입니다. 각 문서에 체인을 개별적으로 적용한 다음 출력을 단일 문서로 결합할 수 있습니다.
긴 문서를 요약하기 위해 먼저 문서를 토큰에 적합한 더 작은 부분(청크)으로 분할할 수 있습니다.LLM의 컨텍스트 길이 및 맵 축소 체인은 재결합하기 전에 이러한 청크를 독립적으로 요약할 수 있습니다. 청크 크기를 제어하면서 요약을 텍스트 길이에 맞게 조정합니다.
주요 단계는 다음과 같습니다.
- Map : 각 문서는 요약 체인(LLM 체인)을 통해 전달됩니다.
- 축소 (선택 사항): 요약된 문서를 하나의 문서로 결합합니다.
- Reduce : 축소된 문서는 최종 LLM 체인을 거쳐 출력을 생성합니다.
pdf_file_path = "data/Introduction_to_Entropy_and_Gini-Index.pdf"
pdf_loader = PyPDFLoader(pdf_file_path)
docs = pdf_loader.load_and_split()
llm = ChatOpenAI(model="gpt-4-1106-preview")
chain = load_summarize_chain(llm, chain_type="map_reduce")
result = chain.run(docs)
print(result)
The article by Gurjinder Kaur in "Towards Data Science" discusses Entropy and Gini Index as metrics for quantifying impurity or uncertainty in datasets, particularly in the context of decision tree algorithms. Both metrics are crucial for evaluating data splits, with higher values indicating greater randomness or heterogeneity. The article uses a supermarket fruit collection example to explain how these measures are calculated and their significance. Entropy is based on the probabilities of each class and can range from 0 for pure datasets to 1 for maximum uncertainty in binary classification. The Gini Index, which also measures dataset purity, ranges from 0 for homogeneity to 0.5 for binary classification when classes are evenly distributed. Both metrics are used to achieve better decision-making in decision trees by identifying splits that reduce impurity the most. The article aims to provide an intuitive understanding of these concepts and their application in machine learning.
변수는 text
,input_documents
로 고정
prompt_template = """Write a concise summary of the following as Korean:
"{text}"
CONCISE SUMMARY:"""
map_prompt = PromptTemplate(template=prompt_template,input_variables=["text"])
combine_prompt = PromptTemplate(template=prompt_template,input_variables=["text"])
pdf_file_path = "data/Introduction_to_Entropy_and_Gini-Index.pdf"
pdf_loader = PyPDFLoader(pdf_file_path)
docs = pdf_loader.load_and_split()
# llm = OpenAI()
llm = ChatOpenAI(model="gpt-4-1106-preview")
chain = load_summarize_chain(llm, chain_type="map_reduce", map_prompt=map_prompt, combine_prompt=combine_prompt)
result = chain({"input_documents": docs}, return_only_outputs=True)
print(result)
{'output_text': '"엔트로피와 지니 지수는 데이터 세트의 불확실성을 측정하는 머신러닝 지표입니다. 이들은 결정 트리 알고리즘에서 데이터 분할의 질을 결정하는 데 사용됩니다. 엔트로피는 데이터의 예측 불가능성을, 지니 지수는 무작위로 선택된 요소가 잘못 레이블될 확률을 나타냅니다. 이들 지표는 데이터 내의 클래스 확률을 기반으로 계산되며, 높은 값은 데이터의 높은 무작위성을 의미합니다. 이진 분류에서 엔트로피의 최대 값은 1, 지니 지수는 0.5이고, 다중 클래스 분류에서는 n에 의존합니다."'}
Monitoring token usage¶
llm_chain = PromptTemplate.from_template("Tell me a joke about {topic}!") | ChatOpenAI()
with get_openai_callback() as cb:
response = llm_chain.invoke(dict(topic="light bulb"))
print(response)
print(f"Totla Tokens: {cb.total_tokens}")
print(f"Prompt Tokens: {cb.prompt_tokens}")
print(f"Completion Tokens: {cb.completion_tokens}")
print(f"Total Cost(USD): {cb.total_cost}")
content='Why did the light bulb go to school?\n\nBecause it wanted to be brighter!' Totla Tokens: 31 Prompt Tokens: 15 Completion Tokens: 16 Total Cost(USD): 5.4499999999999997e-05
def run_with_cost(f, *args, **kwargs):
with get_openai_callback() as cb:
result = f(*args, **kwargs)
print(result)
print(f"Totla Tokens: {cb.total_tokens}")
print(f"Prompt Tokens: {cb.prompt_tokens}")
print(f"Completion Tokens: {cb.completion_tokens}")
print(f"Total Cost(USD): {cb.total_cost}")
run_with_cost(llm_chain.invoke, dict(topic="light bulb"))
content='Why did the light bulb go to school?\n\nBecause it wanted to get brighter!' Totla Tokens: 31 Prompt Tokens: 15 Completion Tokens: 16 Total Cost(USD): 5.4499999999999997e-05
Information Extraction¶
Information information_extraction from documents.
The example CV is from https://github.com/xitanggg/open-resume.
class Experience(BaseModel):
# the title doesn't seem to help at all.
start_date: Optional[str] = Field(description="When the job or study started.")
end_date: Optional[str] = Field(description="When the job or study ended.")
description: Optional[str] = Field(description="What the job or study entailed.")
country: Optional[str] = Field(description="The country of the institution.")
class Study(Experience):
degree: Optional[str] = Field(description="The degree obtained or expected.")
institution: Optional[str] = Field(description="The university, college, or educational instituition visited.")
grade: Optional[str] = Field(description="The grade archieved or expected.")
class WorkExperience(Experience):
company: Optional[str] = Field(description="The company name of the work experience.")
job_title: Optional[str] = Field(description="The job title.")
class Resume(BaseModel):
first_name: Optional[str] = Field(description="The first name of the person.")
last_name: Optional[str] = Field(description="The last name of the person.")
linkedin_url: Optional[str] = Field(description="The url of the linkedin profile of the person.")
email_address: Optional[str] = Field(description="The email address of the person.")
nationality: Optional[str] = Field(description="The nationality of the person.")
skill: Optional[List[str]] = Field(description="A skill listed or mentioned in a description.")
study: Optional[List[Study]] = Field(description="A study that the person completed or is in progress of completing.")
work_experience: Optional[List[WorkExperience]] = Field(description="A work experience of the person." )
hobby: Optional[List[str]] = Field(description="A hobby or recreational activity of the person.")
def parse_cv(pdf_file_path: str) -> str:
"""Parse a resume.
Not totally sure about the return type: is it list[Resume]?
"""
pdf_loader = PyPDFLoader(pdf_file_path)
docs = pdf_loader.load_and_split()
# please note that function calling is not enabled for all models!
# llm = ChatOpenAI(model_name="gpt-3.5-turbo-1106")
llm = ChatOpenAI(model_name="gpt-4-1106-preview")
chain = create_extraction_chain_pydantic(pydantic_schema=Resume, llm=llm)
return chain.run(docs)
result= parse_cv(pdf_file_path="data/openresume-resume.pdf")
result
[Resume(first_name='John', last_name='Doe', linkedin_url='linkedin.com/in/john-doe', email_address='hello@openresume.com', nationality=None, skill=['HTML', 'TypeScript', 'CSS', 'React', 'Python', 'C++', 'React Hooks', 'GraphQL', 'Node.js', 'SQL', 'Postgres', 'NoSql', 'Redis', 'REST API', 'Git', 'Teamwork', 'Creative Problem Solving', 'Communication', 'Learning Mindset', 'Agile'], study=[Study(start_date='Sep 2019', end_date='May 2023', description='Won 1st place in 2022 Education Hackathon, 2nd place in 2023 Health Tech Competition. Teaching Assistant for Programming for the Web (2022 - 2023). Coursework: Object-Oriented Programming (A+), Programming for the Web (A+), Cloud Computing (A), Introduction to Machine Learning (A-), Algorithms Analysis (A-).', country='USA', degree='Bachelor of Science in Computer Science', institution='XYZ University', grade='3.8 GPA')], work_experience=[WorkExperience(start_date='May 2023', end_date='Present', description='Lead a cross-functional team of 5 engineers in developing a search bar, which enables thousands of daily active users to search content across the entire platform. Create stunning home page product demo animations that drives up sign up rate by 20%. Write clean code that is modular and easy to maintain while ensuring 100% test coverage.', country=None, company='ABC Company', job_title='Software Engineer'), WorkExperience(start_date='Summer 2022', end_date=None, description='Re-architected the existing content editor to be mobile responsive that led to a 10% increase in mobile user engagement. Created a progress bar to help users track progress that drove up user retention by 15%. Discovered and fixed 5 bugs in the existing codebase to enhance user experience.', country=None, company='DEF Organization', job_title='Software Engineer Intern'), WorkExperience(start_date='Summer 2021', end_date=None, description='Devised a new NLP algorithm in text classification that results in 10% accuracy increase. Compiled and presented research findings to a group of 20+ faculty and students.', country=None, company='XYZ University', job_title='Research Assistant')], hobby=None)]
for r in result:
print(r.json(indent=2))
{ "first_name": "John", "last_name": "Doe", "linkedin_url": "linkedin.com/in/john-doe", "email_address": "hello@openresume.com", "nationality": null, "skill": [ "HTML", "TypeScript", "CSS", "React", "Python", "C++", "React Hooks", "GraphQL", "Node.js", "SQL", "Postgres", "NoSql", "Redis", "REST API", "Git", "Teamwork", "Creative Problem Solving", "Communication", "Learning Mindset", "Agile" ], "study": [ { "start_date": "Sep 2019", "end_date": "May 2023", "description": "Won 1st place in 2022 Education Hackathon, 2nd place in 2023 Health Tech Competition. Teaching Assistant for Programming for the Web (2022 - 2023). Coursework: Object-Oriented Programming (A+), Programming for the Web (A+), Cloud Computing (A), Introduction to Machine Learning (A-), Algorithms Analysis (A-).", "country": "USA", "degree": "Bachelor of Science in Computer Science", "institution": "XYZ University", "grade": "3.8 GPA" } ], "work_experience": [ { "start_date": "May 2023", "end_date": "Present", "description": "Lead a cross-functional team of 5 engineers in developing a search bar, which enables thousands of daily active users to search content across the entire platform. Create stunning home page product demo animations that drives up sign up rate by 20%. Write clean code that is modular and easy to maintain while ensuring 100% test coverage.", "country": null, "company": "ABC Company", "job_title": "Software Engineer" }, { "start_date": "Summer 2022", "end_date": null, "description": "Re-architected the existing content editor to be mobile responsive that led to a 10% increase in mobile user engagement. Created a progress bar to help users track progress that drove up user retention by 15%. Discovered and fixed 5 bugs in the existing codebase to enhance user experience.", "country": null, "company": "DEF Organization", "job_title": "Software Engineer Intern" }, { "start_date": "Summer 2021", "end_date": null, "description": "Devised a new NLP algorithm in text classification that results in 10% accuracy increase. Compiled and presented research findings to a group of 20+ faculty and students.", "country": null, "company": "XYZ University", "job_title": "Research Assistant" } ], "hobby": null }
pydantic¶
from pydantic import BaseSettings
class Settings(BaseSettings):
api_key: str
login: str
seed: int
class Config:
env_file = "data/env"
env_file_encoding = "utf-8"
settings = Settings()
print(settings)
api_key='SeCR€t!' login='Ahmed' seed=42
Information retrieval with tools¶
RAG(Retrieval Augmented Generation) :
데이터 소스에서 정보를 검색하여 언어 모델에 제공된 프롬프트를 보완하고 정확한 응답을 생성하는 데 필요한 컨텍스트를 모델에 제공하는 방식으로 작동
- 외부 소스에서 관련 데이터를 검색하여 LLM에 주입함으로써 LLM의 한계를 해결
- 문맥, 검색된 데이터는 LLM에 제공되는 프롬프트를 보강하기 위한 추가 정보 역할
- RAG는 관련 데이터 검색을 통해 LLM의 환각 반응을 줄이는 데 도움
Streamlit:
Streamlit 은 기계 학습 및 데이터 과학 팀을 위한 오픈 소스 앱 프레임워크
- 필요 패키지 설치
pip install duckduckgo-search
pip install arxiv
pip install streamlit
#llm = ChatOpenAI(temperature=0, streaming=True, model="gpt-4-1106-preview")
llm = OpenAI(temperature=0, cache=False) #ChatOpenAI(temperature=0, streaming=True)
# DuckDuckGoSearchRun, wolfram alpha, arxiv search, wikipedia
tools = load_tools(llm=llm, tool_names=["ddg-search","wolfram-alpha","arxiv", "wikipedia"])
agent = initialize_agent(llm=llm, tools=tools,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,verbose=True)
run_with_cost(agent, "exp(i*pi)+1")
> Entering new AgentExecutor chain... This is a mathematical expression, so I should use wolfram_alpha to get the answer. Action: wolfram_alpha Action Input: exp(i*pi)+1 Observation: Assumption: exp(i π) + 1 Answer: 0 Thought: I now know the final answer. Final Answer: 0 > Finished chain. {'input': 'exp(i*pi)+1', 'output': '0'} Totla Tokens: 708 Prompt Tokens: 664 Completion Tokens: 44 Total Cost(USD): 0.0010840000000000001
run_with_cost(agent,"2023년 현재 대한민국 대통령은 누구?")
> Entering new AgentExecutor chain... I should use Wikipedia to find information about the current president of South Korea. Action: Wikipedia Action Input: "Current President of South Korea" Observation: Page: President of South Korea Summary: The president of the Republic of Korea (Korean: 대한민국 대통령; RR: Daehanmin-guk daetongnyeong), also known as the president of South Korea (Korean: 대통령), is the head of state and head of government of the Republic of Korea. The president leads the State Council, and is the chief of the executive branch of the national government as well as the commander-in-chief of the Republic of Korea Armed Forces. The Constitution and the amended Presidential Election Act of 1987 provide for election of the president by direct, secret ballot, ending sixteen years of indirect presidential elections under the preceding two authoritarian governments. The president is directly elected to a five-year term, with no possibility of re-election. If a presidential vacancy should occur, a successor must be elected within sixty days, during which time presidential duties are to be performed by the prime minister or other senior cabinet members in the order of priority as determined by law. The president is exempt from criminal liability (except for insurrection or treason). The current president, Yoon Suk Yeol, a former prosecutor general and member of the conservative People Power Party, assumed office on 10 May 2022, after defeating the Democratic Party's nominee Lee Jae-myung with a narrow 48.5% plurality in the 2022 South Korean presidential election. Page: List of presidents of South Korea Summary: The president of the Republic of Korea serves as the chief executive of the government of the Republic of Korea and the commander-in-chief of the Republic of Korea Armed Forces. The South Korean government constitutionally considers the Korean Provisional Government (KPG) to be its predecessor. The KPG was established in 1919 as a government in exile in Shanghai during the Japanese occupation of Korea. It had nine different heads of state between September 1919 and August 1948. The presidential term has been set at five years since 1988. It was previously set at four years from 1948 to 1972, six years from 1972 to 1981, and seven years from 1981 to 1988. Since 1981, the president has been barred from re-election. The president must be a South Korean citizen, at least 40 years old, who has lived in South Korea for 5 years. Page: First Lady of South Korea Summary: The first lady of the Republic of Korea (Korean: 대한민국 대통령 영부인; Hanja: 大韓民國 大統領 令夫人, informally referred to as FLOTROK or FLOSK), commonly known as the first lady of South Korea, is the title held by the hostess of the presidential residence, usually the wife of the president of South Korea. The current first lady is Kim Keon-hee, wife of President Yoon Suk-yeol, in office since 10 May 2022. Thought: I now know the final answer. Final Answer: The current president of South Korea is Yoon Suk-yeol. > Finished chain. {'input': '2023년 현재 대한민국 대통령은 누구?', 'output': 'The current president of South Korea is Yoon Suk-yeol.'} Totla Tokens: 1365 Prompt Tokens: 1312 Completion Tokens: 53 Total Cost(USD): 0.0020740000000000003
prompt_template = "아래 모든 질문은 영어로 번역하여 질문하고 질문에 대한 답변은 한국어로 대답해줘:\n\n{query}"
prompt = PromptTemplate(template=prompt_template,input_variables=["query"])
llm = ChatOpenAI(temperature=0)
tools = load_tools(llm=llm, tool_names=["ddg-search","wolfram-alpha","arxiv", "wikipedia"])
# llm_chain = LLMChain(llm=llm, prompt=prompt)
# # initialize the LLM tool
# llm_tool = Tool(
# name = "Language Model",
# func=llm_chain.run,
# description="use this tool for general purpose queries and logic"
# )
# tools.append(llm_tool)
agent = initialize_agent(llm=llm, tools=tools,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,verbose=True,max_iterations=3)
run_with_cost(agent,prompt.format(query="울프람알파에게 한국의 수도와 인구를 물어봐줘."))
> Entering new AgentExecutor chain... 울프람알파는 수도와 인구에 대한 정보를 제공할 수 있을 것 같다. Action: wolfram_alpha Action Input: "capital and population of South Korea" Observation: Assumption: South Korea | capital city | South Korea | population Answer: capital city | Seoul, South Korea population | 51.8 million people (world rank: 29th) (2023 estimate) Thought:울프람알파에게서 얻은 정보에 따르면 대한민국의 수도는 서울이고, 인구는 약 5180만 명이라고 한다. Final Answer: 대한민국의 수도는 서울이고, 인구는 약 5180만 명이다. > Finished chain. {'input': '아래 모든 질문은 영어로 번역하여 질문하고 질문에 대한 답변은 한국어로 대답해줘:\n\n울프람알파에게 한국의 수도와 인구를 물어봐줘.', 'output': '대한민국의 수도는 서울이고, 인구는 약 5180만 명이다.'} Totla Tokens: 999 Prompt Tokens: 862 Completion Tokens: 137 Total Cost(USD): 0.001567
# !PYTHON_PATH=. streamlit run question_answering/app.py
Exploring reasoning strategies (추론 전략 탐색)¶
LLM은 데이터의 패턴 인식에는 뛰어나지만 복잡한 다단계 문제에 필요한 기호 추론에는 어려움을 겪습니다.
고급 추론 전략을 구현하면 연구 도우미의 능력이 훨씬 더 향상될 것입니다. 신경 패턴 완성과 고의적인 기호 조작을 결합한 하이브리드 시스템은 이러한 기술을 습득할 수 있습니다:
- 일련의 사실로부터 결론을 도출하기 위한 다단계 연역적 추론
- 일련의 변환을 통해 방정식을 푸는 것과 같은 수학적 추론
- 문제를 최적화된 일련의 작업으로 분류하는 전략 계획
단순한 패턴 완성 대신 명시적 추론 단계와 함께 도구를 통합함으로써 에이전트는 추상화와 상상력이 필요한 문제를 해결할 수 있으며, 복잡한 개념에 대해 보다 의미 있는 대화를 나눌 수 있는 복잡한 세계에 대한 이해에 도달할 수 있습니다
도구와 추론을 통해 LLM을 강화하는 방법은 여기에 나와 있습니다
(출처 – https://github.com/billxbf/ReWOO , Binfeng Xu 등이 저술한 Decoupling Reasoning from Observations for Efficient Augmented Language Models Resources 논문 구현 , 2023년 5월) )
<도구로 강화된 LLM 패러다임>
(a) 관찰 의존적 추론에서는 사용자가 요청한 작업을 먼저 컨텍스트 프롬프트와 예시로 래핑한 다음, 추론 프로세스를 시작하기 위해 LLM에 입력합니다.
LLM은 생각(T)과 행동(A)을 생성한 다음 도구에서 관찰(O)을 기다립니다.
관찰은 프롬프트 기록에 쌓여 다음 LLM 호출을 시작합니다.
ZERO_SHOT_REACT_DESCRIPTION에 해당
(b) 추론과 관찰의 분리(ReWOO) 에서 플래너는 상호 의존적인 계획(P)의 목록을 한 번에 생성하고 워크를 호출하여 도구에서 증거(E)를 가져옵니다.
P와 E는 작업과 결합되어 최종 답을 얻기 위해 솔버에 전달됩니다.
(a)에서는 컨텍스트와 예제가 반복적으로 LLM에 공급되어 즉각적인 중복성을 초래한다는 점에 유의하세요.
ref: https://arxiv.org/pdf/2305.18323.pdf
ReWOO¶
계획과 도구 사용을 미세 조정할 수 있는 플래너 (LLM)는 계획 목록(P)을 생성 하고 작업자 (LangChain에서는 에이전트)를 호출하여 도구를 사용하여 증거( E )를 수집합니다.
P 와 E 는 작업과 결합된 다음 최종 답변을 위해 솔버 (LLM)에 입력됩니다. 다음과 같은 의사 알고리즘을 작성할 수 있습니다.
모든 단계를 계획합니다(플래너).
각 단계마다 단계를 완료하고 실행하는 데 적합한 도구를 결정합니다.
플래너 와 솔버는 다음과 같습니다 .
별개의 언어 모델을 통해 Planner 및 Solver 에 대해 더 작고 특수화된 모델을 사용 하고 각 호출에 더 적은 토큰을 사용할 수 있는 가능성이 열립니다 .
ReWOOD 가 생각보다 별로다!!!!¶
토큰량, 시간도 많이 든다. 기존 질문을 계속 사용하는 거 같다.
plan_and_solve()와 같이 method를 만들어서 사용해야 된다.
PlanAndExecute
는 내부적인 메모리를 사용하는거 같은데 전역 변수에 담아 사용하는 경우
기존에 질문한 내용을 보관 하고 있다가 새로운 질문시에도 재사용하는거 같음
def plan_and_solve():
llm = ChatOpenAI(temperature=0, cache=False)
tools = load_tools(tool_names=["ddg-search","wolfram-alpha","arxiv", "wikipedia"],
llm=llm)
# planner = load_chat_planner(llm=llm, system_prompt="모든 질문은 영어로 번역하여 질문하고 질문에 대한 답변은 한국어로 대답해줘") # planner
planner = load_chat_planner(llm=llm) # planner
executor = load_agent_executor(llm=llm, tools=tools, verbose=True) # worker
return PlanAndExecute(planner=planner, executor=executor)
run_with_cost(plan_and_solve(),"울프람알파에게 한국의 수도와 인구를 물어봐줘.")
> Entering new AgentExecutor chain... Action: { "action": "Final Answer", "action_input": "To open a web browser, you can click on the browser icon on your desktop or taskbar. Alternatively, you can search for the browser name in the start menu and click on it to open it." } > Finished chain. > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "To go to the Wolfram Alpha website, you can open a web browser and type in 'www.wolframalpha.com' in the address bar. Press Enter or Return to load the website." } ``` > Finished chain. > Entering new AgentExecutor chain... Action: ``` { "action": "duckduckgo_search", "action_input": { "query": "capital of South Korea" } } ``` Observation: 'Capital'), officially Seoul Special City, serves as the capital of South Korea, and is its most extensive urban center. Capital: Seoul 1 Population: (2023 est.) 51,268,000 Currency Exchange Rate: 1 USD equals 1309.361 South Korean won Form Of Government: unitary multiparty republic with one legislative house (National Assembly [300]) Coordinates: 36°N 128°E South Korea, [b] officially the Republic of Korea ( ROK ), [c] is a country in East Asia. It constitutes the southern part of the Korean Peninsula and borders North Korea along the Korean Demilitarized Zone. [d] The country's western border is formed by the Yellow Sea, while its eastern border is defined by the Sea of Japan. Seoul, the capital of South Korea, is no longer a city that's only gaining attention within Korea's borders. Today, Seoul has established itself as a global international city and holds a significant position in the international arena. Let's explore the reasons behind Seoul's rise as a global international city. 1. Economic hub 6. Party hard in Itaewon, the best nightlife in Seoul. It is well known, Koreans like to drink and like to drink a lot! Korea is the country where people drink the most in Asia. In Seoul and especially Itaewon, you can enjoy the ultimate nightlife experience and dance until sunrise as most bars stay open till late. Thought:The capital of South Korea is Seoul. It is the most extensive urban center in South Korea and serves as its capital. Seoul is a global international city and holds a significant position in the international arena. It is known for its economic hub and vibrant nightlife in areas like Itaewon. > Finished chain. > Entering new AgentExecutor chain... Action: ``` { "action": "wolfram_alpha", "action_input": "capital of South Korea" } ``` Observation: Assumption: South Korea | capital city Answer: Seoul, South Korea Thought:I will use the Wolfram Alpha tool to search for the capital city of South Korea. Action: ``` { "action": "wolfram_alpha", "action_input": "capital of South Korea" } ``` Observation: Assumption: South Korea | capital city Answer: Seoul, South Korea Thought:I have found the answer to your question. The capital city of South Korea is Seoul. > Finished chain. > Entering new AgentExecutor chain... Action: ``` { "action": "wolfram_alpha", "action_input": "population of South Korea" } ``` Observation: Assumption: South Korea | population Answer: 51.8 million people (world rank: 29th) (2023 estimate) Thought:I can use the Wolfram Alpha tool to find the population of South Korea. Let me do that for you. Action: ``` { "action": "wolfram_alpha", "action_input": "population of South Korea" } ``` Observation: Assumption: South Korea | population Answer: 51.8 million people (world rank: 29th) (2023 estimate) Thought:The population of South Korea is approximately 51.8 million people, according to the latest estimate in 2023. South Korea is ranked 29th in the world in terms of population. > Finished chain. > Entering new AgentExecutor chain... Action: ``` { "action": "wolfram_alpha", "action_input": "population of South Korea" } ``` Observation: Assumption: South Korea | population Answer: 51.8 million people (world rank: 29th) (2023 estimate) Thought:I can see that you were looking for the population of South Korea. Based on the previous steps, the population of South Korea is approximately 51.8 million people, according to the latest estimate in 2023. South Korea is ranked 29th in the world in terms of population. > Finished chain. > Entering new AgentExecutor chain... Action: { "action": "Final Answer", "action_input": "Based on the previous steps, the capital city of South Korea is Seoul and the population of South Korea is approximately 51.8 million people, according to the latest estimate in 2023. South Korea is ranked 29th in the world in terms of population." } > Finished chain. {'input': '울프람알파에게 한국의 수도와 인구를 물어봐줘.', 'output': 'Action:\n{\n "action": "Final Answer",\n "action_input": "Based on the previous steps, the capital city of South Korea is Seoul and the population of South Korea is approximately 51.8 million people, according to the latest estimate in 2023. South Korea is ranked 29th in the world in terms of population."\n}'} Totla Tokens: 11539 Prompt Tokens: 10842 Completion Tokens: 697 Total Cost(USD): 0.017657
run_with_cost(plan_and_solve(),"2023년 현재 대한민국 대통령은 누구?")
> Entering new AgentExecutor chain... Action: { "action": "duckduckgo_search", "action_input": "current year" } > Finished chain. > Entering new AgentExecutor chain... Action: ``` { "action": "duckduckgo_search", "action_input": "current president of South Korea" } ``` Observation: During the 2017 presidential election, Moon was elected president as the Democratic Party of Korea candidate following the impeachment of Park Geun-hye and her subsequent removal. Moon Jae-In (born January 24, 1953, Koje [Geoje] Island, South Kyŏngsang [South Gyeongsangnam] do [province], South Korea) South Korean lawyer and civil rights activist who was the president of South Korea (2017-22) and leader of the liberal Democratic Party of Korea (2015-16). Early life and education President Yoon Suk Yeol went to Washington to reset South Korean diplomacy by drawing closer to the United States and taking a larger role on the international stage. If the warmth of his... President: Yoon Suk-Yeol, assisted by Prime Minister: Han Duck-Soo Capital: Seoul 1 Population: (2023 est.) 51,268,000 Currency Exchange Rate: 1 USD equals 1309.361 South Korean won Form Of Government: unitary multiparty republic with one legislative house (National Assembly [300]) Steve Inskeep , Anthony Kuhn 3-Minute Listen Playlist Wednesday's meeting is the first by a Korean leader in 12 years. This year marks the 70th anniversary of the U.S.-Korea alliance — both see... Thought:The current president of South Korea is Yoon Suk-yeol. He was elected as the president in 2022. > Finished chain. > Entering new AgentExecutor chain... Action: { "action": "Final Answer", "action_input": "The current president of South Korea is Yoon Suk-yeol." } > Finished chain. {'input': '2023년 현재 대한민국 대통령은 누구?', 'output': 'Action:\n{\n "action": "Final Answer",\n "action_input": "The current president of South Korea is Yoon Suk-yeol."\n}'} Totla Tokens: 2879 Prompt Tokens: 2731 Completion Tokens: 148 Total Cost(USD): 0.0043925
run_with_cost(plan_and_solve(),"exp(i*pi)+1 를 계산해줘.")
> Entering new AgentExecutor chain... Action: { "action": "Final Answer", "action_input": "import math" } > Finished chain. > Entering new AgentExecutor chain... Action: ``` { "action": "wolfram_alpha", "action_input": "exp(i*pi)" } ``` Observation: Assumption: exp(i π) Answer: -1 Thought:The exponential value of i*pi is -1. > Finished chain. > Entering new AgentExecutor chain... Thought: To add 1 to the result obtained in step 2, I can simply use the addition operator in Python. Action: ```python result = -1 + 1 result ``` > Finished chain. > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "The final result is 0." } ``` > Finished chain. > Entering new AgentExecutor chain... Action: { "action": "Final Answer", "action_input": "The final result is 0." } > Finished chain. {'input': 'exp(i*pi)+1 를 계산해줘.', 'output': 'Action:\n{\n "action": "Final Answer",\n "action_input": "The final result is 0."\n}'} Totla Tokens: 4047 Prompt Tokens: 3826 Completion Tokens: 221 Total Cost(USD): 0.006181