AI LLM & Python
A practical guide to building LLM applications in Python: chat, structured output, tools, agents, multi-agent workflows, memory, embeddings, vector search, RAG, MCP, evaluation, and production controls. It compares the Python frameworks and vector stores introduced in the AI LLM overview, with examples to help you choose the simplest suitable design.
Start with Python code
Use ordinary functions for known steps. Add a framework when its state, routing, integrations, or tracing solve a real problem.
An agent uses tools
The model can request a function; your Python application validates, authorizes, and executes it.
RAG connects your data
Python prepares documents, retrieves permitted evidence, and passes relevant passages to a model.
Production needs boundaries
Typed data, least-privilege tools, human approval, evaluation, and observability belong in the design.
How Python fits into an LLM application
Python does not have to run the model itself. In a common application, Python sends a request to a hosted model API, a cloud model platform, or a local inference server, then validates and uses the response. The application owns the surrounding rules: identity, permissions, data access, state, limits, and error handling.
A useful request lifecycle
- Authenticate the caller and determine what data they may access.
- Validate the request and collect only the context needed for this task.
- Call a model directly or route through a framework/provider adapter.
- Validate structured output and authorize each requested tool action.
- Return a clear answer, record appropriately redacted telemetry, and handle errors explicitly.
Keep the boundaries clear
- Provider SDK: sends requests to a specific model service.
- Orchestration framework: organizes tools, state, routing, retries, or agent loops.
- Data layer: stores conversations, documents, permissions, and vector indexes.
- Application policy: decides who can do what; it must not be delegated to a prompt.
Start with one direct Python call
A direct provider call is a useful baseline before introducing an agent framework. This OpenAI Responses API example reads its model and credentials from the environment; other providers use their own SDKs or compatible integrations.
python -m venv .venv
source .venv/bin/activate
python -m pip install openai
# Configure OPENAI_API_KEY and OPENAI_MODEL outside the source code.
import os
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model=os.environ["OPENAI_MODEL"],
instructions="Answer clearly and state uncertainty when evidence is missing.",
input="Explain the difference between an LLM and an AI agent in two sentences.",
)
print(response.output_text)
Connect to a local OpenAI-compatible endpoint
Some local runtimes expose an OpenAI-style chat-completions endpoint. This pattern is useful only when the server implements that endpoint; it does not imply support for every OpenAI feature or request format.
import os
from openai import OpenAI
local_model = OpenAI(
base_url=os.environ["LOCAL_LLM_BASE_URL"],
api_key=os.environ["LOCAL_LLM_API_KEY"],
)
reply = local_model.chat.completions.create(
model=os.environ["LOCAL_LLM_MODEL"],
messages=[{"role": "user", "content": "Summarize this short note."}],
)
print(reply.choices[0].message.content)Match the Python integration to the model capability
“LLM” can refer to several model capabilities. Select the model and interface for the task, then verify the exact provider’s input format, limits, data terms, and supported features.
| Capability | Python application pattern | Important distinction |
|---|---|---|
| Instruct / chat | Send role-based messages or a prompt; return a generated response. | Conversation history is application state unless a provider session feature explicitly manages it. |
| Reasoning-oriented | Use the provider’s supported reasoning model and settings for planning or complex analysis. | Measure task accuracy, latency, and cost. A model label does not guarantee correctness. |
| Code-focused | Ask for explanation, generation, or a patch, then review and test the result. | Never run generated code inside a privileged application process; use an isolated, resource-limited environment if execution is required. |
| Multimodal | Use a model API that accepts the specific image, audio, or video representation needed. | Formats, size limits, privacy, and supported modalities vary by model and endpoint. |
| Embedding | Convert text or supported media to vectors, then index them for similarity search. | Embedding models create representations; they do not generate a grounded answer on their own. |
| Reranking | Re-score retrieved passages for a particular query before building the final context. | A reranker is a retrieval component, not a vector database or answer-generating model. |
| Fine-tuning | Adapt a model with curated examples when evaluations show that a stable behavior or task pattern needs improvement. | It is not a substitute for RAG when the answer depends on current or private facts; training data, cost, and model terms need review. |
Example: send text and an image to a vision-capable model
The image input shape below is for the OpenAI Responses API. Replace the illustrative URL with an image the server is allowed to access, or use the provider’s supported file-upload flow.
response = client.responses.create(
model=os.environ["VISION_MODEL"],
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "Describe the chart and its main trend."},
{
"type": "input_image",
"image_url": "https://example.com/chart.png",
},
],
}
],
)
print(response.output_text)
Audio and video use additional provider-specific tasks, codecs, and message formats. Check the target API before assuming that one chat request shape supports every modality.
Build single-turn and multi-turn chat
A chat assistant is often one model call plus a carefully managed message history. Keep instructions separate from user content, bound the history to the model’s context budget, and decide explicitly whether conversation state is temporary, stored by your application, or managed by a provider session.
history = []
def ask_assistant(user_text: str) -> str:
history.append({"role": "user", "content": user_text})
response = client.responses.create(
model=os.environ["OPENAI_MODEL"],
instructions="You are a concise support assistant. Do not invent account facts.",
input=history[-12:],
)
answer = response.output_text
history.append({"role": "assistant", "content": answer})
return answer
print(ask_assistant("How do I reset my password?"))
print(ask_assistant("Will that sign me out of my other devices?"))
Chat design checklist
- Set the assistant’s role and boundaries in stable instructions.
- Keep the user’s messages and retrieved documents distinguishable from trusted instructions.
- Summarize or trim old turns when needed; never exceed a context budget blindly.
- Stream partial output only when the UI can safely handle incomplete answers.
- Return an explicit error or retry path when the provider fails.
Structured responses
For data that another part of the application consumes, request a schema and validate it with Pydantic or a framework’s typed-output feature. Treat parsing success as shape validation—not as proof that the values are true or authorized.
Use deterministic Python workflows before adding autonomy
If the steps and branches are known, implement them as ordinary functions. An LLM can classify a request, extract typed fields, or draft text at a defined point; your Python code should still control the order of operations and decide which business actions are permitted.
def handle_request(principal, request):
intent = classify_request(request.text) # Validate the returned intent.
if intent == "knowledge_question":
passages = search_authorized_documents(principal, request.text)
return draft_answer_from_evidence(request.text, passages)
if intent == "order_status":
order = order_service.get_visible_to(principal, request.order_id)
return summarize_order_status(order)
raise ValueError(f"Unsupported intent: {intent}")
The service functions above are application-owned. Notice that the caller’s identity is passed to the data service; the model does not decide which records the caller may see. A known workflow is easier to test and audit than a free-running agent that tries to rediscover the same steps on every request.
Tools and function calling
A tool is a typed Python function exposed through a model or agent framework. The model proposes a name and arguments; the framework may validate a schema, but your application must still authenticate the caller, authorize the requested operation, validate business rules, and handle failures.
When a bounded agent loop helps
Use an agent when the next step genuinely depends on what the model observes—for example, choosing among a few read-only search tools and then asking a follow-up question. Set maximum turns, tool calls, elapsed time, token use, and spending. Use human approval before an irreversible or consequential action.
Treat memory as application data with a lifecycle
Short-term memory is usually the messages and state needed to finish the current conversation or workflow. Long-term memory is persisted data—perhaps user preferences, summaries, or indexed facts—and needs an explicit purpose, consent, access policy, retention period, and deletion path. A vector index is one possible retrieval mechanism, not a memory policy.
A small SQLite example for chat history
This demonstrates persistence only; production storage should also enforce tenant ownership, encryption, retention, and deletion rules.
import sqlite3
conversation_id = "server-generated-conversation-id"
turn_number = 1
messages = [
{"role": "user", "content": "What did I ask about earlier?"},
{"role": "assistant", "content": "You asked about the account security page."},
]
with sqlite3.connect("chat-history.db") as database:
database.execute(
"""
CREATE TABLE IF NOT EXISTS messages (
conversation_id TEXT NOT NULL,
turn_number INTEGER NOT NULL,
message_number INTEGER NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (conversation_id, turn_number, message_number)
)
"""
)
database.executemany(
"INSERT INTO messages VALUES (?, ?, ?, ?, ?)",
[
(conversation_id, turn_number, number, item["role"], item["content"])
for number, item in enumerate(messages)
],
)
rows = database.execute(
"""
SELECT role, content
FROM messages
WHERE conversation_id = ?
ORDER BY turn_number, message_number
""",
(conversation_id,),
).fetchall()
history = [{"role": role, "content": content} for role, content in rows]
Session state
Conversation turns, workflow checkpoints, and temporary tool results. Store only what the next step needs and set an expiry appropriate to the task.
Long-term memory
User-approved preferences or durable knowledge. Keep its source, owner, timestamp, and deletion path; do not silently turn every conversation into permanent memory.
def model_payload(case_reference: str, question: str) -> dict[str, str]:
"""Send only the fields this model task needs."""
return {
"case_reference": case_reference, # Pseudonymous, not guaranteed anonymous.
"question": question,
}Build RAG as a data pipeline, not just a vector query
Retrieval-Augmented Generation (RAG) retrieves external evidence at request time and provides it to the model. Correctness depends on the whole pipeline: parsing, permissions, chunking, embeddings, search, ranking, context construction, citations, and refreshes.
Parse and track sources
Extract clean text and metadata from files, websites, or databases. Record source, version, tenant, permissions, and freshness.
Keep useful boundaries
Split by document structure where possible. Chunk size, overlap, and metadata should be evaluated on representative questions, not copied from a demo.
Create and version vectors
Use an embedding model and keep query and document embeddings compatible. Changing models or dimensions usually requires re-indexing.
Search permitted evidence
Filter by authenticated tenant and access policy before returning results. Combine vector similarity with keyword search when exact terms matter.
Fit evidence to the task
Optionally rerank passages, remove duplicates, and ask the model to cite sources or state when the evidence is insufficient.
Refresh and evaluate
Re-index changed or deleted sources, preserve access rules, and test retrieval and citation quality as data and models change.
A compact Qdrant + OpenAI retrieval example
This example illustrates the data flow, including a tenant filter. Create or migrate collections during an ingestion/deployment step in a real system, rather than recreating them for each request. The tenant value below is illustrative; derive it from authenticated server-side identity.
Install the Qdrant client with pip install qdrant-client.
import os
from uuid import NAMESPACE_URL, uuid5
from openai import OpenAI
from qdrant_client import QdrantClient, models
llm = OpenAI()
store = QdrantClient(
url=os.environ["QDRANT_URL"],
api_key=os.getenv("QDRANT_API_KEY"),
)
collection = "knowledge"
tenant_id = "tenant-42" # Replace with the authenticated tenant.
chunks = [
{
"id": "policy-v3-section-1",
"text": "Refund requests must be submitted within 30 days.",
"source": "refund-policy-v3",
"tenant_id": tenant_id,
}
]
document_vectors = llm.embeddings.create(
model=os.environ["EMBEDDING_MODEL"],
input=[item["text"] for item in chunks],
).data
if not store.collection_exists(collection):
store.create_collection(
collection_name=collection,
vectors_config=models.VectorParams(
size=len(document_vectors[0].embedding),
distance=models.Distance.COSINE,
),
)
store.upsert(
collection_name=collection,
wait=True,
points=[
models.PointStruct(
id=str(uuid5(NAMESPACE_URL, item["id"])),
vector=vector.embedding,
payload=item,
)
for item, vector in zip(chunks, document_vectors, strict=True)
],
)
question = "How long do I have to request a refund?"
query_vector = llm.embeddings.create(
model=os.environ["EMBEDDING_MODEL"],
input=question,
).data[0].embedding
matches = store.query_points(
collection_name=collection,
query=query_vector,
query_filter=models.Filter(
must=[
models.FieldCondition(
key="tenant_id",
match=models.MatchValue(value=tenant_id),
)
]
),
with_payload=True,
limit=5,
).points
evidence = "\n\n".join(
f"Source: {hit.payload['source']}\n{hit.payload['text']}"
for hit in matches
if hit.payload and "text" in hit.payload
)
answer = llm.responses.create(
model=os.environ["OPENAI_MODEL"],
instructions="Answer only from the supplied evidence. Cite its source. If it is insufficient, say so.",
input=f"Question: {question}\n\nEvidence:\n{evidence}",
)
print(answer.output_text)
Optional reranking step
A cross-encoder scores each candidate against the query. It is slower than vector retrieval, so use it to rerank a smaller candidate set rather than the whole corpus.
Install the library with pip install sentence-transformers; select a model that fits your language, license, latency, and deployment requirements.
from sentence_transformers import CrossEncoder
query = "How long do I have to request a refund?"
candidates = [
"Refund requests must be submitted within 30 days.",
"Standard delivery usually takes three to five business days.",
]
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
scores = reranker.predict([(query, text) for text in candidates])
ranked = sorted(
zip(scores, candidates, strict=True),
key=lambda item: item[0],
reverse=True,
)
print(ranked[:3])
Choose a Python vector store for the workload
A vector store saves embeddings and metadata, then retrieves nearby vectors. Some products also provide filtering, hybrid search, replication, access controls, or managed operations. There is no single best or most-used option for every team; benchmark the actual corpus, query mix, filters, scale, and operating model.
| Option | Common Python package | Typical fit | Check before choosing |
|---|---|---|---|
| Pinecone | pinecone |
Managed vector search when a hosted service is preferred. | Cost, region, filters, data handling, and portability. |
| Qdrant | qdrant-client |
Open-source or managed vector search with payload filtering. | Self-hosting effort, managed deployment, and index settings. |
| Weaviate | weaviate-client |
Vector search with metadata and hybrid retrieval capabilities. | Operations, integration model, and fit with the existing stack. |
| Milvus / Zilliz | pymilvus |
Large-scale vector workloads and managed Milvus-compatible deployments. | Infrastructure and operational complexity for the scale required. |
| Chroma | chromadb |
Developer-friendly local, persistent, or hosted vector workflows. | Persistence, access control, and production deployment requirements. |
| PostgreSQL + pgvector | psycopg and pgvector |
Teams already using Postgres that want vector search beside relational data. | Index type, filtering, query load, and operational needs; benchmark before adding another database. |
Try a local Chroma collection
Chroma can embed text for a quick local experiment. Its in-memory client loses data when the process exits; use persistent or server mode when the index must survive restarts.
Install the Python client with pip install chromadb.
import chromadb
client = chromadb.Client()
collection = client.get_or_create_collection(name="support-docs")
collection.upsert(
ids=["reset-guide-v1", "shipping-guide-v1"],
documents=[
"Reset a password from the account security page.",
"Standard shipping usually takes three to five business days.",
],
metadatas=[
{"tenant_id": "tenant-42", "source": "reset-guide"},
{"tenant_id": "tenant-42", "source": "shipping-guide"},
],
)
results = collection.query(
query_texts=["How do I change my password?"],
n_results=3,
where={"tenant_id": "tenant-42"},
)
print(results["documents"])
For a small corpus, Postgres full-text search or an in-process index may be enough. A dedicated vector database is an architectural decision, not a prerequisite for every LLM project.
Choose a Python framework by the control you need
Frameworks can reduce integration work, but they do not remove provider differences or application responsibilities. Start with a direct SDK or deterministic workflow. Add graph state, typed tools, handoffs, data connectors, or tracing when that capability is worth its added concepts and dependency surface.
| Framework | Python package starting point | Good starting fit | Trade-off to consider |
|---|---|---|---|
| LangGraph | langgraph plus the chosen provider integration |
Stateful, multi-step workflows with explicit graph control, persistence, or human review. | Flexible low-level orchestration introduces more concepts and implementation responsibility. |
| CrewAI | crewai |
Role-based agent teams and Flows that organize state and execution steps. | Vague roles or delegation make runs hard to debug; keep tasks and stop conditions explicit. |
| OpenAI Agents SDK | openai-agents |
A lightweight runtime for tools, handoffs, guardrails, sessions, approvals, and tracing. | Review model/provider compatibility and OpenAI-specific behavior for the target deployment. |
| Pydantic AI | pydantic-ai |
Typed inputs, dependency injection, tools, and validated structured outputs in conventional Python services. | Types validate shapes, not truth, authorization, or business rules. |
| AutoGen (Microsoft) | autogen-agentchat and a provider extension such as autogen-ext[openai] |
AgentChat conversations, tool use, and multi-agent experiments. | Multi-agent coordination can add latency, cost, and less predictable behavior. For new Microsoft-centric projects, also evaluate Microsoft Agent Framework. |
Ranked-framework examples
The order below follows the five-framework shortlist in the AI LLM overview. It is a practical comparison, not a universal ranking by downloads or production usage.
LangGraph · explicit state and graph transitions
Start with langgraph and the provider integration you use. Nodes represent clear steps and conditional edges control routing. A model call can live in one node while deterministic checks remain ordinary Python code.
from typing import TypedDict
from langchain.chat_models import init_chat_model
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
question: str
answer: str
model = init_chat_model("openai:gpt-4.1-mini")
def answer_question(state: State) -> dict[str, str]:
result = model.invoke(state["question"])
return {"answer": str(result.content)}
builder = StateGraph(State)
builder.add_node("answer", answer_question)
builder.add_edge(START, "answer")
builder.add_edge("answer", END)
app = builder.compile()
result = app.invoke({"question": "What is RAG?", "answer": ""})
print(result["answer"])CrewAI · roles, tasks, Crews, and Flows
Install crewai. A Crew assigns explicit tasks to agents. For a production application with known steps and state, CrewAI Flows can wrap one or more crews with ordered steps and routing.
from crewai import Agent, Crew, Process, Task
researcher = Agent(
role="Policy researcher",
goal="Find the relevant policy details and summarize them accurately.",
backstory="You work from approved internal policy documents.",
)
task = Task(
description="Summarize the policy for: {topic}",
expected_output="A short summary with the document title and section.",
agent=researcher,
)
crew = Crew(
agents=[researcher],
tasks=[task],
process=Process.sequential,
)
result = crew.kickoff(inputs={"topic": "refund eligibility"})
print(result.raw)OpenAI Agents SDK · tools and bounded handoffs
Install openai-agents. This example exposes a narrow read-only tool. The Python function is still responsible for safe lookup behavior; do not treat the tool description as authorization.
import asyncio
from agents import Agent, Runner
from agents.decorators import tool
OPENING_HOURS = {
"prague": "Monday to Friday, 9:00–17:00",
"brno": "Monday to Friday, 9:00–16:00",
}
@tool
def get_opening_hours(city: str) -> str:
"""Return public opening hours for a known branch."""
return OPENING_HOURS.get(city.lower(), "No branch was found.")
assistant = Agent(
name="Branch assistant",
instructions="Answer branch-hours questions. Use the tool for current hours.",
tools=[get_opening_hours],
)
async def main() -> None:
result = await Runner.run(assistant, "When is the Prague branch open?")
print(result.final_output)
asyncio.run(main())Pydantic AI · typed results and dependencies
Install pydantic-ai. Provider/model strings use a provider prefix. A typed output helps downstream Python code work with a validated shape; add domain checks for values that affect real decisions.
from pydantic import BaseModel
from pydantic_ai import Agent
class SupportAnswer(BaseModel):
answer: str
should_escalate: bool
assistant = Agent(
"openai:gpt-4.1-mini",
output_type=SupportAnswer,
instructions="Answer from supplied support information. Escalate uncertainty.",
)
result = assistant.run_sync(
"The policy excerpt says refunds are allowed within 30 days. "
"The customer purchased 10 days ago. Should this be escalated?"
)
print(result.output)AutoGen · agent conversation with a tool
Install autogen-agentchat and the required provider extension, such as autogen-ext[openai]. AgentChat can stream a tool-using assistant. Close model clients when the task completes, and keep each exposed function narrow and authorized.
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
async def get_service_status(service: str) -> str:
"""Return status from an allowlisted service catalog."""
known_services = {"search": "operational", "billing": "degraded"}
return known_services.get(service.lower(), "unknown service")
async def main() -> None:
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
agent = AssistantAgent(
name="status_agent",
model_client=model_client,
tools=[get_service_status],
system_message="Answer service-status questions using the tool.",
reflect_on_tool_use=True,
)
try:
await Console(agent.run_stream(task="Is billing operational?"))
finally:
await model_client.close()
asyncio.run(main())Multi-agent handoff · delegate only when roles are genuinely distinct
A handoff transfers control to a specialist. A manager-as-tools pattern is different: the manager retains control and calls specialists as tools. Choose one only when the separation improves measurable task quality.
import asyncio
from agents import Agent, Runner
billing_agent = Agent(
name="Billing specialist",
handoff_description="Handles questions about invoices and billing policies.",
instructions="Answer billing questions from the approved billing information.",
)
support_agent = Agent(
name="Support triage",
instructions="Route billing questions to the billing specialist.",
handoffs=[billing_agent],
)
async def main() -> None:
result = await Runner.run(
support_agent,
"Where can I find the billing date on my invoice?",
)
print(result.final_output)
asyncio.run(main())
More agents add latency, cost, coordination errors, and more policy boundaries. A multi-agent design is not automatically more capable than one agent with a few bounded tools.
Other useful Python frameworks and adjacent tools
These projects cover higher-level agent APIs, data-centric RAG, composable search pipelines, Microsoft integrations, and program optimization. They are complementary options, not a requirement to install together.
LangChain · common agent API and integrations
For this OpenAI example, install langchain and its provider integration, such as langchain-openai.
from langchain.agents import create_agent
def get_public_service_status(service: str) -> str:
"""Look up a service in a small public status catalog."""
return {"search": "operational", "billing": "degraded"}.get(
service.lower(),
"unknown service",
)
agent = create_agent(
model="openai:gpt-4.1-mini",
tools=[get_public_service_status],
system_prompt="Answer status questions using the available tool.",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What is the billing status?"}]}
)
print(result["messages"][-1].content)
LangChain offers model, prompt, and tool integrations; LangGraph is its explicit stateful orchestration layer. Review which layer you actually need.
LlamaIndex · document loading, indexing, and RAG
Install llama-index and the required model/embedding integration packages.
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
from llama_index.core import Settings
from llama_index.embeddings.openai import OpenAIEmbedding
Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")
documents = SimpleDirectoryReader("approved-documents").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine(similarity_top_k=5)
response = query_engine.query("What does the policy say about refunds?")
print(response)
LlamaIndex is useful when connectors, document ingestion, indexing, and retrieval are central. Apply access filters before retrieved content reaches the model.
Haystack · composable search and RAG pipelines
Install haystack-ai. This small example uses keyword retrieval; pipelines can also connect embedding, vector, hybrid, ranking, and generator components.
from haystack import Document
from haystack.components.retrievers import InMemoryBM25Retriever
from haystack.document_stores.in_memory import InMemoryDocumentStore
store = InMemoryDocumentStore()
store.write_documents(
[
Document(content="Refund requests are accepted within 30 days."),
Document(content="Standard delivery takes three to five business days."),
]
)
retriever = InMemoryBM25Retriever(document_store=store)
result = retriever.run(query="How long can I request a refund?")
for document in result["documents"]:
print(document.content)Microsoft Agent Framework · agents and workflows
Install agent-framework and azure-identity. The Foundry client below uses Azure CLI credentials rather than a key in source. Other model clients and provider integrations are available; configure the matching one for your environment.
import asyncio
import os
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
assistant = Agent(
client=FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
),
name="Policy assistant",
instructions="Answer briefly and state when the policy evidence is incomplete.",
)
async def main() -> None:
result = await assistant.run("What should a useful agent harness control?")
print(result)
asyncio.run(main())
Microsoft describes Agent Framework as the successor to AutoGen and Semantic Kernel, combining agent patterns with sessions, integrations, and explicit workflows. Check current migration guidance before starting a new Microsoft-centric project.
Semantic Kernel · plugins and model services in existing Python apps
Install semantic-kernel. For an existing Semantic Kernel application, a plugin exposes application functions to a model service. This Azure OpenAI chat example reads deployment settings from the environment.
import asyncio
import os
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents.chat_history import ChatHistory
async def main() -> None:
kernel = Kernel()
chat = AzureChatCompletion(
deployment_name=os.environ["AZURE_OPENAI_DEPLOYMENT"],
api_key=os.environ["AZURE_OPENAI_API_KEY"],
base_url=os.environ["AZURE_OPENAI_ENDPOINT"],
)
kernel.add_service(chat)
history = ChatHistory()
history.add_user_message("Explain the difference between a workflow and an agent.")
reply = await chat.get_chat_message_content(
chat_history=history,
kernel=kernel,
)
print(reply)
asyncio.run(main())DSPy · compose and optimize LLM programs
Install dspy. DSPy expresses a task as a typed signature and a program module; optimizers can then tune the program against representative examples and a measurable metric.
import dspy
dspy.configure(lm=dspy.LM("openai/gpt-5.4-nano"))
class ExtractIntent(dspy.Signature):
"""Extract the main intent from a support message."""
message: str = dspy.InputField()
intent: str = dspy.OutputField()
extract = dspy.Predict(ExtractIntent)
result = extract(message="I cannot sign in after changing my password.")
print(result.intent)
Optimization is only meaningful with representative training and validation examples, a stable metric, and checks against regressions or unsafe behavior.
Connect tools with MCP, skills, and agent-to-agent patterns
These concepts solve different integration problems. MCP standardizes how compatible clients connect to tools and data servers; a skill is a reusable procedure whose exact format depends on the product; A2A patterns support delegation between agent services. None of them replaces authentication, authorization, trust review, or observability.
Expose a narrow tool through the Python MCP SDK
Install the SDK with pip install mcp; add its CLI extra only if you need the development commands.
from mcp.server import MCPServer
server = MCPServer("approved-knowledge-tools")
@server.tool()
def lookup_public_faq(topic: str) -> str:
"""Look up an answer in the approved public FAQ catalog."""
approved_faq = {
"password": "Use the account security page to reset a password.",
"delivery": "Standard delivery usually takes three to five business days.",
}
return approved_faq.get(topic.lower(), "No matching FAQ entry was found.")
The MCP server should expose only capabilities its caller is allowed to use. For remote transport, authenticate clients, authorize each tool, validate outputs, and review the server’s dependencies and ownership.
Represent a reusable skill as a tested Python capability
A skill can be a documented procedure plus small, testable functions and an allowlisted tool set. The model may suggest a skill name, but application code should reject unapproved capabilities.
from collections.abc import Callable
def list_document_headings(document: str) -> list[str]:
"""Return Markdown section headings from an approved document."""
return [
line.removeprefix("#").strip()
for line in document.splitlines()
if line.startswith("#")
]
SKILLS: dict[str, Callable[[str], object]] = {
"list_document_headings": list_document_headings,
}
def run_skill(name: str, document: str, *, allowed: set[str]) -> object:
if name not in allowed:
raise PermissionError(f"Skill is not allowed: {name}")
try:
skill = SKILLS[name]
except KeyError as error:
raise ValueError(f"Unknown skill: {name}") from error
return skill(document)
Skills
Package repeatable instructions, Python functions, tests, and required tools for a specialist task. There is no single universal “skill” interchange format; keep permissions and behavior explicit.
MCP
A protocol for AI applications to discover and call compatible tools, resources, and prompts through MCP clients and servers. Review each server as a trusted integration, not as arbitrary model-provided code.
A2A
Agent-to-agent protocols and patterns enable cross-service discovery or delegation. Keep remote calls behind a typed Python adapter with explicit identity, timeouts, data-sharing rules, and an audit trail.
Keep A2A transport behind a typed Python boundary
A2A integrations are protocol- and provider-specific, so there is no single generic call shape that works for every remote agent. Keep that transport behind an application interface and enforce caller identity, deadlines, and data-sharing policy there.
from typing import Protocol
class ResearchAgentClient(Protocol):
async def research(
self,
topic: str,
*,
request_id: str,
deadline_seconds: int,
) -> str:
"""Delegate a bounded research task through the chosen A2A client."""
...
async def get_research_summary(
agent: ResearchAgentClient,
topic: str,
request_id: str,
) -> str:
return await agent.research(
topic,
request_id=request_id,
deadline_seconds=20,
)Make Python LLM systems reliable, safe, and measurable
A working demo shows that a model can produce an interesting response. A production system also needs controlled data access, bounded execution, meaningful tests, traceable failures, and a way to recover when a provider or tool is unavailable.
Security and privacy
- Keep API keys on the trusted server; use environment configuration or a secret manager, not browser code or source control.
- Treat user input, retrieved documents, webpages, and tool results as untrusted. Prompt injection can arrive indirectly.
- Enforce authorization in Python services and database filters before exposing records or executing tools.
- Give each tool least-privilege credentials; validate arguments and outputs independently of the prompt.
- Require human approval for consequential or irreversible actions such as payments, deletion, or external messages.
- Run generated code in a separate sandbox with strict resource, filesystem, and network limits.
- Redact sensitive data from traces and define retention and deletion policies for chat and memory.
Evaluation and observability
- Create a representative evaluation set before changing prompts, models, retrieval, or tools.
- Measure task success, factual grounding, citation quality, schema validity, tool selection, latency, and cost.
- Include malformed inputs, missing evidence, denied permissions, prompt-injection attempts, and provider failures.
- Trace model calls, retrieval, tool execution, retries, and approvals end to end.
- Version prompts, model IDs, tool schemas, embedding models, chunking, and retrieval settings.
- Use bounded timeouts, retries, rate limits, turn counts, token budgets, and spending limits.
Guardrails, human approval, and an agent harness
Guardrails combine validation, authorization, limits, and sometimes human review. A harness is the runtime that enforces those controls around an agent’s model calls and tools; a prompt alone cannot enforce them.
from decimal import Decimal
MAX_AUTOMATED_REFUND = Decimal("25.00")
def refund_decision(
amount: Decimal,
*,
approved_by_person: bool,
) -> str:
if amount <= Decimal("0"):
raise ValueError("Refund amount must be positive.")
if amount > MAX_AUTOMATED_REFUND and not approved_by_person:
return "needs_human_approval"
return "ready_for_authorized_service"
Test policy code independently of model quality
from decimal import Decimal
import pytest
def test_large_refund_waits_for_human_approval():
decision = refund_decision(
Decimal("80.00"),
approved_by_person=False,
)
assert decision == "needs_human_approval"
def test_non_positive_refund_is_rejected():
with pytest.raises(ValueError):
refund_decision(Decimal("0.00"), approved_by_person=False)
Keep deterministic permission and business-rule tests in ordinary unit tests. Evaluate model quality separately with a versioned set of realistic questions, expected evidence, schema checks, and review criteria; exact-string snapshots alone are brittle.
- Bound model turns, tool calls, elapsed time, retries, tokens, and spend.
- Persist workflow checkpoints when a task must survive restarts or approval waits.
- Make side-effecting tools idempotent where possible and record who approved each action.
- Keep the final business operation in a service that repeats validation and authorization.
A pragmatic implementation sequence
- Define one measurable task. Specify the desired output and the failures that are unacceptable.
- Build the simplest baseline. Use a direct model call or deterministic Python workflow before adding memory, RAG, or multiple agents.
- Evaluate representative cases. Include ordinary, difficult, ambiguous, and adversarial inputs before tuning the implementation.
- Add only the needed context and tools. Use retrieval for changing or private facts; expose narrow functions with explicit permissions.
- Bound and observe execution. Cap time, turns, tool calls, tokens, and cost; trace the steps needed to diagnose failures.
- Deploy gradually. Monitor quality, latency, cost, and incidents, with human review and a rollback path for model or prompt changes.
Python LLM glossary
| Term | Meaning in an application |
|---|---|
| A2A | Agent-to-agent protocols and patterns for delegating work across separate agents or services. |
| API | An interface through which Python requests data or functionality from a model provider or another service. |
| Agent | An application pattern in which a model can choose bounded next steps, often including tools. |
| Embedding | A vector representation of content used to compare similarity and retrieve related items. |
| Fine-tuning | Further training on curated examples to adapt behavior or task performance; it does not replace retrieval for changing facts. |
| Hallucination | A plausible-sounding generated claim that is unsupported or incorrect. |
| Harness | The runtime around an agent: state, context management, tool execution, limits, approvals, persistence, and observability. |
| MCP | Model Context Protocol, a standard for connecting AI applications with compatible tools, data sources, and workflows. |
| Prompt injection | Instructions in user or external content that try to override application behavior or trigger unsafe actions. |
| RAG | Retrieval-Augmented Generation: retrieve relevant evidence and supply it as context to a generative model. |
| Reranker | A model or component that reorders candidate search results by relevance to a query. |
| Tool calling | A model request for a typed application function; Python code still validates, authorizes, and runs it. |
| Vector database | A database or index that stores vectors and supports similarity search, often with metadata filters. |
Official documentation
Provider model catalogs, framework APIs, integrations, and pricing change. Check the current official documentation and verify the feature set for the exact versions and provider you deploy.
Agent frameworks and Python tooling
- LangGraph · graph workflows, state, and agent control.
- CrewAI · agents, tasks, Crews, and Flows.
- OpenAI Agents SDK · agents, tools, handoffs, sessions, and tracing.
- Pydantic AI · typed agents and model integrations.
- AutoGen AgentChat · tool-using and conversational agents.
- Microsoft Agent Framework · agents, harnesses, workflows, and integrations.
- LangChain · model, prompt, and tool integrations.
- LlamaIndex · document loading, indexing, and RAG.
- Haystack · composable retrieval and generation pipelines.
- Semantic Kernel for Python · plugins and model services.
- DSPy · composable and optimizable LLM programs.
Retrieval, protocols, and providers
- Qdrant Python quickstart · vectors, payloads, and filtered search.
- Chroma getting started · local collections and semantic queries.
- Pinecone quickstart · managed vector search.
- Weaviate Python client · collections and vector search.
- Milvus quickstart · vector search with Milvus and Zilliz.
- pgvector · vector similarity search in PostgreSQL.
- Model Context Protocol · MCP concepts and architecture.
- MCP Python SDK · building Python MCP clients and servers.
- OpenAI API documentation · Responses, tools, embeddings, and model capabilities.