TIL 240508

hyeo71·2024년 5월 8일
0

2024 내배캠 AI 트랙

목록 보기
90/108

Sparta News

ai로 News 생성하기

class GenerateNews(APIView):
    def get(self, request):
        ...

    def post(self, request):
    	
        """AI API 설정"""
        prompt = 'Please recommend one of the IT related news. Please let me know the title, content and url as well. Provide your response as a Json object with the following schema: {"title" : "", "content":"", "url":""}.'

        openai_url = "https://api.openai.com/v1/chat/completions"
        openai_api_key = os.environ.get("OPENAI_KEY")
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {openai_api_key}",
        }
        data = {
            "model": "gpt-3.5-turbo",
            "messages": [
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt},
            ],
        }
        response = requests.post(openai_url, json=data, headers=headers)
		
        """Object 생성 후"""
        if response.status_code == 200: # 정상적으로 생성된 경우
            generated_data = response.json()
            news_data = json.loads(generated_data["choices"][0]["message"]["content"])
            admin_user = User.objects.get(username="admin")

            serializer = NewsSerializer(
                data={
                    "type": "gn+",
                    "title": news_data["title"],
                    "content": news_data["content"],
                    "url": news_data["url"],
                },
                context={"request": request},
            )
            if serializer.is_valid():
                serializer.save(author_id=admin_user.pk)	# 관리자가 생성한 것으로 설정
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(
                {"error": "Failed to generate story from AI"},
                status=response.status_code,
            )

0개의 댓글