Skip to content

Commit e519d39

Browse files
authored
Merge pull request #36 from james-see/feature/llm-ai-examples
Add LLM and AI workflow examples (fixes #34)
2 parents fec3ed7 + 0a5262f commit e519d39

File tree

8 files changed

+1220
-0
lines changed

8 files changed

+1220
-0
lines changed

.env.example

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# API Keys for LLM/AI Examples
2+
# Copy this file to .env and add your actual API keys
3+
4+
# OpenAI API Key
5+
# Get yours at: https://platform.openai.com/api-keys
6+
OPENAI_API_KEY=sk-...
7+
8+
# Anthropic API Key
9+
# Get yours at: https://console.anthropic.com/
10+
ANTHROPIC_API_KEY=sk-ant-...
11+
12+
# Hugging Face API Token
13+
# Get yours at: https://huggingface.co/settings/tokens
14+
HUGGINGFACE_API_TOKEN=hf_...
15+
16+
# Pinecone API Key (for vector database examples)
17+
# Get yours at: https://app.pinecone.io/
18+
PINECONE_API_KEY=...
19+
PINECONE_ENVIRONMENT=...
20+
21+
# Other API keys as needed
22+
# Add additional API keys here for other services

README.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,86 @@ uv run isort .
5656
- **tests/**: Test files
5757
- **.github/workflows/**: GitHub Actions for CI/CD
5858

59+
## 🤖 LLM & AI Examples
60+
61+
Modern examples for working with Large Language Models and AI workflows.
62+
63+
### API Configuration
64+
65+
Create a `.env` file in the project root (see `.env.example` for template):
66+
67+
```bash
68+
OPENAI_API_KEY=sk-...
69+
ANTHROPIC_API_KEY=sk-ant-...
70+
```
71+
72+
### Available Examples
73+
74+
**OpenAI GPT** (`openai_gpt-example.py`)
75+
- Chat completions with GPT-4 and GPT-3.5
76+
- Streaming responses
77+
- Function calling (tool use)
78+
- System prompts and conversation memory
79+
- JSON mode for structured outputs
80+
- [Get API key](https://platform.openai.com/api-keys)
81+
82+
**Anthropic Claude** (`anthropic_claude-example.py`)
83+
- Claude 3.5 Sonnet, Opus, and Haiku
84+
- Streaming and multi-turn conversations
85+
- Vision capabilities
86+
- Extended thinking for complex reasoning
87+
- Response prefill for guided outputs
88+
- [Get API key](https://console.anthropic.com/)
89+
90+
**LangChain** (`langchain-example.py`)
91+
- Prompt templates and chains
92+
- Conversation memory
93+
- Structured output parsing with Pydantic
94+
- RAG (Retrieval-Augmented Generation) patterns
95+
- Few-shot prompting
96+
- Sequential chains
97+
- [LangChain Docs](https://python.langchain.com/)
98+
99+
**Instructor** (`instructor-example.py`)
100+
- Type-safe structured outputs
101+
- Pydantic model validation
102+
- List and nested model extraction
103+
- Classification and sentiment analysis
104+
- Chain of thought reasoning
105+
- Streaming structured outputs
106+
- [Instructor Docs](https://python.useinstructor.com/)
107+
108+
### Dependencies
109+
110+
```bash
111+
# Install all LLM dependencies
112+
uv sync
113+
114+
# Or install specific packages
115+
uv add openai anthropic langchain langchain-openai instructor python-dotenv
116+
```
117+
118+
### Usage Examples
119+
120+
```bash
121+
# OpenAI GPT examples
122+
cd python-examples
123+
python openai_gpt-example.py
124+
125+
# Anthropic Claude examples
126+
python anthropic_claude-example.py
127+
128+
# LangChain framework
129+
python langchain-example.py
130+
131+
# Instructor for structured outputs
132+
python instructor-example.py
133+
```
134+
135+
---
136+
137+
## 📚 Classic Python Examples
138+
59139
**urllib** (built-in to python3)
60140

61141
1. [access foursquare API](#foursquare-api-example)

pyproject.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,14 @@ dependencies = [
4343
"numpy>=1.26.0",
4444
"grpcio>=1.68.0",
4545
"grpcio-tools>=1.68.0",
46+
# LLM/AI Libraries
47+
"openai>=1.59.0",
48+
"anthropic>=0.42.0",
49+
"langchain>=0.3.0",
50+
"langchain-openai>=0.2.0",
51+
"langchain-community>=0.3.0",
52+
"instructor>=1.7.0",
53+
"python-dotenv>=1.0.0",
4654
]
4755

4856
[tool.uv]
Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Anthropic Claude API Example
4+
Demonstrates using the Anthropic API with Claude models.
5+
6+
Requirements:
7+
pip install anthropic python-dotenv
8+
9+
Setup:
10+
1. Create a .env file in the project root
11+
2. Add your Anthropic API key: ANTHROPIC_API_KEY=sk-ant-...
12+
3. Get your API key at: https://console.anthropic.com/
13+
"""
14+
15+
import os
16+
from dotenv import load_dotenv
17+
from anthropic import Anthropic
18+
19+
# Load environment variables
20+
load_dotenv()
21+
22+
# Initialize Anthropic client
23+
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
24+
25+
26+
def simple_message():
27+
"""Basic message example with Claude."""
28+
print("=" * 60)
29+
print("1. Simple Message")
30+
print("=" * 60)
31+
32+
message = client.messages.create(
33+
model="claude-3-5-sonnet-20241022", # or "claude-3-opus-20240229", "claude-3-haiku-20240307"
34+
max_tokens=1024,
35+
messages=[
36+
{"role": "user", "content": "Explain machine learning in one sentence."}
37+
]
38+
)
39+
40+
print(f"User: Explain machine learning in one sentence.")
41+
print(f"Claude: {message.content[0].text}\n")
42+
print(f"Tokens - Input: {message.usage.input_tokens}, Output: {message.usage.output_tokens}")
43+
print(f"Model: {message.model}\n")
44+
45+
46+
def streaming_response():
47+
"""Stream responses from Claude."""
48+
print("=" * 60)
49+
print("2. Streaming Response")
50+
print("=" * 60)
51+
52+
print("User: Write a haiku about artificial intelligence.\n")
53+
print("Claude: ", end="", flush=True)
54+
55+
with client.messages.stream(
56+
model="claude-3-5-sonnet-20241022",
57+
max_tokens=1024,
58+
messages=[
59+
{"role": "user", "content": "Write a haiku about artificial intelligence."}
60+
]
61+
) as stream:
62+
for text in stream.text_stream:
63+
print(text, end="", flush=True)
64+
print("\n")
65+
66+
67+
def system_prompt():
68+
"""Use system prompts to set Claude's behavior."""
69+
print("=" * 60)
70+
print("3. System Prompt")
71+
print("=" * 60)
72+
73+
message = client.messages.create(
74+
model="claude-3-5-sonnet-20241022",
75+
max_tokens=1024,
76+
system="You are a helpful Python expert who explains concepts clearly and concisely.",
77+
messages=[
78+
{"role": "user", "content": "What is a decorator?"}
79+
]
80+
)
81+
82+
print("System: You are a helpful Python expert...")
83+
print("User: What is a decorator?")
84+
print(f"Claude: {message.content[0].text}\n")
85+
86+
87+
def multi_turn_conversation():
88+
"""Demonstrate multi-turn conversations with Claude."""
89+
print("=" * 60)
90+
print("4. Multi-turn Conversation")
91+
print("=" * 60)
92+
93+
message = client.messages.create(
94+
model="claude-3-5-sonnet-20241022",
95+
max_tokens=1024,
96+
messages=[
97+
{"role": "user", "content": "I'm learning Python. What should I learn first?"},
98+
{"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?"},
99+
{"role": "user", "content": "Yes, explain functions please."}
100+
]
101+
)
102+
103+
print("User: I'm learning Python. What should I learn first?")
104+
print("Claude: [previous response about fundamentals]")
105+
print("\nUser: Yes, explain functions please.")
106+
print(f"Claude: {message.content[0].text}\n")
107+
108+
109+
def with_vision():
110+
"""Use Claude's vision capabilities (if using a vision-enabled model)."""
111+
print("=" * 60)
112+
print("5. Vision Example (Placeholder)")
113+
print("=" * 60)
114+
115+
# Note: This requires an image URL or base64 encoded image
116+
print("Claude supports vision! You can send images like this:")
117+
print("""
118+
message = client.messages.create(
119+
model="claude-3-5-sonnet-20241022",
120+
max_tokens=1024,
121+
messages=[
122+
{
123+
"role": "user",
124+
"content": [
125+
{
126+
"type": "image",
127+
"source": {
128+
"type": "url",
129+
"url": "https://example.com/image.jpg"
130+
}
131+
},
132+
{
133+
"type": "text",
134+
"text": "What's in this image?"
135+
}
136+
]
137+
}
138+
]
139+
)
140+
""")
141+
print()
142+
143+
144+
def thinking_mode():
145+
"""Demonstrate extended thinking for complex problems."""
146+
print("=" * 60)
147+
print("6. Complex Reasoning")
148+
print("=" * 60)
149+
150+
message = client.messages.create(
151+
model="claude-3-5-sonnet-20241022",
152+
max_tokens=2048,
153+
temperature=1.0,
154+
messages=[
155+
{
156+
"role": "user",
157+
"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?"
158+
}
159+
]
160+
)
161+
162+
print("User: [Logic puzzle about mislabeled fruit boxes]")
163+
print(f"Claude: {message.content[0].text}\n")
164+
165+
166+
def with_prefill():
167+
"""Use prefill to guide Claude's response format."""
168+
print("=" * 60)
169+
print("7. Response Prefill")
170+
print("=" * 60)
171+
172+
message = client.messages.create(
173+
model="claude-3-5-sonnet-20241022",
174+
max_tokens=1024,
175+
messages=[
176+
{"role": "user", "content": "What are the three laws of robotics?"},
177+
{"role": "assistant", "content": "The Three Laws of Robotics are:\n\n1."}
178+
]
179+
)
180+
181+
print("User: What are the three laws of robotics?")
182+
print(f"Claude: The Three Laws of Robotics are:\n\n1.{message.content[0].text}\n")
183+
184+
185+
def error_handling():
186+
"""Demonstrate error handling with Anthropic API."""
187+
print("=" * 60)
188+
print("8. Error Handling")
189+
print("=" * 60)
190+
191+
try:
192+
message = client.messages.create(
193+
model="claude-3-5-sonnet-20241022",
194+
max_tokens=100,
195+
messages=[
196+
{"role": "user", "content": "Hello Claude!"}
197+
]
198+
)
199+
print(f"✓ Success: {message.content[0].text}\n")
200+
201+
except Exception as e:
202+
print(f"✗ Error: {type(e).__name__}")
203+
print(f" Message: {str(e)}\n")
204+
205+
206+
if __name__ == "__main__":
207+
# Check if API key is set
208+
if not os.getenv("ANTHROPIC_API_KEY"):
209+
print("Error: ANTHROPIC_API_KEY not found in environment variables.")
210+
print("Please create a .env file with your API key.")
211+
print("Example: ANTHROPIC_API_KEY=sk-ant-...")
212+
exit(1)
213+
214+
print("\n" + "=" * 60)
215+
print("Anthropic Claude API Examples")
216+
print("=" * 60 + "\n")
217+
218+
try:
219+
simple_message()
220+
streaming_response()
221+
system_prompt()
222+
multi_turn_conversation()
223+
with_vision()
224+
thinking_mode()
225+
with_prefill()
226+
error_handling()
227+
228+
print("=" * 60)
229+
print("All examples completed successfully!")
230+
print("=" * 60)
231+
232+
except Exception as e:
233+
print(f"\n✗ Error running examples: {e}")
234+
print("Make sure your ANTHROPIC_API_KEY is valid and you have credits.")

0 commit comments

Comments
 (0)