Grok is an advanced AI model developed by xAI, the artificial intelligence company founded by Elon Musk. Unlike many mainstream language models, Grok is designed to be less restricted and more open in its responses compared to ChatGPT (by OpenAI) or Claude (by Anthropic). It aims to provide an unbiased, truth-seeking AI experience, making it one of the most powerful and distinctive large language models (LLMs) available today. With the Grok model such as Grok 2, you can explore vision capabilities, text to text and more. Grok 2, like its predecessors, is trained to engage in dynamic conversations, answer complex questions, and even generate creative content while maintaining a logical and fact-based approach.
Here’s the evolution:
Now, Grok 3 is here!!!
Read the full coverage here: Grok 3 is Here! And What It Can Do Will Blow Your Mind!
Grok-2 is an enhanced version of the Grok chatbot developed by Elon Musk’s xAI. It is designed to be more user-friendly, adaptable, and proficient in answering questions, assisting with writing, and tackling coding challenges.
Key Features and Capabilities:
As per Elon Musk, Grok-2 will be open-source in the coming days.
One common misconception is that Grok 2 generates images—but it doesn’t. Instead, xAI relies on a separate image model called Flux.
So, while it may seem like Grok is directly creating images, it’s actually leveraging Flux behind the scenes.
Now is the perfect time to start building AI agents with the Grok API because Grok 3 is here—and it might be the best AI model in the world.
Note: In one or two you can access the Grok 3 through API.
Why is Grok 3 so important?
Most people are still using ChatGPT or Claude, meaning Grok is still under the radar. But if Grok 3 proves superior in the coming days, it could rapidly skyrocket in popularity, potentially becoming the world’s leading LLM within a year or two.
As of now, you can access two models:
Firstly, open: https://x.ai/
Click on “Start Building Now” and sign in using your email id.
Add payment method and billing address as required.
This will set your API key for the model you want to use.
Save the API key in the .env file like: GROK_API_KEY = “Your_API_KEY”
import os
from openai import OpenAI
From dotenv import load_dotenv
load_dotenv()
GROK_API_KEY=os.getenv(“GROK_API_KEY”)
client = OpenAI(
api_key= GROK_API_KEY,
base_url="https://api.x.ai/v1",
)
completion = client.chat.completions.create(
model="grok-2-latest",
messages=[
{"role": "system", "content": "You are a Python progamminmg language expert."},
{"role": "user", "content": "How can a beginner read and parse a JSON file in Python? You can teach them using examples"},
],
)
print(completion.choices[0].message.content)
To help a beginner read and parse a JSON file in Python, let's go through the
process step-by-step with examples. We'll use the `json` module, which is
part of Python's standard library, making it easy to work with JSON data.
Here's how you can read and parse a JSON file:
1. First, we need to import the `json` module.
2. Then, we'll open the JSON file and use `json.load()` to parse its contents.
3. Finally, we can access and use the parsed data.
Let's see this in action with an example:
```python
# Import the json module
import json
# Open and read the JSON file
with open('example.json', 'r') as file:
# Parse the JSON data
data = json.load(file)
# Now we can work with the data
print(data)
# Accessing specific elements (assuming the JSON structure)
print(data['name'])
print(data['age'])
# If it's a list of objects
for item in data:
print(f"Name: {item['name']}, Age: {item['age']}")
```
Let's break down what's happening:
1. We import the `json` module, which provides functions to work with JSON
data.
2. We use a `with` statement to open the file. This ensures the file is
properly closed after we're done with it.
3. We use `json.load(file)` to read and parse the JSON data from the file.
This function automatically converts the JSON data into a Python object
(usually a dictionary or a list).
4. After parsing, `data` now contains the JSON content as a Python object. We
can print it or access its elements.
5. Depending on the structure of your JSON, you can access elements using
dictionary syntax (`data['key']`) or list indexing.
Here's an example of what the `example.json` file might look like:
```json
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
```
Or, if it's a list of objects:
```json
[
{"name": "John Doe", "age": 30},
{"name": "Jane Smith", "age": 25}
]
```
For beginners, here are some important points to remember:
- JSON files typically have a `.json` extension.
- JSON data can be a single object (like a dictionary) or an array (like a
list).
- You need to know the structure of your JSON to access its elements
correctly.
- If you encounter errors, it's often because the JSON file is not properly
formatted or you're trying to access elements that don't exist.
To practice, beginners can create their own JSON files and try parsing them.
They can also use online JSON validators to ensure their files are correctly
formatted before attempting to parse them in Python.
if completion.usage:
print(completion.usage.to_json())
{
"completion_tokens": 713,
"prompt_tokens": 40,
"total_tokens": 753,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 0,
"text_tokens": 40,
"image_tokens": 0
}
}
Cost of Input (Prompt Tokens)
Total Cost for This Request
So, this request costs approximately $0.00721 (or about 0.72 cents).
import os
from openai import OpenAI
from getpass import getpass
XAI_KEY = getpass('Enter Grok API Key: ')
os.environ['XAI_API_KEY'] = XAI_KEY
image_url = (
"https://safarisafricana.com/wp-content/uploads/2020/05/Copy-of-SAFAF-2X1-images-60.jpg"
)
client = OpenAI(
api_key=XAI_KEY,
base_url="https://api.x.ai/v1",
)
messages = [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": image_url,
"detail": "high",
},
},
{
"type": "text",
"text": """Please provide a detailed description of the contents in this image, including any notable objects, colors, patterns, and the overall scene.
If there are any texts or symbols, please transcribe or interpret them as well.""",
},
],
},
]
completion = client.chat.completions.create(
model="grok-2-vision-latest",
messages=messages,
temperature=0.01,
)
print(completion.choices[0].message.content)
Input image
The image depicts a vibrant and lush savanna scene, showcasing a variety of
wildlife in their natural habitat. Here is a detailed description:
### Animals:
1. **Giraffes**: There are three giraffes in the image, standing tall with
their long necks and distinctive spotted patterns. Their colors are
primarily light brown with orange-brown patches. They are positioned towards
the center and right side of the image.
2. **Zebras**: Several zebras are present, identifiable by their black and
white striped patterns. They are scattered across the scene, with some
standing and others grazing. Their stripes create a striking contrast
against the green grass.
3. **Antelopes/Deer**: There are multiple antelopes or deer-like animals,
with slender bodies and light brown coats. Some have white underbellies and
legs. They are smaller in size compared to the giraffes and zebras, and are
seen grazing or standing around.
### Vegetation:
- **Grass**: The ground is covered with lush green grass, indicating a
healthy and vibrant ecosystem.
- **Bushes and Trees**: There are various green bushes and small trees
scattered throughout the scene. In the background, there are larger trees,
including one with a broad canopy on the left side of the image.
### Colors:
- **Green**: Dominant color due to the grass, bushes, and trees.
- **Brown**: Seen in the giraffes' patches, antelopes' coats, and some parts
of the zebras.
- **Black and White**: The zebras' stripes.
- **Orange**: Subtle tones in the giraffes' patches.
### Patterns:
- **Giraffe Spots**: Irregular, orange-brown patches on a light brown
background.
- **Zebra Stripes**: Bold, black and white stripes with varying thickness.
- **Antelope/Deer**: Light brown with white underbellies and legs.
### Overall Scene:
The scene is set in a savanna or grassland environment, typical of African
landscapes. The animals are coexisting peacefully, suggesting a harmonious
ecosystem. The lighting suggests it might be daytime, with natural sunlight
illuminating the scene, enhancing the vividness of the colors.
### Texts or Symbols:
There are no visible texts or symbols in the image.
This image captures the essence of wildlife in a natural setting,
highlighting the diversity and beauty of the animals and their environment.
if completion.usage:
print(completion.usage.to_json())
{
"completion_tokens": 483,
"prompt_tokens": 820,
"total_tokens": 1303,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 0,
"text_tokens": 52,
"image_tokens": 768
}
}
Cost of Input (Prompt Tokens)
Cost of Output (Completion Tokens)
Total Cost for this request
So, this request costs approximately $0.00647 (or about 0.65 cents).
!pip install -U openai langchain_xai chainlit
from langchain_xai import ChatXAI
import os
from openai import OpenAI
from getpass import getpass
XAI_KEY = getpass('Enter Grok API Key: ')
os.environ['XAI_API_KEY'] = XAI_KEY
response = ChatXAI(
model="grok-2-latest",
)
for m in response.stream("Give me a plan to complete a half marathon under 2 hours"):
print(m.content, end="", flush=True)
To complete a half marathon under 2 hours, you need to maintain an average
pace of about 9:09 minutes per mile or 5:40 minutes per kilometer. Here's a
structured plan to help you achieve this goal:
### Phase 1: Base Building (Weeks 1-4)
**Objective:** Build endurance and increase weekly mileage gradually.
**Weekly Schedule:**
- **Monday:** Rest or Cross-Training (e.g., swimming, cycling)
- **Tuesday:** 3-4 miles at an easy pace
- **Wednesday:** 4-5 miles at an easy pace
- **Thursday:** 3-4 miles at an easy pace
- **Friday:** Rest or Cross-Training
- **Saturday:** 6-8 miles at an easy pace (Long Run)
- **Sunday:** 3-4 miles at an easy pace
**Tips:**
- Focus on building a solid aerobic base.
- Keep the pace easy and conversational to avoid burnout and injury.
### Phase 2: Building Speed and Endurance (Weeks 5-8)
**Objective:** Introduce speed work and continue increasing weekly mileage.
**Weekly Schedule:**
- **Monday:** Rest or Cross-Training
- **Tuesday:** 4-5 miles with intervals (e.g., 4 x 800m at 5K pace, with 400m jog recovery)
- **Wednesday:** 5-6 miles at an easy pace
- **Thursday:** 4-5 miles with tempo run (e.g., 2 miles at half marathon
pace)
- **Friday:** Rest or Cross-Training
- **Saturday:** 8-10 miles at an easy pace (Long Run)
- **Sunday:** 4-5 miles at an easy pace
**Tips:**
- Gradually increase the intensity of your workouts.
- Use the long runs to practice hydration and fueling strategies.
### Phase 3: Peak Training (Weeks 9-12)
**Objective:** Maximize fitness and simulate race conditions.
**Weekly Schedule:**
- **Monday:** Rest or Cross-Training
- **Tuesday:** 5-6 miles with intervals (e.g., 6 x 800m at 5K pace, with 400m
jog recovery)
- **Wednesday:** 6-7 miles at an easy pace
- **Thursday:** 5-6 miles with tempo run (e.g., 3 miles at half marathon
pace)
- **Friday:** Rest or Cross-Training
- **Saturday:** 10-12 miles at an easy pace (Long Run)
- **Sunday:** 5-6 miles at an easy pace
**Tips:**
- Include a few longer tempo runs to build stamina at race pace.
- Practice your race day nutrition and hydration during long runs.
### Phase 4: Taper and Race (Weeks 13-14)
**Objective:** Reduce mileage to allow recovery and peak performance on race
day.
**Weekly Schedule:**
- **Monday:** Rest or Cross-Training
- **Tuesday:** 4-5 miles with intervals (e.g., 4 x 800m at 5K pace, with 400m
jog recovery)
- **Wednesday:** 4-5 miles at an easy pace
- **Thursday:** 3-4 miles at an easy pace
- **Friday:** Rest
- **Saturday:** 2-3 miles at an easy pace
- **Sunday:** Race Day (Half Marathon)
**Tips:**
- Reduce mileage to ensure you are fresh and rested for race day.
- Focus on hydration and nutrition in the days leading up to the race.
### Race Day Strategy
- **Warm-Up:** Do a light 10-15 minute jog and some dynamic stretches.
- **Pacing:** Start at a comfortable pace and aim to run each mile in about
9:09. Use the first few miles to settle into your rhythm.
- **Hydration and Fueling:** Drink at water stations and consume any gels or
energy chews you've practiced with during training.
- **Mental Focus:** Break the race into segments (e.g., every 5K) and focus
on maintaining your pace through each one.
### Additional Tips
- **Injury Prevention:** Incorporate strength training and stretching to
prevent injuries.
- **Rest and Recovery:** Ensure you get enough sleep and consider recovery
techniques like foam rolling and massages.
- **Nutrition:** Maintain a balanced diet with adequate carbohydrates,
proteins, and fats to fuel your training.
By following this plan and staying consistent with your training, you should
be well-prepared to complete a half marathon in under 2 hours. Good luck!
pip install -U openai langchain_xai chainlit
from langchain_xai import ChatXAI
import os
from openai import OpenAI
from getpass import getpass
XAI_KEY = getpass('Enter Grok API Key: ')
os.environ['XAI_API_KEY'] = XAI_KEY
response = ChatXAI(
model="grok-2-latest",
)
while True:
text = input(">>> Your Message:")
answer = response.invoke(text)
print(answer.content)
>>> Your Message:Hi, who are you?
I'm Grok, an AI developed by xAI. I'm here to provide helpful and truthful
answers to your questions, often with a dash of outside perspective on
humanity. Think of me as a friendly, cosmic guide, inspired by the likes of
the Hitchhiker's Guide to the Galaxy and JARVIS from Iron Man. What's on
your mind?
>>> Your Message:i want you to give me all the states of India
India is divided into 28 states and 8 union territories. Here is the list of
all the states in India:
1. Andhra Pradesh
2. Arunachal Pradesh
3. Assam
4. Bihar
5. Chhattisgarh
6. Goa
7. Gujarat
8. Haryana
9. Himachal Pradesh
10. Jharkhand
11. Karnataka
12. Kerala
13. Madhya Pradesh
14. Maharashtra
15. Manipur
16. Meghalaya
17. Mizoram
18. Nagaland
19. Odisha
20. Punjab
21. Rajasthan
22. Sikkim
23. Tamil Nadu
24. Telangana
25. Tripura
26. Uttar Pradesh
27. Uttarakhand
28. West Bengal
If you need information about the union territories as well, please let me
know!
>>> Your Message:now give me union territories
Here is a list of the Union Territories of India:
1. **Andaman and Nicobar Islands**
2. **Chandigarh**
3. **Dadra and Nagar Haveli and Daman and Diu**
4. **Delhi (National Capital Territory of Delhi)**
5. **Jammu and Kashmir**
6. **Lakshadweep**
7. **Puducherry**
These Union Territories are administered directly by the Central Government
of India.
>>> Your Message:
With Grok 3’s launch approaching, xAI is rapidly positioning itself as a serious challenger to OpenAI, Google DeepMind, and Anthropic. If xAI’s massive computing power translates into a superior AI model, Grok could dominate the AI space in the next few years. For developers, entrepreneurs, and AI enthusiasts—now is the time to start building with Grok. Early adopters stand to gain a major advantage in what could be the biggest AI revolution yet.
Experience the power of xAI Grok 3, the smartest AI on Earth! Enroll in our course to explore its groundbreaking features and transform your projects today!
I hope you found this article on Grok 2 hands-on informative. Let me know your thoughts in the comment section below.