Building a Stockbroker Agent in LangGraph.js
Summary
TLDRこのビデオでは、Lang Chainを使用してフルスタック株式ブローカーエージェントを実装する方法が説明されています。バックエンドはLangraバックエンドで、フロントエンドはNext.jsで書かれています。エージェントは、Financial APIsから詳細を取得し、株の購入に関するインフォームドな意思決定を支援します。人間ループ機能により、購入前に確認が必要な場合にダイナミックインタラプトが発生し、購入が承認されるまで実行されません。デプロイメントとフロントエンドの統合方法も学びます。
Takeaways
- 😀 ビデオでは、Lang Chainを使用してフルスタックの株式ブローカーエージェントを実装する方法が説明されています。
- 🛠️ 実装には、Lang ChainのバックエンドとNext.jsで書かれたフロントエンドが含まれています。
- 🌐 バックエンドは、金融APIから企業や株の詳細をフェッチする機能を持っています。
- 📈 利用されるAPIは、Vera's Financial APIが挙げられます。このAPIを使用して、株の価格や企業の収入報告書などのデータを取得します。
- 💼 エージェントは株の購入詳細を準備し、購入を実行する前に人間ループ機能で購入確認を求めます。
- 🔄 購入確認が行われる前に、ダイナミックな割り込みが発生し、購入は承認されるまで中断されます。
- 💻 購入は実際にはモックであり、本物の株購入は実行されませんが、本番環境での動作と同様のプロセスが模倣されています。
- 🔗 フロントエンドでは、ユーザーがメッセージを送信すると、バックエンドのLang Chainグラフにイベントが流れます。
- 📊 購入の確認やキャンセルは、ユーザーインターフェースで行い、状態が更新されるとグラフは続行されます。
- 🚀 ビデオでは、Lang Chain Studioを使用してグラフをデプロイし、クラウドに配置する方法も説明されています。
Q & A
ビデオではどのようなアプリケーションを実装していますか?
-ビデオでは、フルスタック株式ブローカーエージェントを実装しています。これは、人間ループ機能を備えており、金融APIから企業の詳細や株価を取得することができます。
どのような技術スタックを使用していますか?
-バックエンドはLangChainを使用し、フロントエンドはNext.jsで書かれています。また、LangChain Cloudにデプロイされます。
人間ループ機能とは何ですか?
-人間ループ機能とは、エージェントが株の購入を実行する前に、購入確認フィールドがtrueに設定されていない場合にダイナミックインタラプトを発生させ、購入を実行する前にユーザーによる確認を必要とする機能です。
購入確認はどのように行われますか?
-購入確認は、購入確認フィールドがtrueに設定されるまで購入は実行されません。ユーザーはこのフィールドをtrueに設定するか、購入をキャンセルする必要があります。
株の購入は実際に実行されますか?
-ビデオではモック購入が行われ、実際の購入は実行されません。しかし、本番環境で構築する場合は、購入APIコールを実行する機能と同様に動作します。
デプロイメントプロセスにはどのようなステップがありますか?
-デプロイメントプロセスには、LangChain Studioに移動し、新しいデプロイメントを作成し、Gitリポジトリをリンクし、デプロイメントタイプと環境変数を指定し、デプロイメントを完了するというステップがあります。
フロントエンドで何が行われますか?
-フロントエンドでは、ユーザーがメッセージを送信し、バックエンドのLangChainエージェントと対話することができます。また、購入の確認やキャンセルなどの操作を行うことができます。
ビデオのデモではどの企業の株価を取得していますか?
-ビデオのデモでは、Googleの現在の株価を取得しています。
購入を確認する方法として2要素認証は推奨されますか?
-本番環境では、購入を確認する方法として2要素認証を導入することが推奨されますが、ビデオのデモではシンプルなブールフィールドを使用しています。
デプロイメントが完了した後、どのようにしてフロントエンドに接続しますか?
-デプロイメントが完了した後、API URLをコピーし、それをフロントエンドの環境変数ファイルに設定して、Next.jsアプリケーションを立ち上げます。
Outlines
🚀 ビデオ概要とプロジェクトの紹介
このビデオでは、 Brace が Lang Chain と呼ばれるプラットフォームを使用してフルスタック株取引エージェントを実装する方法について説明しています。このエージェントには、人間ループ機能が備わっており、金融APIから公開企業の詳細や株の価格を取得することができます。また、モック購入の詳細を準備し、購入が確認されるまで中断されるというプロセスが説明されています。
🛠️ 各ノードの機能とコードの詳細
ビデオでは、各ノードの役割とコードの詳細について説明しています。特に、購入確認フィールドが真に設定されていない場合に発生するダイナミック中断、購入詳細の準備、購入実行ノードの動作について詳述されています。また、Lang Smith Studio でのグラフの動作やデプロイメントの方法も紹介されています。
🌐 Lang Smith でのデプロイメントと設定
デプロイメントプロセスが説明されています。これは、Lang Smith プラットフォーム上で新しいデプロイメントを作成し、Git リポジトリをリンクし、API 構成ファイルのパスを指定するプロセスです。また、環境変数の設定方法やデプロイメントの確認方法についても説明されています。
🖥️ フロントエンドのセットアップと動作
フロントエンドのセットアップと動作が説明されています。これには、環境変数の設定、Next.js アプリケーションの起動、ユーザーインターフェースでの質問の送信、購入の確認プロセスが含まれています。また、購入が完了した後のメッセージの表示方法や、実際の購入が行われる場合のセキュリティ対策についても触れられています。
🎉 プロジェクトの完成と期待
最後に、プロジェクトの完成と、ユーザーがどのようにこの技術を利用して独自のアプリケーションを構築できるかについて話されています。また、ビデオの視聴者に対して、今後のプロジェクトや構築物への期待を表しています。
Mindmap
Keywords
💡フルスタック
💡Lang Chain
💡Human Loop
💡Next.js
💡API
💡デプロイ
💡Docker
💡条件エッジ
💡トランザクション
💡フロントエンド
Highlights
介绍如何实现全栈股票经纪代理,包括Langchain后端和Next.js前端。
代理具有人机循环功能,可以从金融API获取数据。
使用Vera的金融数据集API来获取不同上市公司和股票价格的数据。
代理可以获取股票当前价格、收入报告等数据,以便做出明智的购买决策。
在执行购买之前,如果购买确认字段未设置为true,则会触发动态中断。
演示了如何通过消息询问Google当前股价,并得到响应。
展示了如何准备购买股票的细节,并在没有用户确认的情况下中断购买流程。
用户可以通过设置购买确认字段为true来执行购买。
即使在新的对话线程中,未设置购买确认也会导致购买无法执行。
介绍了如何通过代码实现每个节点的功能。
展示了如何使用Langchain工具节点和工具调用。
详细解释了准备购买细节节点的逻辑和功能。
说明了执行购买节点如何工作,包括确认购买的逻辑。
介绍了如何配置Langchain JSON文件以部署到Langchain Cloud。
演示了如何在Langchain Cloud上部署图,并连接到前端。
展示了如何在Next.js前端中使用聊天界面与生产服务器交互。
提供了如何在生产环境中实现全栈Langchain和Next.js应用程序的示例。
视频结束时,鼓励观众构建自己的应用程序并探索Langchain的可能性。
Transcripts
what's going on everyone it's brace from
Lang chain and in this video we're going
to be implementing a full stack stock
broker human Loop agent including a
langra backend um which we're then going
to deploy to L graph cloud and
production at the end of the video as
well as a front end written in xjs so
this graph we're going to be building is
a stock broker agent which has some
human Loop capabilities where our agent
can fetch details from Financial apis if
you're on Twitter you're probably
familiar with verat we're going to be
using his financial um data sets API to
fetch data about different public
companies and then also prices of stocks
um so big thank you to him for building
out this great financial data API uh so
our agent has a series of tools that it
can call around getting the current
price of a stock getting some you know
revenue reports or some uh different
data that these public companies have to
disclose so that our agent can make
informed decisions about purchasing
stocks um it can then also prepare
purchase details if we ask it to
purchase a stock and then the human Loop
portion um is before it executes the
purchase uh if the purchase confirmed
field in our state is not set to true
then it will throw a dynamic interrupt
interrupt our our graph and we will have
to set this Feld to true or else the um
purchase will not be able to go through
these purchases are just mock stock
purchases they're not actually executing
purchases um but it works pretty much
the same way minus the execute purchase
API call you'd make um if you were to
build this for production so we can try
out a quick message here saying what is
Google's current price and on the right
we see all the events stream in so we
see our LM called the price snapshot
tool the price snapshot tool return
Google's current price and that got sent
back to the LM where it generated a
plain text response saying Google's
current stock price is
$157 we can add a new message saying
let's buy four shares when we submit
that it called the purchase stock tool
that then got routed to the prepare
purchase details node where it prepared
all the purchase details um and before
it could execute the execute purchase
node the graph was interrupted and this
is because purchase confirmed is not set
to true if we inspect the current state
we can see that we have our messages in
our state our requested stock purchase
details object which is what the execute
purchase node needs in order to actually
execute the purchase however purchase
confirmed is not present so if we check
this box here and then update it to
execute this as the prepare purchase
details node so the node that just ran
and resubmit then now purchase confirm
will be true and it should be able to
execute the purchase and the LM should
tell us that it executed the purchase so
we hit submit we see purchase confirm
true and then our llm called the execute
purchase node where it return
successfully purchase four shares of
Google at $157 a share now if we were to
create a new thread and say what's
Google's current stock price submit it
and then once this goes through we can
say let's buy four shares or let's not
set this to true and instead let's say
let's buy four shares we hit
submit it then obviously will not be
able to execute the execute purchase
node because purchase confirmed is not
set to True um and then if we try and
continue it since purchase confirmed is
not set to true it will never be able to
execute this node which is exactly what
we want so we can see doesn't matter how
many times we click continue it is never
able to execute the purchase it also
doesn't matter if we send in a new
message saying execute the purchase uh
we have to explicitly set this field to
true we can send in a new message and as
we can see it did not work even though
it updated the state at the end to
include that it is just unable to call
the node because of our node interrupt
uh which we throw if purchase confirmed
is not true so now that we have a good
highle idea how our graph Works let's go
jump into the code and see exactly how
each node works so to follow along
you're going to want to clone the Lang
graph JS examples repository I'll add a
link to it in the description and then
once you've cloned that navigate into
the stock broker directory I already
have it cloned so I can open it up and
as you can see the stock broker
directory is formatted in a monor repo
like way where we have two projects back
end and front end inside of our
directory and then a root package Json
and a turbo. Json file because we're
using turbo repo to manage our monor
repo so to install dependencies for a
stock broker you can just run yarn
install from the root of the stock
broker directory and that will install
all the dependencies you need for the
back end and the front end and then once
you've done that you can navigate into
backend and index.ts where we have the
code defined for our stock broker agent
so as you can see at the top of our file
the first thing we Define is our graph
annotation this defines the state of our
graph and the different fields which we
can return and pass through to each of
our nodes we are importing the messages
annotation uh State object from Lang
graph where we spread that and that
essentially adds the messages field to
our state um and this is of type base
message or a list of Base messages um
and then when you return a message into
the state it gets concatenated uh to the
current state with a little more logic
around adding and removing messages the
next field we have is the requested
stock purchase details field and this is
of a type ticker uh qu and Max purchase
and this contains the fields which our
prepare purchase details node generates
uh so that when we want to actually
execute the purchase we have exactly the
fields that we need to execute that
purchase finally we have purchase
confirmed uh which is a Boolean and this
is the field we use to determine whether
or not a user has actually confirmed a
purchase we're using gbd4 for this but
you can use any LM you'd like and then
we pass all of our tools to a tool node
a tool node is a built-in class that is
exported from lingraph where you can
pass in a list of tools added as a node
and then anytime that node is invoked
and it's passed an AI message um from an
LM that contains a tool call it will map
the generated tool call to one of the
tool calls you passed in and then invoke
the function on that tool call if we
inspect this list we see we have a web
search tool purchase stock tool and then
a series of other tools from the
financial data sets API which allow us
to get things like the current price
some company facts um and so on we can
inspect the per purchase stock tool for
example and as we can see it's a simple
L chain tool uh that for the function it
just returns a string saying please
confirm you would like you want to
purchase uh this many shares of this
ticker at the purchase price per share
or the current price the schema contains
ticker company name quantity and Max
purchase price which are all optional
and we'll get to why these are all
optional when we inspect the prepare
purchase details node um and then all
the other tools are built pretty much
the same way however the ones which call
an API have this call financial data
data sets API function inside them where
they are actually hitting the financial
data sets. a API so that's the um tools
which we provide to the model and then
the first node we have is call model
this call model maps to the agent node
if we scroll to the bottom we can see in
our graph we've defined the agent node
with the call model function um and then
every time we start we will always map
to the agent node and that's what we can
see right here start always goes to the
agent node so if we inspect this node we
can see it takes in an argument of state
which contains all the fields in our
state we extract the messages and then
we Define a simple system message are
just saying things like you're a
financial analyst you can do XYZ you
have a series of tools um provided to
you we then bind all of our tools to the
LM so that our LM can actually invoke
the tools that will need to be routed to
the tool router prepare purchase details
node and then we invoke the LM always
passing the system message as the first
message and then the rest of the message
come after finally we return the result
to the messages field and then our
messages annotation State object will
handle concatenating this new AI message
to the rest of our messages in our state
we can see we've defined a conditional
edge here which always occurs after the
agent node is invoked um and that's why
our agent node has all of these dotted
lines coming out of it or dotted arrows
sorry these dotted arrows indicate a
conditional Edge that this node can take
so we can either go to the tools node
prepare purchase details node and so on
and we can see the different options
that this condition Edge can take are
the tools node it can end it can call
the prepare purchase details node and
finally it can call the execute purchase
node so if we inspect the should
continue function we see it also takes
in a state argument the as as the first
argument um and the type of it is the
graph annotation we defined and then we
extract the messages requested stock
purchase details fielded from the state
and we make sure that the last message
is either an AI message or um if it's
not an AI message we return and if it is
an AI message but is not have tool calls
we also return uh so we return this
special end variable here and that will
essentially map our agent to the end so
if there were no tool calls called or if
it was say a human message somehow made
it to the last message in the list then
just return because there's no more
actions for the agent to take next if
you have populated the request stock
purchase details field then we want to
map to the execute purchase node um
that's because if this field is
populated that means that there is a
stock purchase which the user uh is
trying to put through so we want to map
it to this noes so that I can execute
the purchase or it will be interrupted
if you've not set um purchase confirm to
true then we extract the tool calls from
the message and throw an error if none
exist and then finally we iterate over
all the tool calls and we say if the
tool name is purchase stock so if they
called this purchase stock tool then we
want to route to the prepare purchase
details node and if it's not route to
the tools node um which has access to
all the different tools we defined and
it can invoke the functions on those
tools we want to route to a special node
for the prepare purchase details um
function because this contains some
extra logic that doesn't live inside of
our tool so we've seen the call model
node we've seen the tool node and we've
seen our conditional Edge for the agent
next we can inspect the prepare purchase
details node and then finally the excute
purchase details node so for the prepare
purchase details node which is this node
we see right here once again it takes in
the state it extracts the message and if
the last message is not an AI message
throw an error because that's unexpected
next we look for the purchase stock tool
call if it do not exist throw an error
because once again this should always
exist if this note is being called then
we extract the max purchase price
company name and ticker fields from that
tool call so this tool call is going to
use the context in the message history
um and or if the user just said I want
to buy you know this many shares of this
company for this price um it'll extract
those and then pass them to the tool
where we're get given structured output
like we see here then if the user does
not define a ticker see we allow for for
a company name and a ticker if they do
not Define a ticker we then check to see
if they Define a company name if they
did not Define a company name then we
want to return early um and as this
comment States right here since the last
call is a tool call we will always need
to have a tool message follow that tool
call and that is because the open AI API
simply does not allow for messages which
are not tool messages to follow AI
messages which called tools so we just
return a tool call or tool message
saying please provide missing
information um and then we provide an AI
message saying please provide either the
company ticker or the company name to
purchase a stock since this is an AI
message uh with a string content and no
tool calls it'll just get routed to the
end and that will you know tell the user
you need to provide either the company
ticker or the company name however if
they did Define a company name then we
can pass it to the find company name
function essentially what this function
does is it takes in the company name it
calls the web search tool which is
powered by T to search the web for the
ticker for this company name and then we
pass the search results of the TV search
results tool to an llm with a simple
structured output um tool bound to it
saying extract the ticker from the
search results and then we return the
ticker next if the user did not Define a
Max purchase price then we're going to
invoke the price snapshot tool passing
in the ticker uh because the per Max
purchase price defaults to the current
price if it's not specified and then we
assign the max purchase price um
variable to the result of the price
snapshot tool call finally we return the
requested stock purchase details object
and that's what our exq purchase uh node
needs in order to execute the purchase
passing in the ticker the quantity uh
defaulting to one and then the max
purchase price next we see we have the
execute purchase node and that's this
one the first thing we do is we extract
the purchase confirmed Boolean field and
the requested stock purchase details
field from the state if you have not
defined your requested stock purchase
details we throw an error this should
never happen because this this node
should only ever be called after the
prepare purchase Det details um but if
somehow it is called we want to throw an
error because you cannot purchase a
stock if you don't know what you're
purchasing then we check for the
purchase confirmed field this is
important because here we're throwing a
special type of error node interrupt
because if you have not specified
purchase confirmed true right if this is
false then we need to interrupt the
graph saying please confirm the purchase
before executing uh in order to allow
the user to set purchase confirmed to
true or false if they don't want to
confirm it this is so we can't just say
the LM buy four shares and then it goes
through and just buys these shares right
away without letting us confirm so if
purchase confirmed is not true we're
going to interrupt the graph with this
special error here which we can throw
inside any node um and that will
interrupt the graph like we saw in the
studio allow us to update the state and
then it can
continue it's important to note that in
the real world in production you're
probably going to want to have some sort
of two-factor authentication here
instead of a simple Boolean field uh
where the user you know adds some
two-factor authen authentication code
and then in your backend you validate
that code to ensure that they actually
are allowed to confirm purchases but in
this case we just have a simple Boolean
field because we're not actually
purchasing stocks so if all this is
defined then we execute the purchase um
in our case it's just returning a new
message um an AI message saying
successfully purchased this many shares
at this price and once again since it's
a text message it will get routed back
to the agent where the agent will say
okay it's an AI message and there are no
tool calls so route to the end and then
that will finish the
graph now let's inspect our L graph .
Json file this is where we Define all
the configuration for running our graph
in the studio and also deploying it to
the cloud which will do in just a second
we can specify things like the node
version we can customize our Docker file
the dependencies in this case I just
said to look inside this directory and
install the dependencies inside this
directory and then our graphs we only
have one graph here stock broker uh but
if you are building a larger application
you can Define as many graphs you would
like and then finally we Define our
environment variable file and this tell
the studio for local development where
to find our secrets so it can actually
invoke our not that require these
specific API Keys okay so now that we've
looked at exactly how our graph works we
can go and deploy it to production and
then hook it up to our front end and run
it and see how it would work with a chat
likee interface so to deploy your graph
to production you're going to want to go
to Lang Smith and then to the
deployments tab and click new deployment
here you can link your GI up repository
if you've not already linked it
um and once you've done that you can
select a rebook from the drop down in my
case it's going to be Lang graph JS
examples and then you want to give it a
name so we'll use the default name for
now um and then after that you want to
specify the path to the Lang graph API
config file and this is the path or this
is the file that we were just looking at
a moment ago and in our case it's going
to be nested inside of the uh stock
broker SLB backend directory so when
we've updated that path our Cloud
deployment will actually be able to find
the proper Lang graph config uh file and
all the different configurations we've
stated next you can specify a git Branch
if you want to customize that in our
case main is fine and then a deployment
type so if you're going to production
you're obviously going to want to select
production here but for us uh just
development is okay and then your
environment variables uh this is where
you would add your uh financial data
sets API key your T API key and your
open AI API key you do not need to add a
lang Smith API key because lra Cloud
will automatically create a new tracing
project just for this deployment and
then all the different lsmith runs and
events that occur inside this production
deployment will automatically get mapped
to this uh project and the API keys for
this project are in are injected right
to your deployment so there's no need to
specify any sort of L Smith API keys
because we do all that for you when
you're done you hit submit and then when
your deployment is finished you can open
it up like this open up the uh
deployment page right here and you see a
bunch of different things like your
tracing project the repository which
this was loaded in from this is the
production API URL and it's how you'll
actually hit your API um and you can see
things like the different uh runs which
were occurred or which were invoked
using your production endpoint so we can
inspect all of these um just like you
would if you were say looking at your
runs inside your projects from the
project page you can also check out the
different revisions um a revision is
essentially when you make a change to
your code you need to trigger a new
revision by clicking new revision here
um and that will redeploy your app using
the new code you can also open it up in
L graph Studio and this looks pretty
much the same as the langra studio
you're running locally however this is
connected to your production endpoint um
and you can interact with it the exact
same way you would using the local
version uh but of course this is going
to hit the production end point so now
this is done we can copy our API URL and
then navigate back to our GitHub
repository go into the front end
directory and then you're going to want
to copy this environment variable
example file um and create a newm file
using your actual secrets so Lang graph
API key API URL that's going to be the
API URL that was Genera your deployment
Lan chain API key you do need this um in
order to connect to that deployment and
then the next public Lan graph graph ID
this is going to be the name of the
graph that you defined in your lr. Json
so in our case it's going to be stock
broker once you've defined all those
fields you can run yarn Dev um inside of
the front end directory and spin up your
uh web server so we can do that right
now see I I open up my terminal I want
to navigate into the front end directory
and then I can run yarn Dev it's going
to spit up a new deployment or a new web
server sorry at locost 3000 I can open
that up and then we'll see our UI is
loaded uh we pre-loaded in some
questions like what are some facts about
Google how much revenue did Apple make
last year and so on um but we can just
submit a question like how much revenue
did Apple make last year this is going
to call some tools so we see it called
the income statements tool passing in
the arguments of Apple's ticker um the
period of time in which to fetch the
income statement and then the limit and
then finally it generated a response
saying Apple made $383 billion Revenue
last year we can also click show result
here and this shows us the result of the
tool in this case it's the result from
the financial data sets API that was uh
invoked by our tool and this is how our
LM was able to generate that context now
if we want to say um purchase some Apple
stock we're going to ask it what the
current price is and then say purchase
and um since our graph will be
interrupted we'll see a similar UI to
what we saw saw in langra studio
allowing us to say confirm or deny so
for purchasing I've created a new
session here and we can send a message
like let's buy four shares of Apple for
the current price we'll hit submit and
it should call some tools see it call
the price snapshot tool um which got the
current price of Apple passing in
Apple's ticker and then it called the
purchase stock Tool uh passing in
Apple's ticker the company name the
quantity um for and then the max
purchase price uh since our graph was
interrupted we get this message here
saying graph interrupted the next node
is the execute purchase node and then
also our input is disabled while our
graph is interrupted so if we want to
confirm we can say confirm purchase and
then update State this is going to make
an update State API call to our Lang
graph production deployment updating the
states so that the purchase confirm
field is true for this uh thread and
then once this is done we going to
continue and this is also similar to the
ux you saw in the land graph Studio
where you would continue and it
continues from where it left off in the
graph so we see state was updated and
when once we continue it should purchase
the stock for us so we say continue and
then successfully purchase four shares
of Apple at $220 a share so this worked
exactly as we intended um and obviously
in production you're not going to want
to have a simple checkbox the user can
check it might want to be like I said
earlier some sort of two-factor
authentication this is how you'd
Implement a full stack L graph and
nextjs app uh deploy it to L graph cloud
in production and then hit your
production API uh using a nextjs front
end like this we can interact with our
production server you using a chat
interface um I hope you guys enjoyed
this video and know some more about
human Loop applications and Lane graph
and I'm excited to see what everyone's
builds
Voir Plus de Vidéos Connexes
DifyでStable Diffusion3で連続で画像を作るエージェントを作成
AI/ML based Card Payment Fraud Detection on AWS using replicated data from mainframe
WHAT IS FORM 183/FAQ 11/USMLE/ECFMG APPLICATION PROCESS#IMGs
Building a Generative UI App With LangChain Python
Backlogに入ってまず何するの?はじめての課題管理!
Next.js 14 Tutorial - 3 - Project Structure
5.0 / 5 (0 votes)