Spaces:
Sleeping
Sleeping
Update third.py
Browse files
third.py
CHANGED
|
@@ -3,78 +3,76 @@
|
|
| 3 |
import os
|
| 4 |
import openai
|
| 5 |
import json
|
|
|
|
| 6 |
from langchain.chat_models import ChatOpenAI
|
| 7 |
from langchain_experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner
|
| 8 |
from langchain.llms import OpenAI
|
| 9 |
-
from langchain.utilities import GoogleSearchAPIWrapper
|
| 10 |
from langchain.agents.tools import Tool
|
| 11 |
from bs4 import BeautifulSoup
|
| 12 |
import asyncio
|
| 13 |
from datetime import timedelta
|
| 14 |
|
| 15 |
-
# APIキー
|
| 16 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
# 実行された指示を追跡するリスト
|
| 21 |
executed_instructions = []
|
| 22 |
-
|
| 23 |
# 調査結果を保存するリスト
|
| 24 |
research_results = []
|
| 25 |
|
| 26 |
async def main(editable_output2, keyword_id):
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
tools = [
|
| 30 |
-
Tool(
|
| 31 |
-
name = "Search",
|
| 32 |
-
func=search.run,
|
| 33 |
-
description="useful for when you need to answer questions about current events"
|
| 34 |
-
),
|
| 35 |
-
]
|
| 36 |
|
| 37 |
-
#
|
| 38 |
model_name = "gpt-3.5-turbo-1106"
|
| 39 |
llm = ChatOpenAI(model_name=model_name, temperature=0, max_tokens=1000)
|
| 40 |
planner = load_chat_planner(llm)
|
| 41 |
executor = load_agent_executor(llm, tools, verbose=True)
|
| 42 |
|
| 43 |
-
# ここでexecutorの内容を出力して確認
|
| 44 |
-
print("Executor:", executor)
|
| 45 |
-
|
| 46 |
agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)
|
| 47 |
|
| 48 |
-
#
|
| 49 |
soup = BeautifulSoup(editable_output2, 'html.parser')
|
| 50 |
-
|
| 51 |
-
# Use the text of the h1 tag as the purpose.
|
| 52 |
h1_text = soup.find('h1').get_text()
|
| 53 |
-
|
| 54 |
-
# Use the text of the h2 tags as part of the purpose.
|
| 55 |
h2_texts = [h2.get_text() for h2 in soup.find_all('h2')]
|
| 56 |
-
|
| 57 |
-
# Use the text of the h3 tags as part of the purpose.
|
| 58 |
h3_texts = [h3.get_text() for h3 in soup.find_all('h3')]
|
| 59 |
|
| 60 |
-
# Generate the purpose.
|
| 61 |
purpose = f"about {h1_text}, focusing particularly on {' and '.join(h2_texts)} and {' and '.join(h3_texts)}, to investigate the latest information and details"
|
| 62 |
|
| 63 |
-
#
|
| 64 |
-
if "人物" in h1_text or any("人物" in
|
| 65 |
-
# If the topic is about a person, specify that you want to research their name and career.
|
| 66 |
purpose += " including the person's name and career"
|
| 67 |
-
elif "商品" in h1_text or any("商品" in
|
| 68 |
-
# If the topic is about a product, specify that you want to research the brand name, product name, and price.
|
| 69 |
purpose += " including the brand name, product name, and price"
|
| 70 |
-
elif "イベント" in h1_text or any("イベント" in
|
| 71 |
-
# If the topic is about an event, specify that you want to research the event's content, schedule, and venue.
|
| 72 |
purpose += " including the event's content, schedule, and venue"
|
| 73 |
|
| 74 |
-
# Convert the purpose into an instruction in the form of a question.
|
| 75 |
instruction = f"Can you research {purpose} and include specific details in your response? Please provide the information in Japanese."
|
| 76 |
|
| 77 |
-
# Run the instruction with a clear expectation of the output format
|
| 78 |
if instruction not in executed_instructions:
|
| 79 |
raw_output = agent.run(instruction)
|
| 80 |
executed_instructions.append(instruction)
|
|
@@ -84,41 +82,33 @@ async def main(editable_output2, keyword_id):
|
|
| 84 |
index = executed_instructions.index(instruction)
|
| 85 |
response_content = research_results[index]
|
| 86 |
|
| 87 |
-
# Prepare the system message
|
| 88 |
system_message = {
|
| 89 |
"role": "system",
|
| 90 |
"content": "あなたはプロのライターです。すべての回答を日本語でお願いします。"
|
| 91 |
}
|
| 92 |
|
| 93 |
-
# Prepare the user message
|
| 94 |
research_summary = "\n".join(research_results)
|
| 95 |
instructions = []
|
| 96 |
|
| 97 |
-
# 記事タイトルに関する指示
|
| 98 |
instructions.append(f"""
|
| 99 |
<h1>{h1_text}</h1>
|
| 100 |
"{h1_text}"に関する導入文を日本語で作成してください。直接的なコピーまたは近いフレーズを避けて、オリジナルな内容にしてください。""")
|
| 101 |
|
| 102 |
-
# research_summaryを文単位に分割
|
| 103 |
sentences = research_summary.split('。')
|
| 104 |
|
| 105 |
-
# 各見出しと小見出しに関する指示
|
| 106 |
for idx, h2_text in enumerate(h2_texts):
|
| 107 |
h3_for_this_h2 = [h3 for h3 in h3_texts if h3.startswith(f"{idx+1}-")]
|
| 108 |
instructions.append(f"""
|
| 109 |
<h2>{h2_text}</h2>
|
| 110 |
"{h2_text}"に関する導入文を日本語で作成してください。この導入文は、以下の小見出しの内容を考慮してください:{"、".join(h3_for_this_h2)}。直接的なコピーまたは近いフレーズを避けて、オリジナルな内容にしてください。""")
|
| 111 |
for h3 in h3_for_this_h2:
|
| 112 |
-
# 関連する文を基に、<h3>の内容に関する記事本文を生成
|
| 113 |
related_sentences = [sentence for sentence in sentences if h3 in sentence]
|
| 114 |
if related_sentences:
|
| 115 |
content_for_h3 = "。".join(related_sentences) + "。"
|
| 116 |
-
# <h3>タグを使用した指示に修正
|
| 117 |
instructions.append(f"""
|
| 118 |
<h3>{h3}</h3>
|
| 119 |
"{h3}"に関する詳細な内容として、以下の情報を日本語で記述してください:{content_for_h3} ここでも、オリジナルな内容を心がけてください。""")
|
| 120 |
else:
|
| 121 |
-
# <h3>タグを使用した指示に修正
|
| 122 |
instructions.append(f"""
|
| 123 |
<h3>{h3}</h3>
|
| 124 |
"{h3}"に関する詳細な内容を日本語で記述してください。オリジナルな内容を心がけてください。""")
|
|
@@ -128,7 +118,6 @@ async def main(editable_output2, keyword_id):
|
|
| 128 |
"content": "\n".join(instructions)
|
| 129 |
}
|
| 130 |
|
| 131 |
-
# Generate a new text using the ChatCompletion API
|
| 132 |
response = openai.ChatCompletion.create(
|
| 133 |
model="gpt-4-0125-preview",
|
| 134 |
messages=[system_message, user_message],
|
|
@@ -136,10 +125,7 @@ async def main(editable_output2, keyword_id):
|
|
| 136 |
)
|
| 137 |
result = response.choices[0]["message"]["content"]
|
| 138 |
|
| 139 |
-
# Save the generated message to output3.txt
|
| 140 |
with open('output3.txt', 'w', encoding='utf-8') as f:
|
| 141 |
f.write(result)
|
| 142 |
|
| 143 |
-
|
| 144 |
-
print(result)
|
| 145 |
-
|
|
|
|
| 3 |
import os
|
| 4 |
import openai
|
| 5 |
import json
|
| 6 |
+
import requests
|
| 7 |
from langchain.chat_models import ChatOpenAI
|
| 8 |
from langchain_experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner
|
| 9 |
from langchain.llms import OpenAI
|
|
|
|
| 10 |
from langchain.agents.tools import Tool
|
| 11 |
from bs4 import BeautifulSoup
|
| 12 |
import asyncio
|
| 13 |
from datetime import timedelta
|
| 14 |
|
| 15 |
+
# APIキーの設定
|
| 16 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 17 |
+
TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')
|
| 18 |
+
|
| 19 |
+
# Tavily APIのツールを定義
|
| 20 |
+
class TavilySearchTool:
|
| 21 |
+
@staticmethod
|
| 22 |
+
def search(query):
|
| 23 |
+
response = requests.post('https://api.tavily.com/search', headers={
|
| 24 |
+
'Content-Type': 'application/json'
|
| 25 |
+
}, json={
|
| 26 |
+
'api_key': TAVILY_API_KEY,
|
| 27 |
+
'query': query,
|
| 28 |
+
'max_results': 10,
|
| 29 |
+
'include_answers': True
|
| 30 |
+
})
|
| 31 |
+
if response.status_code == 200:
|
| 32 |
+
return response.json()['results']
|
| 33 |
+
else:
|
| 34 |
+
raise Exception("Failed to fetch data from Tavily API")
|
| 35 |
|
| 36 |
# 実行された指示を追跡するリスト
|
| 37 |
executed_instructions = []
|
|
|
|
| 38 |
# 調査結果を保存するリスト
|
| 39 |
research_results = []
|
| 40 |
|
| 41 |
async def main(editable_output2, keyword_id):
|
| 42 |
+
tavily_search_tool = Tool(
|
| 43 |
+
name="TavilySearch",
|
| 44 |
+
func=TavilySearchTool.search,
|
| 45 |
+
description="Search tool using Tavily API"
|
| 46 |
+
)
|
| 47 |
|
| 48 |
+
tools = [tavily_search_tool]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
# PlannerとExecutorの定義
|
| 51 |
model_name = "gpt-3.5-turbo-1106"
|
| 52 |
llm = ChatOpenAI(model_name=model_name, temperature=0, max_tokens=1000)
|
| 53 |
planner = load_chat_planner(llm)
|
| 54 |
executor = load_agent_executor(llm, tools, verbose=True)
|
| 55 |
|
|
|
|
|
|
|
|
|
|
| 56 |
agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)
|
| 57 |
|
| 58 |
+
# HTML解析
|
| 59 |
soup = BeautifulSoup(editable_output2, 'html.parser')
|
|
|
|
|
|
|
| 60 |
h1_text = soup.find('h1').get_text()
|
|
|
|
|
|
|
| 61 |
h2_texts = [h2.get_text() for h2 in soup.find_all('h2')]
|
|
|
|
|
|
|
| 62 |
h3_texts = [h3.get_text() for h3 in soup.find_all('h3')]
|
| 63 |
|
|
|
|
| 64 |
purpose = f"about {h1_text}, focusing particularly on {' and '.join(h2_texts)} and {' and '.join(h3_texts)}, to investigate the latest information and details"
|
| 65 |
|
| 66 |
+
# 特定情報の指定
|
| 67 |
+
if "人物" in h1_text or any("人物" in h2 for h2 in h2_texts) or any("人物" in h3 for h3 in h3_texts):
|
|
|
|
| 68 |
purpose += " including the person's name and career"
|
| 69 |
+
elif "商品" in h1_text or any("商品" in h2 for h2 in h2_texts) or any("商品" in h3 for h3 in h3_texts):
|
|
|
|
| 70 |
purpose += " including the brand name, product name, and price"
|
| 71 |
+
elif "イベント" in h1_text or any("イベント" in h2 for h2 in h2_texts) or any("イベント" in h3 for h3 in h3_texts):
|
|
|
|
| 72 |
purpose += " including the event's content, schedule, and venue"
|
| 73 |
|
|
|
|
| 74 |
instruction = f"Can you research {purpose} and include specific details in your response? Please provide the information in Japanese."
|
| 75 |
|
|
|
|
| 76 |
if instruction not in executed_instructions:
|
| 77 |
raw_output = agent.run(instruction)
|
| 78 |
executed_instructions.append(instruction)
|
|
|
|
| 82 |
index = executed_instructions.index(instruction)
|
| 83 |
response_content = research_results[index]
|
| 84 |
|
|
|
|
| 85 |
system_message = {
|
| 86 |
"role": "system",
|
| 87 |
"content": "あなたはプロのライターです。すべての回答を日本語でお願いします。"
|
| 88 |
}
|
| 89 |
|
|
|
|
| 90 |
research_summary = "\n".join(research_results)
|
| 91 |
instructions = []
|
| 92 |
|
|
|
|
| 93 |
instructions.append(f"""
|
| 94 |
<h1>{h1_text}</h1>
|
| 95 |
"{h1_text}"に関する導入文を日本語で作成してください。直接的なコピーまたは近いフレーズを避けて、オリジナルな内容にしてください。""")
|
| 96 |
|
|
|
|
| 97 |
sentences = research_summary.split('。')
|
| 98 |
|
|
|
|
| 99 |
for idx, h2_text in enumerate(h2_texts):
|
| 100 |
h3_for_this_h2 = [h3 for h3 in h3_texts if h3.startswith(f"{idx+1}-")]
|
| 101 |
instructions.append(f"""
|
| 102 |
<h2>{h2_text}</h2>
|
| 103 |
"{h2_text}"に関する導入文を日本語で作成してください。この導入文は、以下の小見出しの内容を考慮してください:{"、".join(h3_for_this_h2)}。直接的なコピーまたは近いフレーズを避けて、オリジナルな内容にしてください。""")
|
| 104 |
for h3 in h3_for_this_h2:
|
|
|
|
| 105 |
related_sentences = [sentence for sentence in sentences if h3 in sentence]
|
| 106 |
if related_sentences:
|
| 107 |
content_for_h3 = "。".join(related_sentences) + "。"
|
|
|
|
| 108 |
instructions.append(f"""
|
| 109 |
<h3>{h3}</h3>
|
| 110 |
"{h3}"に関する詳細な内容として、以下の情報を日本語で記述してください:{content_for_h3} ここでも、オリジナルな内容を心がけてください。""")
|
| 111 |
else:
|
|
|
|
| 112 |
instructions.append(f"""
|
| 113 |
<h3>{h3}</h3>
|
| 114 |
"{h3}"に関する詳細な内容を日本語で記述してください。オリジナルな内容を心がけてください。""")
|
|
|
|
| 118 |
"content": "\n".join(instructions)
|
| 119 |
}
|
| 120 |
|
|
|
|
| 121 |
response = openai.ChatCompletion.create(
|
| 122 |
model="gpt-4-0125-preview",
|
| 123 |
messages=[system_message, user_message],
|
|
|
|
| 125 |
)
|
| 126 |
result = response.choices[0]["message"]["content"]
|
| 127 |
|
|
|
|
| 128 |
with open('output3.txt', 'w', encoding='utf-8') as f:
|
| 129 |
f.write(result)
|
| 130 |
|
| 131 |
+
print(result)
|
|
|
|
|
|