Skip to content

Commit 0a0b665

Browse files
committed
code fixes
1 parent 89dba9f commit 0a0b665

3 files changed

Lines changed: 136 additions & 88 deletions

File tree

agent-framework/user-guide/agents/agent-types/openai-assistants-agent.md

Lines changed: 35 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -249,46 +249,59 @@ Enable your assistant to search through uploaded documents:
249249
```python
250250
from agent_framework import HostedFileSearchTool, HostedVectorStoreContent
251251

252-
async def file_search_example():
253-
client = OpenAIAssistantsClient()
254-
255-
# Create a vector store with documents
252+
async def create_vector_store(client: OpenAIAssistantsClient) -> tuple[str, HostedVectorStoreContent]:
253+
"""Create a vector store with sample documents."""
256254
file = await client.client.files.create(
257-
file=("knowledge.txt", b"The weather today is sunny with a high of 75F."),
255+
file=("todays_weather.txt", b"The weather today is sunny with a high of 75F."),
258256
purpose="user_data"
259257
)
260258
vector_store = await client.client.vector_stores.create(
261259
name="knowledge_base",
262260
expires_after={"anchor": "last_active_at", "days": 1},
263261
)
264-
await client.client.vector_stores.files.create_and_poll(
262+
result = await client.client.vector_stores.files.create_and_poll(
265263
vector_store_id=vector_store.id,
266264
file_id=file.id
267265
)
266+
if result.last_error is not None:
267+
raise Exception(f"Vector store file processing failed with status: {result.last_error.message}")
268268

269-
try:
270-
async with client.create_agent(
271-
name="KnowledgeBot",
272-
instructions="You are a helpful assistant that searches files in a knowledge base.",
273-
tools=HostedFileSearchTool(
274-
vector_stores=[HostedVectorStoreContent(vector_store_id=vector_store.id)]
275-
),
276-
) as agent:
277-
result = await agent.run("What does the document say about weather?")
278-
print(result.text)
279-
finally:
280-
# Cleanup
281-
await client.client.vector_stores.delete(vector_store.id)
282-
await client.client.files.delete(file.id)
269+
return file.id, HostedVectorStoreContent(vector_store_id=vector_store.id)
270+
271+
async def delete_vector_store(client: OpenAIAssistantsClient, file_id: str, vector_store_id: str) -> None:
272+
"""Delete the vector store after using it."""
273+
await client.client.vector_stores.delete(vector_store_id=vector_store_id)
274+
await client.client.files.delete(file_id=file_id)
275+
276+
async def file_search_example():
277+
print("=== OpenAI Assistants Client Agent with File Search Example ===\n")
278+
279+
client = OpenAIAssistantsClient()
280+
async with ChatAgent(
281+
chat_client=client,
282+
instructions="You are a helpful assistant that searches files in a knowledge base.",
283+
tools=HostedFileSearchTool(),
284+
) as agent:
285+
query = "What is the weather today? Do a file search to find the answer."
286+
file_id, vector_store = await create_vector_store(client)
287+
288+
print(f"User: {query}")
289+
print("Agent: ", end="", flush=True)
290+
async for chunk in agent.run_stream(
291+
query, tool_resources={"file_search": {"vector_store_ids": [vector_store.vector_store_id]}}
292+
):
293+
if chunk.text:
294+
print(chunk.text, end="", flush=True)
295+
print() # New line after streaming
296+
297+
await delete_vector_store(client, file_id, vector_store.vector_store_id)
283298
```
284299

285300
### Thread Management
286301

287302
Maintain conversation context across multiple interactions:
288303

289304
```python
290-
from agent_framework import AgentThread
291-
292305
async def thread_example():
293306
async with OpenAIAssistantsClient().create_agent(
294307
name="Assistant",

agent-framework/user-guide/agents/agent-types/openai-chat-completion-agent.md

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -206,27 +206,26 @@ async def local_mcp_example():
206206
Maintain conversation context across multiple interactions:
207207

208208
```python
209-
from agent_framework import AgentThread
210-
211209
async def thread_example():
212-
async with OpenAIChatClient().create_agent(
213-
name="Assistant",
210+
agent = OpenAIChatClient().create_agent(
211+
name="Agent",
214212
instructions="You are a helpful assistant.",
215-
) as agent:
216-
# Create a persistent thread for conversation context
217-
thread = agent.get_new_thread()
218-
219-
# First interaction
220-
first_query = "My name is Alice"
221-
print(f"User: {first_query}")
222-
first_result = await agent.run(first_query, thread=thread)
223-
print(f"Agent: {first_result.text}")
224-
225-
# Second interaction - agent remembers the context
226-
second_query = "What's my name?"
227-
print(f"User: {second_query}")
228-
second_result = await agent.run(second_query, thread=thread)
229-
print(f"Agent: {second_result.text}") # Should remember "Alice"
213+
)
214+
215+
# Create a persistent thread for conversation context
216+
thread = agent.get_new_thread()
217+
218+
# First interaction
219+
first_query = "My name is Alice"
220+
print(f"User: {first_query}")
221+
first_result = await agent.run(first_query, thread=thread)
222+
print(f"Agent: {first_result.text}")
223+
224+
# Second interaction - agent remembers the context
225+
second_query = "What's my name?"
226+
print(f"User: {second_query}")
227+
second_result = await agent.run(second_query, thread=thread)
228+
print(f"Agent: {second_result.text}") # Should remember "Alice"
230229
```
231230

232231
### Streaming Responses
@@ -239,8 +238,8 @@ async def streaming_example():
239238
name="StoryTeller",
240239
instructions="You are a creative storyteller.",
241240
)
242-
243-
print("Assistant: ", end="", flush=True)
241+
242+
print("Agent: ", end="", flush=True)
244243
async for chunk in agent.run_stream("Tell me a short story about AI."):
245244
if chunk.text:
246245
print(chunk.text, end="", flush=True)

agent-framework/user-guide/agents/agent-types/openai-responses-agent.md

Lines changed: 81 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ Import the required classes from the Agent Framework:
9797

9898
```python
9999
import asyncio
100+
from agent_framework import ChatAgent
100101
from agent_framework.openai import OpenAIResponsesClient
101102
```
102103

@@ -147,7 +148,7 @@ async def streaming_example():
147148
instructions="You are a creative storyteller.",
148149
)
149150

150-
print("Assistant: ", end="", flush=True)
151+
print("Agent: ", end="", flush=True)
151152
async for chunk in agent.run_stream("Tell me a short story about AI."):
152153
if chunk.text:
153154
print(chunk.text, end="", flush=True)
@@ -172,7 +173,7 @@ async def reasoning_example():
172173
reasoning={"effort": "high", "summary": "detailed"},
173174
)
174175

175-
print("Assistant: ", end="", flush=True)
176+
print("Agent: ", end="", flush=True)
176177
async for chunk in agent.run_stream("Solve: 3x + 11 = 14"):
177178
if chunk.contents:
178179
for content in chunk.contents:
@@ -270,68 +271,89 @@ async def code_interpreter_example():
270271
For data analysis tasks, you can upload files and analyze them with code:
271272

272273
```python
274+
import os
273275
import tempfile
276+
from agent_framework import HostedCodeInterpreterTool
277+
from openai import AsyncOpenAI
274278

275279
async def code_interpreter_with_files_example():
276-
client = OpenAIResponsesClient()
280+
print("=== OpenAI Code Interpreter with File Upload ===")
281+
282+
# Create the OpenAI client for file operations
283+
openai_client = AsyncOpenAI()
277284

278285
# Create sample CSV data
279286
csv_data = """name,department,salary,years_experience
280287
Alice Johnson,Engineering,95000,5
281288
Bob Smith,Sales,75000,3
282289
Carol Williams,Engineering,105000,8
290+
David Brown,Marketing,68000,2
291+
Emma Davis,Sales,82000,4
292+
Frank Wilson,Engineering,88000,6
283293
"""
284294

285-
# Upload file for analysis
295+
# Create temporary CSV file
286296
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as temp_file:
287297
temp_file.write(csv_data)
288298
temp_file_path = temp_file.name
289299

300+
# Upload file to OpenAI
301+
print("Uploading file to OpenAI...")
290302
with open(temp_file_path, "rb") as file:
291-
uploaded_file = await client.client.files.create(
303+
uploaded_file = await openai_client.files.create(
292304
file=file,
293-
purpose="assistants",
305+
purpose="assistants", # Required for code interpreter
294306
)
295307

296-
agent = client.create_agent(
297-
name="DataAnalyst",
298-
instructions="You are a data analyst that can write and execute Python code.",
299-
tools=HostedCodeInterpreterTool(file_ids=[uploaded_file.id]),
308+
print(f"File uploaded with ID: {uploaded_file.id}")
309+
310+
# Create agent using OpenAI Responses client
311+
agent = ChatAgent(
312+
chat_client=OpenAIResponsesClient(),
313+
instructions="You are a helpful assistant that can analyze data files using Python code.",
314+
tools=HostedCodeInterpreterTool(inputs=[{"file_id": uploaded_file.id}]),
300315
)
301316

302-
result = await agent.run("Analyze the salary data and create a summary by department.")
303-
print(result.text)
317+
# Test the code interpreter with the uploaded file
318+
query = "Analyze the employee data in the uploaded CSV file. Calculate average salary by department."
319+
print(f"User: {query}")
320+
result = await agent.run(query)
321+
print(f"Agent: {result.text}")
304322

305-
# Cleanup
306-
await client.client.files.delete(uploaded_file.id)
323+
# Clean up: delete the uploaded file
324+
await openai_client.files.delete(uploaded_file.id)
325+
print(f"Cleaned up uploaded file: {uploaded_file.id}")
326+
327+
# Clean up temporary local file
328+
os.unlink(temp_file_path)
329+
print(f"Cleaned up temporary file: {temp_file_path}")
307330
```
308331

309332
### Thread Management
310333

311334
Maintain conversation context across multiple interactions:
312335

313336
```python
314-
from agent_framework import AgentThread
315-
316337
async def thread_example():
317-
async with OpenAIResponsesClient().create_agent(
318-
name="Assistant",
338+
agent = OpenAIResponsesClient().create_agent(
339+
name="Agent",
319340
instructions="You are a helpful assistant.",
320-
) as agent:
321-
# Create a persistent thread for conversation context
322-
thread = agent.get_new_thread()
323-
324-
# First interaction
325-
first_query = "My name is Alice"
326-
print(f"User: {first_query}")
327-
first_result = await agent.run(first_query, thread=thread)
328-
print(f"Agent: {first_result.text}")
329-
330-
# Second interaction - agent remembers the context
331-
second_query = "What's my name?"
332-
print(f"User: {second_query}")
333-
second_result = await agent.run(second_query, thread=thread)
334-
print(f"Agent: {second_result.text}") # Should remember "Alice"
341+
)
342+
343+
# Create a persistent thread for conversation context
344+
thread = agent.get_new_thread()
345+
346+
# First interaction
347+
first_query = "My name is Alice"
348+
print(f"User: {first_query}")
349+
first_result = await agent.run(first_query, thread=thread)
350+
print(f"Agent: {first_result.text}")
351+
352+
# Second interaction - agent remembers the context
353+
second_query = "What's my name?"
354+
print(f"User: {second_query}")
355+
second_result = await agent.run(second_query, thread=thread)
356+
print(f"Agent: {second_result.text}") # Should remember "Alice"
335357
```
336358

337359
### File Search
@@ -344,30 +366,44 @@ from agent_framework import HostedFileSearchTool, HostedVectorStoreContent
344366
async def file_search_example():
345367
client = OpenAIResponsesClient()
346368

347-
# Create a vector store with documents
369+
# Create a file with sample content
348370
file = await client.client.files.create(
349-
file=("knowledge.txt", b"The weather today is sunny with a high of 75F."),
371+
file=("todays_weather.txt", b"The weather today is sunny with a high of 75F."),
350372
purpose="user_data"
351373
)
374+
375+
# Create a vector store for document storage
352376
vector_store = await client.client.vector_stores.create(
353377
name="knowledge_base",
354378
expires_after={"anchor": "last_active_at", "days": 1},
355379
)
356-
await client.client.vector_stores.files.create_and_poll(
380+
381+
# Add file to vector store and wait for processing
382+
result = await client.client.vector_stores.files.create_and_poll(
357383
vector_store_id=vector_store.id,
358384
file_id=file.id
359385
)
360-
361-
agent = client.create_agent(
362-
name="KnowledgeBot",
363-
instructions="You are a helpful assistant that can search through documents.",
364-
tools=HostedFileSearchTool(
365-
vector_stores=[HostedVectorStoreContent(vector_store_id=vector_store.id)]
366-
),
386+
387+
# Check if processing was successful
388+
if result.last_error is not None:
389+
raise Exception(f"Vector store file processing failed with status: {result.last_error.message}")
390+
391+
# Create vector store content reference
392+
vector_store_content = HostedVectorStoreContent(vector_store_id=vector_store.id)
393+
394+
# Create agent with file search capability
395+
agent = ChatAgent(
396+
chat_client=client,
397+
instructions="You are a helpful assistant that can search through files to find information.",
398+
tools=[HostedFileSearchTool(inputs=vector_store_content)],
367399
)
368400

369-
result = await agent.run("What does the document say about weather?")
370-
print(result.text)
401+
# Test the file search
402+
message = "What is the weather today? Do a file search to find the answer."
403+
print(f"User: {message}")
404+
405+
response = await agent.run(message)
406+
print(f"Agent: {response}")
371407

372408
# Cleanup
373409
await client.client.vector_stores.delete(vector_store.id)

0 commit comments

Comments
 (0)