pythonadvanced
OpenAI Assistants API with File Search
Create a persistent AI assistant with file search capability using the Assistants API v2.
pythonPress ⌘/Ctrl + Shift + C to copy
from openai import OpenAI
from pathlib import Path
import time
client = OpenAI()
# Upload knowledge file
file = client.files.create(file=Path('knowledge.txt').open('rb'), purpose='assistants')
# Create vector store
vs = client.beta.vector_stores.create(name='My Knowledge')
client.beta.vector_stores.files.create(vector_store_id=vs.id, file_id=file.id)
# Create assistant
assistant = client.beta.assistants.create(
model='gpt-4o-mini',
name='Knowledge Assistant',
instructions='Answer questions using the provided files.',
tools=[{'type': 'file_search'}],
tool_resources={'file_search': {'vector_store_ids': [vs.id]}},
)
# Run a conversation
thread = client.beta.threads.create(messages=[{'role':'user','content':'What topics are covered?'}])
run = client.beta.threads.runs.create_and_poll(thread_id=thread.id, assistant_id=assistant.id)
messages = client.beta.threads.messages.list(thread_id=thread.id)
print(messages.data[0].content[0].text.value)Use Cases
- document Q&A
- persistent assistants
- knowledge management
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
#langchain#openai
typescriptintermediate
OpenAI Assistants API with Threads
Create persistent conversation threads with OpenAI Assistants API for stateful multi-turn interactions.
Best for: Customer support bots
#openai#assistants
pythonintermediate
Async OpenAI Client in Python
Use the AsyncOpenAI client with asyncio to run concurrent chat completions without blocking.
Best for: concurrent LLM calls
#openai#async
pythonadvanced
OpenAI Batch API for Cost Reduction
Submit large workloads via the OpenAI Batch API for 50% cost reduction with async processing.
Best for: batch inference
#openai#batch