Introduction
The Advanced Agent API can stream responses. This allows you to process data incrementally as it becomes available, rather than waiting for the full payload. This tutorial section describes how to make an API call enabling the stream response in Python.Prerequisites and Requirements
To reproduce this tutorial, you need:- At least Python 3.10.1 installed on your machine.
- A valid API KEY.
advanced-agent-stream-response/
. At the end of this step, the folder will have the following structure:
advanced-agent-stream-response/
Copy
Ask AI
advanced-agent-stream-response/
├── advanced-agent-stream-response.py
└── venv/
advanced-agent-stream-response.py
is the Python file that contains the coding logic.venv/
contains the virtual environment.
Copy
Ask AI
pip install requests sseclient-py
Manage The Stream Response With the Advanced Agent API
To manage the stream response with the Advanced Agent API, write the following code in theadvanced-agent-stream-response.py
file:
advanced-agent-stream-response.py
Copy
Ask AI
import json
import requests
import sseclient
# Insert the base URL for the API endpoint
BASE_URL = "https://api.you.com"
# Set your API key
API_KEY = "your-api-key"
# Insert the input query for the agent
query = "your query"
# Construct the full URL
url = f"{BASE_URL}/v1/agents/runs"
# Define the headers for the HTTP request
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
# Define the payload of the request
payload = {
"agent": "advanced", # Set the agent to "advanced"
# The user's input query
"input": query,
# Call the research and compute tools
"tools": [
{
"type": "research",
"search_effort": "medium",
"report_verbosity": "medium",
},
{
"type": "compute",
},
],
# Controls the verbosity of the agent
"verbosity": "medium",
"store": False,
# Enable streaming response
"stream": True,
}
# Send the POST request
response = requests.post(url, headers=headers, json=payload, stream=True)
# Initialize the SSE client with the response object to handle the event stream
client = sseclient.SSEClient(response)
# Initialize variables to store the incoming data
response_deltas = [] # A list to hold each text chunk (delta) of the response
search_results = None # A variable to store the final search results
# Iterate over the events received from the server
for event in client.events():
# Check for the event that contains the full search results
if event.event == "response.output_content.full":
event_data = json.loads(event.data)
# Ensure the content type is web search results before storing
if event_data["response"]["type"] == "Web Search.results":
search_results = event_data["response"]["full"]
# Check for the event that contains a text chunk (delta) of the main response
elif event.event == "response.output_text.delta":
event_data = json.loads(event.data)
response_delta = event_data["response"]["delta"]
response_deltas.append(response_delta)
# Stream the response delta to the console in real-time
print(response_delta, end="")
# Print a separator for clarity
print("\n--------------------------------")
# Check if search results were found and format them for printing
if search_results:
print("### Search Results")
for i, result in enumerate(search_results, 1):
print(f"{i}. {result.get('title', 'No Title')}")
print(f" URL: {result.get('url', 'No URL')}")
else:
print("No search results found.")
# Join all the collected text deltas to form the complete response string
full_response = "".join(response_deltas)
WARNING:
Based on your specific query, the agent may take up to 5 minutes to stream the entire response.
Write a report about Obama
. When launching the advanced-agent-stream-response.py
file, the result will be similar to the following:
Copy
Ask AI
## Barack Obama: A Comprehensive Biographical and Political Report
> **Key Findings:**
> - Barack Obama’s life journey—from a multicultural upbringing to Harvard Law, community organizing, and the presidency—has profoundly shaped American politics and culture.
> - As president, he enacted landmark domestic reforms (notably the Affordable Care Act), steered the nation through economic crisis, and achieved major diplomatic breakthroughs.
> - Obama’s post-presidency is marked by global leadership development, award-winning media production, and continued advocacy for democracy and social justice.
> - His family’s public presence and his status as the first African American president have left an enduring legacy on American society and popular culture.
---
### Early Life and Education
Barack Hussein Obama II was born on August 4, 1961, in Honolulu, Hawaii, to Ann Dunham, an American from Kansas, and Barack Obama Sr., a Kenyan economist [[1]](https://www.obamalibrary.gov/obamas/president-barack-obama#:~:text=Barack%20Hussein%20Obama%20II,Sr.%2C%20and%20Stanley%20Ann). His early years were marked by a multicultural upbringing—living in Hawaii and Indonesia, attending local schools, and being exposed to diverse cultures and religions [[2]](https://www.abc-clio.com/product/A2983C/#:~:text=Barack%20Obama%20is%20the,by%20this%20compelling%20and). Obama returned to Hawaii at age 10, attending the prestigious Punahou School, where he grappled with issues of identity and race [[3]](https://buzztatler.com/young-barack-obama-formative-years-in-the-1960s-and-1970s/#:~:text=Back%20in%20Hawaii%2C%20Obama,of%20the%20few%20Black).
After high school, Obama attended Occidental College in Los Angeles before transferring to Columbia University in New York, graduating with a degree in political science in 1983 [[4]](https://www.obamalibrary.gov/obamas/president-barack-obama#:~:text=Obama%20first%20attended%20Occidental,in%20political%20science%20in). He later attended Harvard Law School, where he became the first African American president of the Harvard Law Review and graduated magna cum laude in 1991 [[5]](https://en.wikipedia.org/wiki/Barack_Obama#:~:text=He%20was%20selected%20as,journal%20in%20his%20second).
---
### Early Career: Community Organizer and Political Rise
#### Community Organizing in Chicago
Obama began his career as a community organizer on Chicago’s South Side, working with the Developing Communities Project to address issues like job training, affordable housing, and public transportation [[6]](https://www.chicagotribune.com/opinion/editorials/ct-edit-obama-presidential-center-community-benefits-20170926-story.html#:~:text=job%20training%20programs%2C%20the,to%20the%20Metra%20Electric). His approach emphasized grassroots empowerment, dialogue, and coalition-building [[7]](https://www.chicagotribune.com/opinion/editorials/ct-edit-obama-presidential-center-community-benefits-20170926-story.html#:~:text=Obama%20made%20his%20answer,everyone%20in%20a%20transparent).
#### Civil Rights Attorney and State Senate
After Harvard, Obama worked as a civil rights attorney and taught constitutional law at the University of Chicago. In 1996, he was elected to the Illinois State Senate, where he championed ethics reform, transparency, and coalition-building, earning a reputation as a pragmatic and strategic legislator [[8]](https://www.chicagotribune.com/2004/10/24/obama-for-the-us-senate/#:~:text=In%20his%20autobiography%2C%20Barack,here%20to%20become%20a).
#### U.S. Senate
Obama’s 2004 election to the U.S. Senate brought him national attention, especially after his keynote address at the Democratic National Convention. In the Senate, he sponsored significant legislation on ethics, consumer protection, and financial reform, and built a broad political network through grassroots and insider alliances [[9]](https://www.chicagotribune.com/news/ct-xpm-2004-11-03-0411030317-story.html#:~:text=Democrat%20Barack%20Obama%2C%20a,a%20historic%20and%20decisive).
---
### Presidential Campaigns and Electoral Success
#### 2008 Campaign
Obama’s 2008 campaign, built on themes of “hope” and “change,” leveraged digital organizing, grassroots mobilization, and a diverse voter coalition. He defeated Hillary Clinton in a historic primary and John McCain in the general election, winning 365 electoral votes and 53% of the popular vote [[10]](https://en.wikipedia.org/wiki/Barack_Obama_2008_presidential_campaign#:~:text=On%20November%204%2C%202008%2C,electoral%20votes%20to%20McCain%E2%80%93Palin%27s). His victory was propelled by strong support from young voters, African Americans, and Hispanics [[11]](https://en.wikipedia.org/wiki/Barack_Obama_2008_presidential_campaign#:~:text=In%20the%20general%20election%2C,crucial%20demographic%20victories%20for).
#### 2012 Campaign
Running on the slogan “Forward,” Obama’s 2012 campaign focused on economic recovery and protecting the middle class. He defeated Mitt Romney with 332 electoral votes and 51.1% of the popular vote, again relying on high minority and youth turnout and innovative data-driven strategies [[12]](https://en.wikipedia.org/wiki/Barack_Obama_2012_presidential_campaign#:~:text=Obama%20was%20re%2Delected%20on,votes%20and%20332%20electoral).
---
### Presidency (2009–2017): Major Achievements
#### Domestic Policy
- **Affordable Care Act (ACA):** Expanded health insurance to millions, banned denial for pre-existing conditions, and allowed young adults to stay on parents’ plans [[13]](https://www.congress.gov/bill/111th-congress/house-bill/3590#:~:text=111th%20Congress%20%282009%2D2010%29%3A%20Patient,tribes%2C%20and%20individuals%20who).
- **Economic Recovery:** The American Recovery and Reinvestment Act provided nearly $800 billion in stimulus, helping avert a deeper recession and supporting infrastructure, education, and job creation [[14]](https://www.congress.gov/crs_external_products/R/HTML/R40537.web.html#:~:text=President%20Barack%20Obama%20signed,17%2C%202009%2C%20as%20P.L.).
- **Financial Reform:** The Dodd-Frank Act overhauled financial regulation to prevent future crises [[15]](https://www.brookings.edu/research/president-barack-obamas-first-two-years-policy-accomplishments-political-difficulties/#:~:text=sweeping%20reform%20of%20financial).
- **Climate Policy:** Obama set ambitious emissions targets, launched the Clean Power Plan, raised fuel economy standards, and played a central role in the Paris Climate Agreement [[16]](https://www.brookings.edu/articles/the-united-states-and-president-obamas-climate-action-plan/#:~:text=The%20Climate%20Action%20Plan,carbon%20pollution%20from%20power).
- **Social Justice:** Repealed “Don’t Ask, Don’t Tell,” supported marriage equality, advanced criminal justice reform, and promoted evidence-based social policy [[17]](https://www.congress.gov/event/117th-congress/senate-event/LC73731/text#:~:text=Hate%20Crimes%20Prevention%20Act%2C,still%20live%20in%20a).
#### Foreign Policy
- **Iran Nuclear Deal:** Negotiated a multilateral agreement to limit Iran’s nuclear program in exchange for sanctions relief [[18]](https://scholarlycommons.law.case.edu/jil/vol48/iss1/4/#:~:text=This%20Article%20will%20examine,of%20International%20Law%20%3E).
- **Paris Climate Agreement:** Led global efforts to secure a landmark climate accord with nearly 200 nations [[19]](https://obamawhitehouse.archives.gov/the-press-office/2016/10/05/remarks-president-paris-agreement#:~:text=Rose%20Garden%20%2A%2APlease%20see,will%20not%20solve%20the).
- **Normalization with Cuba:** Restored diplomatic relations after decades of hostility [[20]](https://2009-2017-fpc.state.gov/251239.htm#:~:text=normalization%20of%20relations%20with).
- **Counter-ISIL Campaign:** Built an international coalition to degrade ISIL’s territorial control [[21]](https://2009-2017-fpc.state.gov/267078.htm#:~:text=ISIL%20has%20been%20degraded,in%20a%20number%20of).
- **Asia-Pacific Rebalance:** Strengthened alliances and managed complex relations with China and Russia [[22]](https://2009-2017-fpc.state.gov/267078.htm#:~:text=Most%20of%20our%20signature,in%20part%20on%20U.S.%2DChinese).
---
### Post-Presidency and Ongoing Influence
#### Obama Foundation
Obama’s post-presidency centers on the Obama Foundation, which develops global leaders, advances civic engagement, and champions racial equity. Signature initiatives include the Global Leaders Program, My Brother’s Keeper Alliance, and the forthcoming Obama Presidential Center in Chicago [[23]](https://www.obama.org/press-releases/the-obama-foundation-introduces-2025-2026-class-of-more-than-200-global-leaders/#:~:text=This%20year%E2%80%99s%20group%20of,Through%20the%20Foundation%E2%80%99s%20signature).
#### Media and Writing
With Michelle Obama, he founded Higher Ground Productions, producing award-winning documentaries and series for Netflix and Audible, such as “American Factory” and “Our Great National Parks.” His memoir, *A Promised Land*, became a bestseller and continues to shape public discourse [[24]](https://en.wikipedia.org/wiki/A_Promised_Land#:~:text=By%20November%2024%2C%202020%2C,sales%20of%20a%20presidential).
#### Advocacy and Public Engagement
Obama remains a leading voice on democracy, pluralism, and social justice, supporting redistricting reform, campaigning for Democratic candidates, and speaking out on global challenges [[25]](https://www.britannica.com/biography/Barack-Obama/Life-after-the-presidency#:~:text=Obama%20also%20indicated%20his,the%20abuses%20of%20Republican).
---
### Family Life and Cultural Legacy
#### The Obama Family
Barack and Michelle Obama, married since 1992, have two daughters, Malia and Sasha. The family prioritized privacy and normalcy during their White House years, with both daughters now pursuing their own careers and education [[26]](https://www.obamalibrary.gov/obamas/president-barack-obama#:~:text=Barack%20Obama%20and%20Michelle,to%20the%20nation%20regarding). Michelle’s candid reflections on marriage and parenting have resonated widely [[27]](https://insidefame.com/article/barack-obama-admits-to-digging-out-of-a-hole-with-michelle#:~:text=Michelle%20Obama%20has%20been,media%2C%20as%20reported%20by).
#### Cultural Significance
Obama’s election as the first African American president was a historic milestone, symbolizing progress in civil rights and inspiring millions [[28]](https://en.wikipedia.org/wiki/Barack_Obama#:~:text=he%20was%20the%20first%20African%20American). His presidency and family normalized the image of a Black first family, catalyzed cultural conversations, and influenced social movements like Black Lives Matter [[29]](https://news.harvard.edu/gazette/story/2016/10/impact-of-the-nations-first-black-president/#:~:text=Noting%20the%20black%20cultural,Matter%20movement%20during%20his). Obama’s embrace of popular culture, love of music, literature, and sports, and his relatable persona have made him a lasting figure in American and global culture [[30]](https://medium.com/sing-song-blog-log/the-art-of-change-exploring-pop-culture-under-the-obama-administration-8e62de0f96ff#:~:text=%22Obama%20was%20the%20first,of%20facilitator%22%20in%20popular).
---
### Summary Table: Key Milestones
| Period | Key Events & Achievements |
|-------------------|------------------------------------------------------------------------------------------|
| Early Life | Born in Hawaii (1961), lived in Indonesia, Punahou School, Columbia, Harvard Law |
| Early Career | Community organizer, civil rights attorney, Illinois State Senate |
| U.S. Senate | Elected 2004, sponsored major legislation, built national profile |
| Presidency | ACA, economic recovery, Dodd-Frank, Paris Agreement, Iran deal, social justice reforms |
| Post-Presidency | Obama Foundation, Higher Ground Productions, bestselling memoir, global advocacy |
| Family & Culture | Married to Michelle, daughters Malia and Sasha, first Black president, cultural icon |
---
## Conclusion
> **Key Takeaway:**
> Barack Obama’s life and career embody the transformative potential of American democracy. From his multicultural roots and community activism to his historic presidency and ongoing global influence, Obama has shaped the nation’s political, social, and cultural landscape. His legacy endures around the world.
---
### Search Results
1. Borrowing page from Obama’s past, activists seek slice of library pie
URL: https://www.chicagotribune.com/news/obama-center/ct-obama-library-community-benefits-met-20160823-story.html#:~:text=President%20Barack%20Obama%20began,on%20the%20Far%20South
2. Did Obama the community organizer settle for ‘Just trust us’?
URL: https://www.chicagotribune.com/opinion/editorials/ct-edit-obama-presidential-center-community-benefits-20170926-story.html#:~:text=in%20the%201980s%20was,training%20activists%20in%20church
<Content omitted for brevity>
302. The Status Report: Obama’s Commitment to Creating Opportunity | Brookings
URL: https://www.brookings.edu/articles/the-status-report-obamas-commitment-to-creating-opportunity/#:~:text=Arguably%20the%20most%20important,the%20emphasis%20on%20evidence%2Dbased