This notebook outlines how to use the ADS4GPTs Tools and Toolkit in LangChain directly. In your LangGraph application though you will most likely use our prebuilt LangGraph agents.
# Install ADS4GPTs Package# Install the ADS4GPTs package using pip!pip install ads4gpts-langchain
Set up the environment variables for API authentication (Obtain API Key).
Copy
Ask AI
# Setup Environment Variables# Prompt the user to enter their ADS4GPTs API key securelyif not os.environ.get("ADS4GPTS_API_KEY"): os.environ["ADS4GPTS_API_KEY"] = getpass("Enter your ADS4GPTS API key: ")
Import the necessary libraries, including ADS4GPTs tools and toolkit.Initialize the ADS4GPTs tools such as Ads4gptsInlineSponsoredResponseTool. We are going to work with one tool because the process is the same for every other tool we provide.
Initialize the Ads4gptsToolkit with the required parameters.
Copy
Ask AI
# Toolkit Initialization# Initialize the Ads4gptsToolkit with the required parameterstoolkit = Ads4gptsToolkit( ads4gpts_api_key=os.environ["ADS4GPTS_API_KEY"],)# Retrieve tools from the toolkittools = toolkit.get_tools()# Print the initialized toolsfor tool in tools: print(f"Initialized tool: {tool.__class__.__name__}")
Run the ADS4GPTs tools with sample inputs and display the results.
Copy
Ask AI
# Run ADS4GPTs Tools# Sample input data for the toolssample_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 Ads4gptsInlineSponsoredResponseToolinline_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
Ask AI
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<->'}
Run the ADS4GPTs tools asynchronously with sample inputs and display the results.
Copy
Ask AI
import asyncio# Define an async function to run the tools asynchronouslyasync 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
Ask AI
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<->'}
# Sample input data for the toolssample_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 resulttool = tools[0]result = tool._run(**sample_input)print(f"Result from {tool.__class__.__name__}:", result)# Define an async function to run the tools asynchronouslyasync def run_toolkit_tools_async(): result = await tool._arun(**sample_input) print(f"Async result from {tool.__class__.__name__}:", result)# Execute the async functionawait run_toolkit_tools_async()
Copy
Ask AI
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<->'}
if not os.environ.get("OPENAI_API_KEY"): os.environ["OPENAI_API_KEY"] = getpass("Enter your OPENAI_API_KEY API key: ")
Copy
Ask AI
import osfrom langchain_openai import ChatOpenAIopenai_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
Ask AI
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}}