async def streamlit_input_callback(request: HumanInputRequest) -> HumanInputResponse:
return HumanInputResponse(request_id=request.request_id, response="Approved.")
async def get_agent():
"""
Get existing agent from session state or create a new one
"""
if "agent" not in st.session_state:
mcp_agent = Agent(
name="MCP Agent",
instruction="*** System Propmt ***",
server_names=["postgres"],
connection_persistence=False,
human_input_callback=streamlit_input_callback,
)
await mcp_agent.initialize()
st.session_state["agent"] = mcp_agent
if "llm" not in st.session_state:
st.session_state["llm"] = await st.session_state["agent"].attach_llm(AnthropicAugmentedLLM)
return st.session_state["agent"], st.session_state["llm"]
import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
# Read the CSV files into Pandas Dataframes
df_player_data = pd.read_csv('player_data.csv')
# Display the first 5 rows of each DataFrame
print(df_player_data.head().to_markdown(index=False, numalign="left", stralign="left"))
# Print the column names and their data types for each DataFrame
print(df_player_data.info())
# Count the number of players by country
player_counts_by_country = df_player_data['country_code'].value_counts().reset_index()
player_counts_by_country.columns = ['country_code', 'num_players']
# Print the first 5 rows of the dataframe
print(player_counts_by_country.head().to_markdown(index=False, numalign="left", stralign="left"))
# Print the column name and their data types
print(player_counts_by_country.info())
import altair as alt
# Create the bar chart
chart = alt.Chart(player_counts_by_country).mark_bar().encode(
# Set `country_code` to x-axis and set the label as 'Country Code'
x=alt.X('country_code', title='Country Code'),
# Set `num_players` to y-axis and set the label as 'Number of Players'
y=alt.Y('num_players', title='Number of Players'),
tooltip=['country_code', 'num_players'] # Add tooltip
).properties(
title='Number of Players by Country' # Set the title of the chart to 'Number of Players by Country'
).interactive() # Make the chart Interactive
# Save the chart
chart.save('number_of_players_by_country_bar_chart.json')
ひとまず入力したcsvを理解してプロットまではできているようです。
MAU(Monthly Active User)をプロット
それでは次に、運営タイトルではよく確認される MAU をプロットさせます。追加で以下のプロンプトを入力しました。
player_login_logs をもとに各月のユーザー数をプロットしてください。これをMonthly Active User(MAU)と定義します。
event_masterにはstart_atとend_atが指定されており、イベント開催期間が設定されています。このイベント開催期間にログインしたユーザーをplayer_login_logsを参照してプロットしてください。X軸はevent_masterのcodeとします。これをEvent Active User (EAU)と定義します。
画面上の「Weather Agent」をクリックし、「Write a message…」と書かれているところに「渋谷の天気を知りたい」と入れて送信すると、現時点(2025/3/31の午後6時)だと以下のような結果が返ってきます。後で説明しますが、これはopen-meteo.comという緯度経度から現在の天気を教えてくれるAPIの結果をもとに出力されています。
Shibuya's current weather is overcast with a temperature of 7.6°C, but it feels like 4.5°C due to the wind. The humidity is at 76%, and there is a wind speed of 11.3 km/h with gusts up to 29.9 km/h.
export const weatherAgent = new Agent({
name: 'Weather Agent',
instructions: `
You are a helpful weather assistant that provides accurate weather information.
Your primary function is to help users get weather details for specific locations. When responding:
- Always ask for a location if none is provided
- If the location name isn’t in English, please translate it
- If giving a location with multiple parts (e.g. "New York, NY"), use the most relevant part (e.g. "New York")
- Include relevant details like humidity, wind conditions, and precipitation
- Keep responses concise but informative
Use the weatherTool to fetch current weather data.
`,
model: openai('gpt-4o'),
tools: { weatherTool },
});
ここからWeather Agentについて以下のことがわかります。
instructionsで天気情報を提供することを命じられている
modelでopenaiの”gpt-4o”のAIモデル(LLM)を使用するように設定されている
toolsでweatherToolが指定されている
instructionsはそのAgentの基本動作を規定します。これをもとにAIモデル(openAIのgpt-4o)は何をユーザから聞き出し、何を実行し、何をユーザに提供するかをの指針を得ることができます。今回の例であれば天気を調べるにあたり必要な情報(location)を理解します。そして、天気の情報を得るために、weatherToolというツールを使えること、およびユーザに提供する情報に含めるべきこと(wind conditionsなども含める)や、形式(concise but informative)について理解します。
const weatherWorkflow = new Workflow({
name: 'weather-workflow',
triggerSchema: z.object({
city: z.string().describe('The city to get the weather for'),
}),
})
.step(fetchWeather)
.then(planActivities);
weatherWorkflow.commit();
import { AgentNetwork } from '@mastra/core';
import { openai } from '@mastra/openai';
// Create specialized agents
const webSearchAgent = new Agent({
name: 'Web Search Agent',
instructions: 'You search the web for information.',
model: openai('gpt-4o'),
tools: { /* web search tools */ },
});
const dataAnalysisAgent = new Agent({
name: 'Data Analysis Agent',
instructions: 'You analyze data and provide insights.',
model: openai('gpt-4o'),
tools: { /* data analysis tools */ },
});
// Create the network
const researchNetwork = new AgentNetwork({
name: 'Research Network',
instructions: 'Coordinate specialized agents to research topics thoroughly.',
model: openai('gpt-4o'),
agents: [webSearchAgent, dataAnalysisAgent],
});
// Use the network
const result = await researchNetwork.generate('Research the impact of climate change on agriculture');
console.log(result.text);
上記はMastraの公式のサンプルですがこのように、複数のAgentをAgentNetworkに集めて、’Research the impact of climate change on agriculture’というプロンプトから適切なAgentを自律的に選択しながら、気候変動の農業の影響を調査するタスクを実行します。
Macの場合、デフォルトでzipでダウンロードされるので、ダブルクリックで解凍します。すると「Visual Studio Code – Insiders.app」というファイルが出てくるので、それをダブルクリックすることで、VSCodeを起動することができます。通常のVSCodeはブルーのアイコンになっていますが、Insiders版はエメラルドグリーンのアイコンになっています。必要に応じて、アプリケーションフォルダに移動することで、Launchpadからも選択できる様になります。