Overview
이 노트북은 LangChain에서 ADS4GPTs Tools와 Toolkit을 직접 사용하는 방법을 설명합니다. 하지만 LangGraph 애플리케이션에서는 사전 구축된 LangGraph agent를 사용하는 것이 더 일반적입니다.Setup
Install ADS4GPTs Package
pip을 사용하여 ADS4GPTs 패키지를 설치합니다.Copy
# Install ADS4GPTs Package
# Install the ADS4GPTs package using pip
!pip install ads4gpts-langchain
Copy
# Setup Environment Variables
# Prompt the user to enter their ADS4GPTs API key securely
if not os.environ.get("ADS4GPTS_API_KEY"):
os.environ["ADS4GPTS_API_KEY"] = getpass("Enter your ADS4GPTS API key: ")
Instantiation
ADS4GPTs tools와 toolkit을 포함한 필요한 라이브러리를 import합니다. Ads4gptsInlineSponsoredResponseTool과 같은 ADS4GPTs tools를 초기화합니다. 제공하는 다른 모든 tool에 대해서도 프로세스가 동일하므로 하나의 tool로 작업하겠습니다.Copy
# Import Required Libraries
import os
from getpass import getpass
from ads4gpts_langchain import Ads4gptsInlineSponsoredResponseTool, Ads4gptsToolkit
Copy
# Initialize ADS4GPTs Tools
# Initialize the Ads4gptsInlineSponsoredResponseTool
inline_sponsored_response_tool = Ads4gptsInlineSponsoredResponseTool(
ads4gpts_api_key=os.environ["ADS4GPTS_API_KEY"],
)
Toolkit Instantiation
필요한 매개변수로 Ads4gptsToolkit을 초기화합니다.Copy
# Toolkit Initialization
# Initialize the Ads4gptsToolkit with the required parameters
toolkit = Ads4gptsToolkit(
ads4gpts_api_key=os.environ["ADS4GPTS_API_KEY"],
)
# Retrieve tools from the toolkit
tools = toolkit.get_tools()
# Print the initialized tools
for tool in tools:
print(f"Initialized tool: {tool.__class__.__name__}")
Copy
Initialized tool: Ads4gptsInlineSponsoredResponseTool
Initialized tool: Ads4gptsSuggestedPromptTool
Invocation
샘플 입력으로 ADS4GPTs tools를 실행하고 결과를 표시합니다.Copy
# Run ADS4GPTs Tools
# Sample input data for the tools
sample_input = {
"id": "test_id",
"user_gender": "female",
"user_age": "25-34",
"user_persona": "test_persona",
"ad_recommendation": "test_recommendation",
"undesired_ads": "test_undesired_ads",
"context": "test_context",
"num_ads": 1,
"style": "neutral",
}
# Run Ads4gptsInlineSponsoredResponseTool
inline_sponsored_response_result = inline_sponsored_response_tool._run(
**sample_input, ad_format="INLINE_SPONSORED_RESPONSE"
)
print("Inline Sponsored Response Result:", inline_sponsored_response_result)
Copy
Inline Sponsored Response Result: {'ad_text': '<- Promoted Content ->\n\nLearn the sartorial ways and get your handmade tailored suit by the masters themselves with Bespoke Tailors. [Subscribe now](https://youtube.com/@bespoketailorsdubai?si=9iH587ujoWKkueFa)\n\n<->'}
Async Run ADS4GPTs Tools
샘플 입력으로 ADS4GPTs tools를 비동기적으로 실행하고 결과를 표시합니다.Copy
import asyncio
# Define an async function to run the tools asynchronously
async def run_ads4gpts_tools_async():
# Run Ads4gptsInlineSponsoredResponseTool asynchronously
inline_sponsored_response_result = await inline_sponsored_response_tool._arun(
**sample_input, ad_format="INLINE_SPONSORED_RESPONSE"
)
print("Async Inline Sponsored Response Result:", inline_sponsored_response_result)
Copy
Async Inline Sponsored Response Result: {'ad_text': '<- Promoted Content ->\n\nGet the best tailoring content from Jonathan Farley. Learn to tie 100 knots and more! [Subscribe now](https://www.youtube.com/channel/UCx5hk4LN3p02jcUt3j_cexQ)\n\n<->'}
Toolkit Invocation
Ads4gptsToolkit을 사용하여 tools를 가져오고 실행합니다.Copy
# Sample input data for the tools
sample_input = {
"id": "test_id",
"user_gender": "female",
"user_age": "25-34",
"user_persona": "test_persona",
"ad_recommendation": "test_recommendation",
"undesired_ads": "test_undesired_ads",
"context": "test_context",
"num_ads": 1,
"style": "neutral",
}
# Run one tool and print the result
tool = tools[0]
result = tool._run(**sample_input)
print(f"Result from {tool.__class__.__name__}:", result)
# Define an async function to run the tools asynchronously
async def run_toolkit_tools_async():
result = await tool._arun(**sample_input)
print(f"Async result from {tool.__class__.__name__}:", result)
# Execute the async function
await run_toolkit_tools_async()
Copy
Result from Ads4gptsInlineSponsoredResponseTool: {'ad_text': '<- Promoted Content ->\n\nLearn the sartorial ways and get your handmade tailored suit by the masters themselves with Bespoke Tailors. [Subscribe now](https://youtube.com/@bespoketailorsdubai?si=9iH587ujoWKkueFa)\n\n<->'}
Async result from Ads4gptsInlineSponsoredResponseTool: {'ad_text': '<- Promoted Content ->\n\nGet the best tailoring content from Jonathan Farley. Learn to tie 100 knots and more! [Subscribe now](https://www.youtube.com/channel/UCx5hk4LN3p02jcUt3j_cexQ)\n\n<->'}
Chaining
Copy
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass("Enter your OPENAI_API_KEY API key: ")
Copy
import os
from langchain_openai import ChatOpenAI
openai_model = ChatOpenAI(model="gpt-4o", openai_api_key=os.environ["OPENAI_API_KEY"])
model = openai_model.bind_tools(tools)
model_response = model.invoke(
"Get me an ad for clothing. I am a young man looking to go out with friends."
)
print("Tool call:", model_response)
Copy
Tool call: content='' additional_kwargs={'tool_calls': [{'id': 'call_XLR5UjF8JhylVHvrk9mTjhj8', 'function': {'arguments': '{"id":"unique_user_id_001","user_gender":"male","user_age":"18-24","ad_recommendation":"Stylish and trendy clothing suitable for young men going out with friends.","undesired_ads":"formal wear, women\'s clothing, children\'s clothing","context":"A young man looking for clothing to go out with friends","num_ads":1,"style":"youthful and trendy","ad_format":"INLINE_SPONSORED_RESPONSE"}', 'name': 'ads4gpts_inline_sponsored_response'}, 'type': 'function'}], 'refusal': None} response_metadata={'token_usage': {'completion_tokens': 106, 'prompt_tokens': 1070, 'total_tokens': 1176, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 1024}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_eb9dce56a8', 'finish_reason': 'tool_calls', 'logprobs': None} id='run-e3e64b4b-4505-4a71-bf02-a8d77bb68eee-0' tool_calls=[{'name': 'ads4gpts_inline_sponsored_response', 'args': {'id': 'unique_user_id_001', 'user_gender': 'male', 'user_age': '18-24', 'ad_recommendation': 'Stylish and trendy clothing suitable for young men going out with friends.', 'undesired_ads': "formal wear, women's clothing, children's clothing", 'context': 'A young man looking for clothing to go out with friends', 'num_ads': 1, 'style': 'youthful and trendy', 'ad_format': 'INLINE_SPONSORED_RESPONSE'}, 'id': 'call_XLR5UjF8JhylVHvrk9mTjhj8', 'type': 'tool_call'}] usage_metadata={'input_tokens': 1070, 'output_tokens': 106, 'total_tokens': 1176, 'input_token_details': {'audio': 0, 'cache_read': 1024}, 'output_token_details': {'audio': 0, 'reasoning': 0}}
API reference
ADS4GPTs와 tools에 대한 자세한 내용은 GitHub에서 확인할 수 있습니다.Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.