""" https://chatgpt.com/share/6a0668d8-1c1c-83a9-9d77-de76eb3e7716 """ import requests from fastapi import APIRouter, Form, File, UploadFile from utils.common import CommonResponse from utils.db import get_connection import json router = APIRouter( prefix="/llm", tags=["llm"] ) @router.post("/askllm") def test_home(userquery: str = Form("") , selected_cards:str = Form("[]") , chat_history:str=Form("[]") ): try: cards=json.loads(selected_cards) card_text = "\n".join([ f"- {card['position']} 위치: {card['name']} / {'역방향' if card['reversed'] else '정방향'}" for card in cards ]) history=json.loads(chat_history) with get_connection() as conn: with conn.cursor() as cur: cur.execute(""" SELECT api_key FROM t_api_keys WHERE service_name='pollination' LIMIT 1 """) row = cur.fetchone() pollination_api_key=row[0] if row else None # pollination key 없으면 그냥 클라한테 오류라고 퉤 뱉기 if not pollination_api_key: return CommonResponse( success=False, msg="Pollinations API Key가 없습니다." ) # 2. Pollinations Text 모델에 보낼 데이터 url = "https://gen.pollinations.ai/v1/chat/completions" """ 택배상자에 뭐 주소나 내 정보 쓰잔아요? 컴퓨터의 api 통신에 Content-Type, Authorization 이거 쓰래요 Authorization 부분에 pollination_api_key 넣어서 보내래요 """ headers = { "Content-Type": "application/json", "Authorization": f"Bearer {pollination_api_key}" } """ 내용물. body 라고도 부름. """ # 4. LLM에게 보낼 messages 만들기 messages = [ { "role": "system", "content": """ 당신은 친절한 타로 상담사입니다. 답변은 5문장 이내로 짧게 하세요. 복잡한 설명은 하지 마세요. 쉽고 직관적이게 답변해주세요. 사용자가 선택한 카드는 과거, 현재, 미래 순서입니다. 각 카드의 정방향/역방향 의미를 반영해서 답변하세요. 중요: 사용자의 최근 대화 흐름을 반드시 기억하고 이어서 답변하세요. 꼭 상대방과 대화하는 느낌이 들도록 답변하세요. """ } ] # 5. 이전 대화 기록 추가 for msg in history: messages.append({ "role": msg["role"], "content": msg["content"] }) # 6. 이번 사용자 질문 추가 messages.append({ "role": "user", "content": f""" 사용자 질문: {userquery} 선택된 타로 카드: {card_text} 위 질문과 선택된 카드를 바탕으로 짧게 타로 상담을 해주세요. """ }) print(f"# userquery: \n",userquery) print(f"# messages: \n",messages) payload = { "model": "openai-fast", "messages": messages, "temperature": 0.8, "max_tokens": 5000, "stream": False } # 3. Pollinations API 호출 response = requests.post(url, headers=headers, json=payload) # 4. 실패 체크 if response.status_code != 200: return CommonResponse( success=False, msg=f"Pollinations API 오류: {response.text}" ) result = response.json() print("========== Pollinations raw result ==========") print(result) print("============================================") # 5. AI 응답 텍스트 꺼내기 answer = result["choices"][0]["message"]["content"] # 6. 프론트로 반환 return CommonResponse( success=True, data={ "question": userquery, "answer": answer } ) except Exception as e: return CommonResponse(success=False, msg=str(e))