questions_prompt = ChatPromptTemplate.from_messages([
(
"system",
"""
You are a helpful assistant that is role playing as a teacher.
Based ONLY on the following context make 10 questions to test the user's knowledge about the text.
Each question should have 4 answers, three of them must be incorrect and one should be correct.
Use (o) to signal the correct answer.
Question examples:
Question: What is the color of the ocean?
Answers: Red | Yellow | Green | Blue(o)
Your turn!
Context: {context}
"""
)
])
questions_chain = {
"context": format_docs
} | questions_prompt | llm
formatting_prompt = ChatPromptTemplate.from_messages([
(
"system",
"""
You are a powerful formatting algorithm.
You format exam questions into JSON format.
Answers with (o) are the correct ones.
Example Input:
Question: What is the color of the ocean?
Answers: Red|Yellow|Green|Blue(o)
Example Output:
```json
{{
"question": "What is the color of the ocean?",
"answers": [
{{
"answer": "Red",
"correct": false
}},
{{
"answer": "Yellow",
"correct": false
}},
{{
"answer": "Green",
"correct": false
}},
{{
"answer": "Blue",
"correct": true
}},
]
}}
```
Your turn!
Questions: {context}
""",
)
])
formatting_chain = formatting_prompt | llm
LLM 응답을 특정 포맷으로 변환
응답을 정제 및 후처리
안정성 확보
- API 연동, 데이터 저장 등에서 일관된 포맷을 데이터가 필요할 때 유용함
- LLM이 예상치 못한 출력을 내는 경우를 방지
정확한 응답 제공
LLM을 API 인터페이스로 사용
복잡한 작업 자동화
OpenAI API에서 Function Calling 활성화
functions
파라미터를 설정하면 함수 호출을 활성화 할 수 있음함수 정의 & OpenAI에 등록
import openai
import json
openai.api_key = "YOUR_OPENAI_API_KEY"
# 1️⃣ 함수 정의 (날씨 조회)
functions = [
{
"name": "get_weather",
"description": "Fetches the current weather for a given city.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name to get the weather for"
}
},
"required": ["location"]
}
}
]
# 2️⃣ 실제 날씨 정보를 반환하는 함수
def get_weather(location):
weather_data = {
"Seoul": {"temperature": "12°C", "condition": "Clear"},
"New York": {"temperature": "8°C", "condition": "Cloudy"},
}
return weather_data.get(location, {"temperature": "Unknown", "condition": "Unknown"})
# 3️⃣ GPT 모델 호출 (Function Calling 활성화)
response = openai.ChatCompletion.create(
model="gpt-4-0613", # Function Calling 지원 모델 사용
messages=[{"role": "user", "content": "서울의 날씨 어때?"}],
functions=functions,
function_call="auto" # 자동으로 적절한 함수 선택
)
# 4️⃣ GPT가 함수 호출을 요청했는지 확인
if response["choices"][0]["message"].get("function_call"):
function_name = response["choices"][0]["message"]["function_call"]["name"]
function_args = json.loads(response["choices"][0]["message"]["function_call"]["arguments"])
if function_name == "get_weather":
result = get_weather(**function_args) # 실제 함수 실행
print(f"🌦️ 서울의 현재 날씨: {result['temperature']} ({result['condition']})")