TwitterでフォローしていいかどうかもGPTに決めてもらう世界線

必要性が不明の生成画像: https://www.bing.com/images/create

TwitterとOpenAIのAPIを繋いで評価を自動化します。

#!/usr/bin/env python

import os
import sys

import tweepy
from langchain import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import HumanMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate

# フォローしたいアカウントのタイプを定義する
preferences = "\n".join([
    "創造的な性格。",
    "新しいものが好き。",
    "建設的な発言が多い。",
])

username = sys.argv[1]
oauth2_bearer_token = os.environ['TWITTER_BEARER_TOKEN']

auth = tweepy.OAuth2BearerHandler(oauth2_bearer_token)
api = tweepy.API(auth)

tweets = api.user_timeline(screen_name=username)

user = tweets[0].user
user_dump = str({
    'id': user.id_str,
    'name': user.name,
    'screen_name': user.screen_name,
    'location': user.location,
    'description': user.description,
    'url': user.url,
    'followers_count': user.followers_count,
    'friends_count': user.friends_count,
    'listed_count': user.listed_count,
    'created_at': user.created_at,
    'favourites_count': user.favourites_count,
    'verified': user.verified,
    'statuses_count': user.statuses_count,
    'lang': user.lang,
})

tweet_texts = "\n".join([t.text for t in tweets])

messages = [
    SystemMessagePromptTemplate.from_template(""""tweetの内容を分析してuserがどのような人物なのかを分析してください。
score: preferencesに一致するかを1~5で評価してください。
explain: scoreの理由を説明してください。

preferences:
{preferences}

結果をscore, explainの順で出力してください。 
"""),
    HumanMessagePromptTemplate.from_template("user:\n{user_dump}\ntweet:\n{tweet_texts}"),
]

chat_prompt = ChatPromptTemplate(input_variables=['preferences', 'user_dump', 'tweet_texts'], messages=messages)

llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=1.0, streaming=True)
chain = LLMChain(prompt=chat_prompt, llm=llm)

result = chain.run({'user_dump': user_dump, 'tweet_texts': tweet_texts, 'preferences': preferences})

print(f"# https://twitter.com/{username} の評価")
print(result)

以下のように実行します。

> ./main.py elonmusk


# https://twitter.com/elonmusk の評価
score: 
創造的な性格に5
新しいものが好きに5
建設的な発言が多いに4

explain:
Elon Muskは新しい技術やコンセプトに強い関心を持ち、自身でも革新的なアイデアを次々と生み出しています。彼のtweetには創造性に溢れた発言が多く、新しいものに対して興味を持っていると思われます。
  た、彼の多様なビジネスにおいて、建設的な意見を提供していることも知られています。しかしながら、時には非建設的な発言もするため、建設的な発言が多いという点で4としました。

LangChainをわざわざ使っているのは当初OutPutParserでCSVに吐き出して一括処理を目論んでいたからです。LLMがいうこと聞いてくれないので諦めました。

PS: 自分のアカウントを与えてみたら「若干自己中心的な人物であるかもしれません」とやんわりDISられました。