Python과 OpenAI API를 사용하여 기사 작성 도구를 만들려면 여러 단계가 필요합니다.
환경 설정, 필요한 라이브러리 설치, 기사 생성을 위한 코드 작성 과정을 진행하겠습니다.
시작하기 전에 다음 사항을 확인하세요.
먼저 가상 환경을 생성하고 필요한 라이브러리를 설치해야 합니다. 터미널을 열고 다음 명령을 실행하세요:
# Create a virtual environment python -m venv myenv # Activate the virtual environment # On Windows myenv\Scripts\activate # On macOS/Linux source myenv/bin/activate # Install necessary libraries pip install openai
article_writer.py와 같은 Python 파일을 만들고 원하는 텍스트 편집기에서 엽니다. 코드를 여러 섹션으로 나누겠습니다.
import openai import os
'your-api-key'를 실제 OpenAI API 키로 바꿔야 합니다.
# Set up the OpenAI API key openai.api_key = 'your-api-key'
OpenAI의 GPT 모델을 사용하여 주제를 입력으로 받아 기사를 반환하는 함수를 작성하겠습니다.
def generate_article(topic): response = openai.Completion.create( engine="text-davinci-003", prompt=f"Write an article about {topic}.", max_tokens=1024, n=1, stop=None, temperature=0.7, ) return response.choices[0].text.strip()
def main(): print("Welcome to the Article Writing Tool!") topic = input("Enter the topic for your article: ") print("\nGenerating article...\n") article = generate_article(topic) print(article) if __name__ == "__main__": main()
article_writer.py 파일을 저장하고 터미널에서 실행하세요.
python article_writer.py
주제를 입력하라는 메시지가 표시되고 도구는 해당 주제를 기반으로 기사를 생성합니다.
이것은 기사 작성 도구의 기본 버전이지만 고려할 수 있는 몇 가지 향상된 기능이 있습니다.
도구를 더욱 강력하게 만들려면 API 오류 또는 잘못된 입력을 관리하는 오류 처리를 추가하세요.
def generate_article(topic): try: response = openai.Completion.create( engine="text-davinci-003", prompt=f"Write an article about {topic}.", max_tokens=1024, n=1, stop=None, temperature=0.7, ) return response.choices[0].text.strip() except openai.error.OpenAIError as e: return f"An error occurred: {str(e)}"
뉴스 기사, 블로그 게시물, 연구 논문 등 보다 구체적인 유형의 기사를 얻으려면 프롬프트를 맞춤설정하세요.
def generate_article(topic, style="blog post"): prompt = f"Write a {style} about {topic}." try: response = openai.Completion.create( engine="text-davinci-003", prompt=prompt, max_tokens=1024, n=1, stop=None, temperature=0.7, ) return response.choices[0].text.strip() except openai.error.OpenAIError as e: return f"An error occurred: {str(e)}"
주 함수에서 스타일을 포함하도록 입력을 수정합니다.
def main(): print("Welcome to the Article Writing Tool!") topic = input("Enter the topic for your article: ") style = input("Enter the style of the article (e.g., blog post, news article, research paper): ") print("\nGenerating article...\n") article = generate_article(topic, style) print(article)
이 단계를 따르면 Python과 OpenAI API를 사용하여 기본 기사 작성 도구를 만들 수 있습니다.
이 도구는 기사를 파일에 저장하거나, 웹 인터페이스와 통합하거나, 생성된 콘텐츠에 대한 더 많은 사용자 정의 옵션을 제공하는 등의 추가 기능을 통해 더욱 향상될 수 있습니다.
자세히 알아보고 싶으신가요? ZeroByteCode.
에서 프로그래밍 기사, 팁, 요령을 살펴보세요.부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3