diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e821000 --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +# API Keys for LLM/AI Examples +# Copy this file to .env and add your actual API keys + +# OpenAI API Key +# Get yours at: https://platform.openai.com/api-keys +OPENAI_API_KEY=sk-... + +# Anthropic API Key +# Get yours at: https://console.anthropic.com/ +ANTHROPIC_API_KEY=sk-ant-... + +# Hugging Face API Token +# Get yours at: https://huggingface.co/settings/tokens +HUGGINGFACE_API_TOKEN=hf_... + +# Pinecone API Key (for vector database examples) +# Get yours at: https://app.pinecone.io/ +PINECONE_API_KEY=... +PINECONE_ENVIRONMENT=... + +# Other API keys as needed +# Add additional API keys here for other services diff --git a/README.md b/README.md index f8f9275..300fc38 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,86 @@ uv run isort . - **tests/**: Test files - **.github/workflows/**: GitHub Actions for CI/CD +## šŸ¤– LLM & AI Examples + +Modern examples for working with Large Language Models and AI workflows. + +### API Configuration + +Create a `.env` file in the project root (see `.env.example` for template): + +```bash +OPENAI_API_KEY=sk-... +ANTHROPIC_API_KEY=sk-ant-... +``` + +### Available Examples + +**OpenAI GPT** (`openai_gpt-example.py`) +- Chat completions with GPT-4 and GPT-3.5 +- Streaming responses +- Function calling (tool use) +- System prompts and conversation memory +- JSON mode for structured outputs +- [Get API key](https://platform.openai.com/api-keys) + +**Anthropic Claude** (`anthropic_claude-example.py`) +- Claude 3.5 Sonnet, Opus, and Haiku +- Streaming and multi-turn conversations +- Vision capabilities +- Extended thinking for complex reasoning +- Response prefill for guided outputs +- [Get API key](https://console.anthropic.com/) + +**LangChain** (`langchain-example.py`) +- Prompt templates and chains +- Conversation memory +- Structured output parsing with Pydantic +- RAG (Retrieval-Augmented Generation) patterns +- Few-shot prompting +- Sequential chains +- [LangChain Docs](https://python.langchain.com/) + +**Instructor** (`instructor-example.py`) +- Type-safe structured outputs +- Pydantic model validation +- List and nested model extraction +- Classification and sentiment analysis +- Chain of thought reasoning +- Streaming structured outputs +- [Instructor Docs](https://python.useinstructor.com/) + +### Dependencies + +```bash +# Install all LLM dependencies +uv sync + +# Or install specific packages +uv add openai anthropic langchain langchain-openai instructor python-dotenv +``` + +### Usage Examples + +```bash +# OpenAI GPT examples +cd python-examples +python openai_gpt-example.py + +# Anthropic Claude examples +python anthropic_claude-example.py + +# LangChain framework +python langchain-example.py + +# Instructor for structured outputs +python instructor-example.py +``` + +--- + +## šŸ“š Classic Python Examples + **urllib** (built-in to python3) 1. [access foursquare API](#foursquare-api-example) diff --git a/pyproject.toml b/pyproject.toml index ec3c041..89d97f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,14 @@ dependencies = [ "numpy>=1.26.0", "grpcio>=1.68.0", "grpcio-tools>=1.68.0", + # LLM/AI Libraries + "openai>=1.59.0", + "anthropic>=0.42.0", + "langchain>=0.3.0", + "langchain-openai>=0.2.0", + "langchain-community>=0.3.0", + "instructor>=1.7.0", + "python-dotenv>=1.0.0", ] [tool.uv] diff --git a/python-examples/anthropic_claude-example.py b/python-examples/anthropic_claude-example.py new file mode 100644 index 0000000..f69bf3e --- /dev/null +++ b/python-examples/anthropic_claude-example.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +""" +Anthropic Claude API Example +Demonstrates using the Anthropic API with Claude models. + +Requirements: + pip install anthropic python-dotenv + +Setup: + 1. Create a .env file in the project root + 2. Add your Anthropic API key: ANTHROPIC_API_KEY=sk-ant-... + 3. Get your API key at: https://console.anthropic.com/ +""" + +import os +from dotenv import load_dotenv +from anthropic import Anthropic + +# Load environment variables +load_dotenv() + +# Initialize Anthropic client +client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) + + +def simple_message(): + """Basic message example with Claude.""" + print("=" * 60) + print("1. Simple Message") + print("=" * 60) + + message = client.messages.create( + model="claude-3-5-sonnet-20241022", # or "claude-3-opus-20240229", "claude-3-haiku-20240307" + max_tokens=1024, + messages=[ + {"role": "user", "content": "Explain machine learning in one sentence."} + ] + ) + + print(f"User: Explain machine learning in one sentence.") + print(f"Claude: {message.content[0].text}\n") + print(f"Tokens - Input: {message.usage.input_tokens}, Output: {message.usage.output_tokens}") + print(f"Model: {message.model}\n") + + +def streaming_response(): + """Stream responses from Claude.""" + print("=" * 60) + print("2. Streaming Response") + print("=" * 60) + + print("User: Write a haiku about artificial intelligence.\n") + print("Claude: ", end="", flush=True) + + with client.messages.stream( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[ + {"role": "user", "content": "Write a haiku about artificial intelligence."} + ] + ) as stream: + for text in stream.text_stream: + print(text, end="", flush=True) + print("\n") + + +def system_prompt(): + """Use system prompts to set Claude's behavior.""" + print("=" * 60) + print("3. System Prompt") + print("=" * 60) + + message = client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + system="You are a helpful Python expert who explains concepts clearly and concisely.", + messages=[ + {"role": "user", "content": "What is a decorator?"} + ] + ) + + print("System: You are a helpful Python expert...") + print("User: What is a decorator?") + print(f"Claude: {message.content[0].text}\n") + + +def multi_turn_conversation(): + """Demonstrate multi-turn conversations with Claude.""" + print("=" * 60) + print("4. Multi-turn Conversation") + print("=" * 60) + + message = client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[ + {"role": "user", "content": "I'm learning Python. What should I learn first?"}, + {"role": "assistant", "content": "Great! Start with these fundamentals:\n1. Variables and data types\n2. Control flow (if/else, loops)\n3. Functions\n4. Lists and dictionaries\n\nWould you like me to explain any of these?"}, + {"role": "user", "content": "Yes, explain functions please."} + ] + ) + + print("User: I'm learning Python. What should I learn first?") + print("Claude: [previous response about fundamentals]") + print("\nUser: Yes, explain functions please.") + print(f"Claude: {message.content[0].text}\n") + + +def with_vision(): + """Use Claude's vision capabilities (if using a vision-enabled model).""" + print("=" * 60) + print("5. Vision Example (Placeholder)") + print("=" * 60) + + # Note: This requires an image URL or base64 encoded image + print("Claude supports vision! You can send images like this:") + print(""" + message = client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[ + { + "role": "user", + "content": [ + { + "type": "image", + "source": { + "type": "url", + "url": "https://example.com/image.jpg" + } + }, + { + "type": "text", + "text": "What's in this image?" + } + ] + } + ] + ) + """) + print() + + +def thinking_mode(): + """Demonstrate extended thinking for complex problems.""" + print("=" * 60) + print("6. Complex Reasoning") + print("=" * 60) + + message = client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=2048, + temperature=1.0, + messages=[ + { + "role": "user", + "content": "Solve this logic puzzle: There are 3 boxes. One contains only apples, one contains only oranges, and one contains both. All boxes are labeled incorrectly. You can pick one fruit from one box. How do you correctly label all boxes?" + } + ] + ) + + print("User: [Logic puzzle about mislabeled fruit boxes]") + print(f"Claude: {message.content[0].text}\n") + + +def with_prefill(): + """Use prefill to guide Claude's response format.""" + print("=" * 60) + print("7. Response Prefill") + print("=" * 60) + + message = client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[ + {"role": "user", "content": "What are the three laws of robotics?"}, + {"role": "assistant", "content": "The Three Laws of Robotics are:\n\n1."} + ] + ) + + print("User: What are the three laws of robotics?") + print(f"Claude: The Three Laws of Robotics are:\n\n1.{message.content[0].text}\n") + + +def error_handling(): + """Demonstrate error handling with Anthropic API.""" + print("=" * 60) + print("8. Error Handling") + print("=" * 60) + + try: + message = client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=100, + messages=[ + {"role": "user", "content": "Hello Claude!"} + ] + ) + print(f"āœ“ Success: {message.content[0].text}\n") + + except Exception as e: + print(f"āœ— Error: {type(e).__name__}") + print(f" Message: {str(e)}\n") + + +if __name__ == "__main__": + # Check if API key is set + if not os.getenv("ANTHROPIC_API_KEY"): + print("Error: ANTHROPIC_API_KEY not found in environment variables.") + print("Please create a .env file with your API key.") + print("Example: ANTHROPIC_API_KEY=sk-ant-...") + exit(1) + + print("\n" + "=" * 60) + print("Anthropic Claude API Examples") + print("=" * 60 + "\n") + + try: + simple_message() + streaming_response() + system_prompt() + multi_turn_conversation() + with_vision() + thinking_mode() + with_prefill() + error_handling() + + print("=" * 60) + print("All examples completed successfully!") + print("=" * 60) + + except Exception as e: + print(f"\nāœ— Error running examples: {e}") + print("Make sure your ANTHROPIC_API_KEY is valid and you have credits.") diff --git a/python-examples/instructor-example.py b/python-examples/instructor-example.py new file mode 100644 index 0000000..22dc56b --- /dev/null +++ b/python-examples/instructor-example.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +""" +Instructor Library Example +Demonstrates using Instructor for structured outputs from LLMs. + +Instructor adds type-safety and validation to LLM responses using Pydantic models. + +Requirements: + pip install instructor openai pydantic python-dotenv + +Setup: + 1. Create a .env file in the project root + 2. Add your OpenAI API key: OPENAI_API_KEY=sk-... +""" + +import os +from dotenv import load_dotenv +import instructor +from openai import OpenAI +from pydantic import BaseModel, Field, validator +from typing import List, Optional, Literal +from enum import Enum + +# Load environment variables +load_dotenv() + +# Patch OpenAI client with instructor +client = instructor.from_openai(OpenAI(api_key=os.getenv("OPENAI_API_KEY"))) + + +def basic_extraction(): + """Extract structured data from text.""" + print("=" * 60) + print("1. Basic Data Extraction") + print("=" * 60) + + class UserInfo(BaseModel): + """User information extracted from text.""" + name: str + age: int + email: str + occupation: Optional[str] = None + + text = "John Doe is 30 years old. His email is john@example.com and he works as a software engineer." + + user = client.chat.completions.create( + model="gpt-4o-mini", + response_model=UserInfo, + messages=[ + {"role": "user", "content": f"Extract user information from: {text}"} + ] + ) + + print(f"Input: {text}\n") + print(f"Extracted Data:") + print(f" Name: {user.name}") + print(f" Age: {user.age}") + print(f" Email: {user.email}") + print(f" Occupation: {user.occupation}\n") + + +def with_validation(): + """Use Pydantic validators for data validation.""" + print("=" * 60) + print("2. Data Validation") + print("=" * 60) + + class ValidatedUser(BaseModel): + """User with validated fields.""" + name: str = Field(..., min_length=2) + age: int = Field(..., ge=0, le=120) + email: str + + @validator('email') + def validate_email(cls, v): + if '@' not in v: + raise ValueError('Invalid email format') + return v + + try: + user = client.chat.completions.create( + model="gpt-4o-mini", + response_model=ValidatedUser, + messages=[ + {"role": "user", "content": "Extract: Jane Smith, 25, jane.smith@email.com"} + ] + ) + print(f"āœ“ Valid user extracted:") + print(f" {user.name}, {user.age}, {user.email}\n") + except Exception as e: + print(f"āœ— Validation error: {e}\n") + + +def extract_list(): + """Extract lists of items.""" + print("=" * 60) + print("3. List Extraction") + print("=" * 60) + + class Task(BaseModel): + """A single task.""" + title: str + priority: Literal["high", "medium", "low"] + estimated_hours: Optional[int] = None + + class TaskList(BaseModel): + """List of tasks.""" + tasks: List[Task] + + text = """ + I need to: + 1. Fix the authentication bug (urgent, 3 hours) + 2. Write documentation (medium priority) + 3. Review pull requests (low priority, 1 hour) + """ + + result = client.chat.completions.create( + model="gpt-4o-mini", + response_model=TaskList, + messages=[ + {"role": "user", "content": f"Extract tasks from: {text}"} + ] + ) + + print("Extracted Tasks:") + for i, task in enumerate(result.tasks, 1): + hours = f" ({task.estimated_hours}h)" if task.estimated_hours else "" + print(f" {i}. {task.title} - Priority: {task.priority}{hours}") + print() + + +def nested_models(): + """Work with nested Pydantic models.""" + print("=" * 60) + print("4. Nested Models") + print("=" * 60) + + class Address(BaseModel): + """Address information.""" + street: str + city: str + country: str + postal_code: Optional[str] = None + + class Company(BaseModel): + """Company information.""" + name: str + employees: int + address: Address + founded: int + + text = "Microsoft was founded in 1975 and has about 220,000 employees. They're located at One Microsoft Way, Redmond, USA." + + company = client.chat.completions.create( + model="gpt-4o-mini", + response_model=Company, + messages=[ + {"role": "user", "content": f"Extract company info from: {text}"} + ] + ) + + print(f"Company: {company.name}") + print(f"Employees: {company.employees:,}") + print(f"Founded: {company.founded}") + print(f"Location: {company.address.city}, {company.address.country}\n") + + +def classification_task(): + """Use enums for classification.""" + print("=" * 60) + print("5. Text Classification") + print("=" * 60) + + class Category(str, Enum): + """Content categories.""" + TECHNOLOGY = "technology" + BUSINESS = "business" + SCIENCE = "science" + HEALTH = "health" + ENTERTAINMENT = "entertainment" + + class Classification(BaseModel): + """Text classification result.""" + category: Category + confidence: float = Field(..., ge=0.0, le=1.0) + keywords: List[str] + + texts = [ + "New AI model achieves breakthrough in natural language processing", + "Stock market reaches all-time high as tech companies lead gains" + ] + + for text in texts: + result = client.chat.completions.create( + model="gpt-4o-mini", + response_model=Classification, + messages=[ + {"role": "user", "content": f"Classify this text: {text}"} + ] + ) + print(f"Text: {text[:50]}...") + print(f"Category: {result.category.value}") + print(f"Confidence: {result.confidence:.2%}") + print(f"Keywords: {', '.join(result.keywords)}\n") + + +def sentiment_analysis(): + """Structured sentiment analysis.""" + print("=" * 60) + print("6. Sentiment Analysis") + print("=" * 60) + + class Sentiment(BaseModel): + """Sentiment analysis result.""" + sentiment: Literal["positive", "negative", "neutral"] + score: float = Field(..., ge=-1.0, le=1.0, description="Sentiment score from -1 to 1") + aspects: Optional[List[str]] = Field(None, description="Aspects mentioned") + + reviews = [ + "I love this product! The quality is amazing and customer service was great.", + "Disappointed with the purchase. Poor quality and slow shipping." + ] + + for review in reviews: + result = client.chat.completions.create( + model="gpt-4o-mini", + response_model=Sentiment, + messages=[ + {"role": "user", "content": f"Analyze sentiment: {review}"} + ] + ) + print(f"Review: {review}") + print(f"Sentiment: {result.sentiment} (score: {result.score:+.2f})") + if result.aspects: + print(f"Aspects: {', '.join(result.aspects)}") + print() + + +def chain_of_thought(): + """Include reasoning in structured output.""" + print("=" * 60) + print("7. Chain of Thought") + print("=" * 60) + + class MathSolution(BaseModel): + """Math problem solution with reasoning.""" + reasoning: str = Field(..., description="Step-by-step reasoning") + answer: int = Field(..., description="Final answer") + + problem = "If a train travels 60 miles per hour for 2.5 hours, how far does it travel?" + + solution = client.chat.completions.create( + model="gpt-4o-mini", + response_model=MathSolution, + messages=[ + {"role": "user", "content": f"Solve this problem step by step: {problem}"} + ] + ) + + print(f"Problem: {problem}\n") + print(f"Reasoning: {solution.reasoning}\n") + print(f"Answer: {solution.answer} miles\n") + + +def partial_responses(): + """Handle partial/streaming responses.""" + print("=" * 60) + print("8. Streaming Structured Output") + print("=" * 60) + + class Article(BaseModel): + """Article with title and content.""" + title: str + author: str + summary: str + tags: List[str] + + print("Generating article (streaming)...\n") + + article_stream = client.chat.completions.create_partial( + model="gpt-4o-mini", + response_model=Article, + messages=[ + {"role": "user", "content": "Write a short article about Python programming"} + ], + stream=True + ) + + for partial_article in article_stream: + # In a real app, you'd update UI with partial results + pass + + # Final result + print(f"Title: {partial_article.title}") + print(f"Author: {partial_article.author}") + print(f"Summary: {partial_article.summary[:100]}...") + print(f"Tags: {', '.join(partial_article.tags)}\n") + + +if __name__ == "__main__": + # Check if API key is set + if not os.getenv("OPENAI_API_KEY"): + print("Error: OPENAI_API_KEY not found in environment variables.") + print("Please create a .env file with your API key.") + exit(1) + + print("\n" + "=" * 60) + print("Instructor - Structured Outputs from LLMs") + print("=" * 60 + "\n") + + try: + basic_extraction() + with_validation() + extract_list() + nested_models() + classification_task() + sentiment_analysis() + chain_of_thought() + partial_responses() + + print("=" * 60) + print("All examples completed successfully!") + print("=" * 60) + + except Exception as e: + print(f"\nāœ— Error running examples: {e}") + print("Make sure your OPENAI_API_KEY is valid.") diff --git a/python-examples/langchain-example.py b/python-examples/langchain-example.py new file mode 100644 index 0000000..14be8a7 --- /dev/null +++ b/python-examples/langchain-example.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +""" +LangChain Framework Example +Demonstrates using LangChain for building LLM applications. + +Requirements: + pip install langchain langchain-openai langchain-community python-dotenv + +Setup: + 1. Create a .env file in the project root + 2. Add your OpenAI API key: OPENAI_API_KEY=sk-... +""" + +import os +from dotenv import load_dotenv +from langchain_openai import ChatOpenAI +from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder +from langchain.schema import HumanMessage, SystemMessage, AIMessage +from langchain.chains import LLMChain +from langchain.memory import ConversationBufferMemory +from langchain.output_parsers import PydanticOutputParser +from pydantic import BaseModel, Field +from typing import List + +# Load environment variables +load_dotenv() + + +def basic_llm_call(): + """Simple LLM call with LangChain.""" + print("=" * 60) + print("1. Basic LLM Call") + print("=" * 60) + + llm = ChatOpenAI( + model="gpt-4o-mini", + temperature=0.7, + api_key=os.getenv("OPENAI_API_KEY") + ) + + messages = [ + SystemMessage(content="You are a helpful AI assistant."), + HumanMessage(content="What is LangChain?") + ] + + response = llm.invoke(messages) + print(f"User: What is LangChain?") + print(f"Assistant: {response.content}\n") + + +def prompt_template_example(): + """Use prompt templates for reusable prompts.""" + print("=" * 60) + print("2. Prompt Templates") + print("=" * 60) + + llm = ChatOpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY")) + + template = ChatPromptTemplate.from_messages([ + ("system", "You are a {expertise} expert."), + ("human", "{question}") + ]) + + chain = template | llm + + result = chain.invoke({ + "expertise": "Python programming", + "question": "What is a decorator?" + }) + + print("Template: You are a {expertise} expert.") + print("Question: What is a decorator?") + print(f"Response: {result.content}\n") + + +def conversation_with_memory(): + """Maintain conversation memory.""" + print("=" * 60) + print("3. Conversation Memory") + print("=" * 60) + + llm = ChatOpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY")) + + memory = ConversationBufferMemory(return_messages=True) + + prompt = ChatPromptTemplate.from_messages([ + ("system", "You are a helpful coding assistant."), + MessagesPlaceholder(variable_name="history"), + ("human", "{input}") + ]) + + conversation = [ + "What is a list comprehension in Python?", + "Show me an example", + "How is it different from a map function?" + ] + + for user_input in conversation: + # Get chat history + history = memory.load_memory_variables({}) + + # Create chain + chain = prompt | llm + + # Get response + response = chain.invoke({ + "history": history.get("history", []), + "input": user_input + }) + + # Save to memory + memory.save_context({"input": user_input}, {"output": response.content}) + + print(f"User: {user_input}") + print(f"Assistant: {response.content[:200]}...\n") + + +def structured_output_parsing(): + """Parse LLM output into structured data.""" + print("=" * 60) + print("4. Structured Output Parsing") + print("=" * 60) + + # Define output structure + class Recipe(BaseModel): + """Recipe information.""" + name: str = Field(description="Name of the dish") + ingredients: List[str] = Field(description="List of ingredients") + steps: List[str] = Field(description="Cooking steps") + prep_time: int = Field(description="Preparation time in minutes") + + # Set up parser + parser = PydanticOutputParser(pydantic_object=Recipe) + + llm = ChatOpenAI(model="gpt-4o-mini", temperature=0, api_key=os.getenv("OPENAI_API_KEY")) + + prompt = ChatPromptTemplate.from_messages([ + ("system", "You are a helpful cooking assistant."), + ("human", "{query}\n\n{format_instructions}") + ]) + + chain = prompt | llm | parser + + result = chain.invoke({ + "query": "Give me a simple pasta recipe", + "format_instructions": parser.get_format_instructions() + }) + + print("Query: Give me a simple pasta recipe\n") + print(f"Recipe Name: {result.name}") + print(f"Prep Time: {result.prep_time} minutes") + print(f"Ingredients: {', '.join(result.ingredients[:3])}...") + print(f"Steps: {len(result.steps)} steps\n") + + +def simple_rag_example(): + """Simple Retrieval-Augmented Generation example.""" + print("=" * 60) + print("5. Simple RAG Pattern") + print("=" * 60) + + # Simulate document retrieval + documents = [ + "LangChain is a framework for developing applications powered by language models.", + "It enables applications that are context-aware and can reason based on provided context.", + "LangChain provides components for working with LLMs, prompts, memory, and agents." + ] + + llm = ChatOpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY")) + + # Create RAG prompt + rag_prompt = ChatPromptTemplate.from_messages([ + ("system", "Answer the question based on the following context:\n\n{context}"), + ("human", "{question}") + ]) + + chain = rag_prompt | llm + + question = "What does LangChain enable?" + context = "\n".join(documents) + + response = chain.invoke({ + "context": context, + "question": question + }) + + print(f"Context: [3 documents about LangChain]") + print(f"Question: {question}") + print(f"Answer: {response.content}\n") + + +def few_shot_prompting(): + """Demonstrate few-shot learning with examples.""" + print("=" * 60) + print("6. Few-Shot Prompting") + print("=" * 60) + + llm = ChatOpenAI(model="gpt-4o-mini", temperature=0, api_key=os.getenv("OPENAI_API_KEY")) + + few_shot_prompt = ChatPromptTemplate.from_messages([ + ("system", "You are a sentiment classifier. Respond with only: positive, negative, or neutral."), + ("human", "I love this product!"), + ("ai", "positive"), + ("human", "This is terrible."), + ("ai", "negative"), + ("human", "It's okay, nothing special."), + ("ai", "neutral"), + ("human", "{text}") + ]) + + chain = few_shot_prompt | llm + + test_cases = [ + "This is amazing!", + "I'm disappointed.", + "It works as expected." + ] + + print("Few-shot sentiment classification:\n") + for text in test_cases: + result = chain.invoke({"text": text}) + print(f"Text: '{text}'") + print(f"Sentiment: {result.content}\n") + + +def chain_multiple_calls(): + """Chain multiple LLM calls together.""" + print("=" * 60) + print("7. Sequential Chains") + print("=" * 60) + + llm = ChatOpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY")) + + # First chain: Generate a topic + topic_prompt = ChatPromptTemplate.from_messages([ + ("system", "Generate a random technical topic in one word."), + ("human", "Give me a topic") + ]) + + # Second chain: Explain the topic + explain_prompt = ChatPromptTemplate.from_messages([ + ("system", "Explain the following topic in one sentence."), + ("human", "{topic}") + ]) + + topic_chain = topic_prompt | llm + explain_chain = explain_prompt | llm + + # Execute chains + topic_response = topic_chain.invoke({}) + topic = topic_response.content.strip() + + explanation = explain_chain.invoke({"topic": topic}) + + print(f"Generated Topic: {topic}") + print(f"Explanation: {explanation.content}\n") + + +if __name__ == "__main__": + # Check if API key is set + if not os.getenv("OPENAI_API_KEY"): + print("Error: OPENAI_API_KEY not found in environment variables.") + print("Please create a .env file with your API key.") + exit(1) + + print("\n" + "=" * 60) + print("LangChain Examples") + print("=" * 60 + "\n") + + try: + basic_llm_call() + prompt_template_example() + conversation_with_memory() + structured_output_parsing() + simple_rag_example() + few_shot_prompting() + chain_multiple_calls() + + print("=" * 60) + print("All examples completed successfully!") + print("=" * 60) + + except Exception as e: + print(f"\nāœ— Error running examples: {e}") + print("Make sure your OPENAI_API_KEY is valid.") diff --git a/python-examples/openai_gpt-example.py b/python-examples/openai_gpt-example.py new file mode 100644 index 0000000..c5d1714 --- /dev/null +++ b/python-examples/openai_gpt-example.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +""" +OpenAI GPT API Example +Demonstrates using the OpenAI API with GPT models for various tasks. + +Requirements: + pip install openai python-dotenv + +Setup: + 1. Create a .env file in the project root + 2. Add your OpenAI API key: OPENAI_API_KEY=sk-... + 3. Get your API key at: https://platform.openai.com/api-keys +""" + +import os +from dotenv import load_dotenv +from openai import OpenAI + +# Load environment variables +load_dotenv() + +# Initialize OpenAI client +client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) + + +def simple_chat_completion(): + """Basic chat completion example.""" + print("=" * 60) + print("1. Simple Chat Completion") + print("=" * 60) + + response = client.chat.completions.create( + model="gpt-4o-mini", # or "gpt-4", "gpt-3.5-turbo" + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Explain quantum computing in one sentence."} + ], + temperature=0.7, + max_tokens=150 + ) + + answer = response.choices[0].message.content + print(f"User: Explain quantum computing in one sentence.") + print(f"Assistant: {answer}\n") + print(f"Tokens used: {response.usage.total_tokens}") + print(f"Model: {response.model}\n") + + +def streaming_response(): + """Stream responses token by token.""" + print("=" * 60) + print("2. Streaming Response") + print("=" * 60) + + print("User: Write a haiku about Python programming.\n") + print("Assistant: ", end="", flush=True) + + stream = client.chat.completions.create( + model="gpt-4o-mini", + messages=[ + {"role": "user", "content": "Write a haiku about Python programming."} + ], + stream=True + ) + + for chunk in stream: + if chunk.choices[0].delta.content is not None: + print(chunk.choices[0].delta.content, end="", flush=True) + print("\n") + + +def function_calling(): + """Demonstrate function calling (tool use).""" + print("=" * 60) + print("3. Function Calling") + print("=" * 60) + + # Define a function schema + tools = [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"], + "description": "The temperature unit" + } + }, + "required": ["location"] + } + } + } + ] + + response = client.chat.completions.create( + model="gpt-4o-mini", + messages=[ + {"role": "user", "content": "What's the weather like in Boston?"} + ], + tools=tools, + tool_choice="auto" + ) + + message = response.choices[0].message + + if message.tool_calls: + tool_call = message.tool_calls[0] + print(f"User: What's the weather like in Boston?") + print(f"\nGPT wants to call function: {tool_call.function.name}") + print(f"Arguments: {tool_call.function.arguments}\n") + else: + print(f"Response: {message.content}\n") + + +def system_prompt_example(): + """Show how system prompts affect behavior.""" + print("=" * 60) + print("4. System Prompt Example") + print("=" * 60) + + prompts = [ + ("You are a pirate. Respond in pirate speak.", "How do I write Python code?"), + ("You are a Shakespeare scholar. Use Elizabethan English.", "How do I write Python code?"), + ] + + for system_msg, user_msg in prompts: + response = client.chat.completions.create( + model="gpt-4o-mini", + messages=[ + {"role": "system", "content": system_msg}, + {"role": "user", "content": user_msg} + ], + max_tokens=100, + temperature=0.8 + ) + + print(f"System: {system_msg}") + print(f"User: {user_msg}") + print(f"Assistant: {response.choices[0].message.content}\n") + + +def conversation_with_history(): + """Maintain conversation context.""" + print("=" * 60) + print("5. Multi-turn Conversation") + print("=" * 60) + + messages = [ + {"role": "system", "content": "You are a helpful Python programming tutor."} + ] + + conversation = [ + "What is a list comprehension?", + "Can you show me an example?", + "How is it different from a regular for loop?" + ] + + for user_input in conversation: + messages.append({"role": "user", "content": user_input}) + + response = client.chat.completions.create( + model="gpt-4o-mini", + messages=messages, + max_tokens=150 + ) + + assistant_message = response.choices[0].message.content + messages.append({"role": "assistant", "content": assistant_message}) + + print(f"User: {user_input}") + print(f"Assistant: {assistant_message}\n") + + +def with_json_mode(): + """Use JSON mode for structured outputs.""" + print("=" * 60) + print("6. JSON Mode") + print("=" * 60) + + response = client.chat.completions.create( + model="gpt-4o-mini", + messages=[ + { + "role": "system", + "content": "You are a helpful assistant that outputs JSON." + }, + { + "role": "user", + "content": "Extract the following information in JSON format: Name: John Doe, Age: 30, City: New York" + } + ], + response_format={"type": "json_object"}, + temperature=0 + ) + + print("User: Extract information from: Name: John Doe, Age: 30, City: New York") + print(f"Assistant (JSON): {response.choices[0].message.content}\n") + + +def error_handling(): + """Demonstrate error handling.""" + print("=" * 60) + print("7. Error Handling") + print("=" * 60) + + try: + response = client.chat.completions.create( + model="gpt-4o-mini", + messages=[ + {"role": "user", "content": "Hello!"} + ], + max_tokens=50 + ) + print(f"āœ“ Success: {response.choices[0].message.content}\n") + + except Exception as e: + print(f"āœ— Error: {type(e).__name__}") + print(f" Message: {str(e)}\n") + + +if __name__ == "__main__": + # Check if API key is set + if not os.getenv("OPENAI_API_KEY"): + print("Error: OPENAI_API_KEY not found in environment variables.") + print("Please create a .env file with your API key.") + print("Example: OPENAI_API_KEY=sk-...") + exit(1) + + print("\n" + "=" * 60) + print("OpenAI GPT API Examples") + print("=" * 60 + "\n") + + try: + simple_chat_completion() + streaming_response() + function_calling() + system_prompt_example() + conversation_with_history() + with_json_mode() + error_handling() + + print("=" * 60) + print("All examples completed successfully!") + print("=" * 60) + + except Exception as e: + print(f"\nāœ— Error running examples: {e}") + print("Make sure your OPENAI_API_KEY is valid and you have credits.") diff --git a/requirements.txt b/requirements.txt index 16cdd4a..924f8be 100644 --- a/requirements.txt +++ b/requirements.txt @@ -33,3 +33,10 @@ pillow>=10.3.0 numpy>=1.26.0 grpcio>=1.68.0 grpcio-tools>=1.68.0 +openai>=1.59.0 +anthropic>=0.42.0 +langchain>=0.3.0 +langchain-openai>=0.2.0 +langchain-community>=0.3.0 +instructor>=1.7.0 +python-dotenv>=1.0.0